Unit 1
Unit 1
History of Java
• Java started out as a research project.
• Research began in 1991 as the Green Project at Sun Microsystems, Inc.
• Research efforts birthed a new language, OAK. (A tree outside of the window of James
Gosling’s office at Sun).
• It was developed as an embedded programming language, which would enable
embedded system application.
• It was not really created as web programming language.
• Java is available as jdk and it is an open source s/w.
Language was created with 5 main goals:
Java Platforms
There are three main platforms for Java:
Java Terminology
1. Java Development Kit:
It contains one (or more) JRE's along with the various development tools like the Java source
compilers, bundling and deployment tools, debuggers, development libraries, etc.
2. Java Virtual Machine:
An abstract machine architecture specified by the Java Virtual Machine Specification.
It interprets the byte code into the machine code depending upon the underlying OS and
hardware combination. JVM is platform dependent. (It uses the class libraries, and other
supporting files provided in JRE)
3. Java Runtime Environment:
A runtime environment which implements Java Virtual Machine, and provides all class
libraries and other facilities necessary to execute Java programs. This is the software on your
computer that actually runs Java programs.
JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc) +runtime libraries.
• Class loader subsystem: A mechanism for loading types (classes and interfaces) given
fully qualified names.
• The Java virtual machine organizes the memory it needs to execute a program into
several runtime data areas.
• Each Java virtual machine also has an execution engine: a mechanism responsible for
executing the instructions contained in the methods of loaded classes.
Class loader subsystem
• The Java virtual machine contains two kinds of class loaders: a bootstrap class
loader and user-defined class loaders.
• The bootstrap class loader is a part of the virtual machine implementation, and user-
defined class loaders are part of the running Java application.
• Loading: finding and importing the binary data for a type
• Linking: performing verification, preparation, and (optionally) resolution
• Verification: ensuring the correctness of the imported type
• Preparation: allocating memory for class variables and initializing the memory to
default values
• Resolution: transforming symbolic references from the type into direct references.
• Initialization: invoking Java code that initializes class variables to their proper
starting values.
When the virtual machine loads a class file, it parses information about a type from the binary
data contained in the class file.
It places this type information into the method area. As the program runs, the virtual machine
places all objects the program instantiates onto the heap. As each new thread comes into
existence, it gets its own pc register (program counter) and Java stack.
Byte code is a highly optimized set of instructions designed to be executed by the Java run-
time system, which is called the Java Virtual Machine (JVM). JVM is an interpreter for byte
code.
• Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
• The principle of data hiding helps the programmer to build secure programs.
• It is easy to partition the work in a project based on objects.
• Object oriented system easily upgraded from small to large systems.
• Software complexity can be easily managed.
1. Simple
• No pointers
• Automatic garbage collection
• Rich pre-defined class library
2. Object Oriented
• Focus on the data (objects) and methods manipulating the data
• All methods are associated with objects
• Potentially better code organization and reuse
3. Compile, Interpreted and High Performance
• Java compiler generate byte-codes, not native machine code
• The compiled byte-codes are platform-independent
• Java byte codes are translated on the fly to machine readable instructions in runtime
(Java Virtual Machine)
• Easy to translate directly into native machine code by using a just-in-time compiler.
4. Portable
• Same application runs on all platforms
• The sizes of the primitive data types are always the same
• The libraries define portable interfaces
5. Reliable/Robust
• Extensive compile-time and runtime error checking
• No pointers but real arrays. Memory corruptions or unauthorized memory accesses
are impossible
• Automatic garbage collection tracks objects usage over time
• Secure
• Java’s robustness feature makes java secure.
• Access restrictions are forced (private, public)
6. Multithreaded
• It supports multithreaded programming.
• Need not wait for the application to finish one task before beginning another one.
7. Dynamic
• Libraries can freely add new methods and instance variables without any effect on
their clients
• Interfaces promote flexibility and reusability in code by specifying a set of methods
an object can perform, but leaves open how these methods should be implemented.
8. Distributed
• Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols.
• Allows objects on two different computers to execute procedures remotely by using
package called Remote Method Invocation (RMI).
9. Architecture-Neutral
• Goal of java designers is “write once; run anywhere, anytime, forever.”
• Every variable has a type, every expression has a type, and every type is strictly
defined.
• All assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility.
• There are no automatic conversions of conflicting types as in some languages.
For example, in C/C++ you can assign a floating-point value to an integer. In Java, you cannot.
1. Integer Data Types
• Java does not support unsigned, positive-only integers.
• All are signed, positive and negative values.
Ex: int a=2, b= -1;
2)
3)
Variables
• The variable is the basic unit of storage in a Java program.
• A variable is defined by the combination of an identifier, a type, and an optional
initializer.
Declaring a Variable
• Instance Variable
• Static Variable
• Local Variable
• Parameters
1. Local variables:
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and
the variable will be destroyed once it exits the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor or block.
• There is no default value for local variables so local variables should be declared
and an initial value should be assigned before the first use.
2. Instance variables:
• Instance variables are declared in a class, but outside a method, constructor or any
block.
• Instance variables are created when an object is created with the use of the key word
'new' and destroyed when the object is destroyed.
• Each object gets its own copy of the instance variables.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the
class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name inside the
class.
• However, within static methods and different class (when instance variables are
given accessibility) that should be called using the fully qualified name
ObjectReference.VariableName
3. Static variables:
• Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when the
program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
ClassName.VariableName
Sample Program
class HelloWorld {
public static void main (String args []) {
System.out.println (“Welcome to Java Programming…..”);
}
}
• public allows the program to control the visibility of class members. When a class
member is preceded by public, then that member may be accessed by code outside the
class in which it is declared.
• In this case, main( ) must be declared as public, since it must be called by code outside
of its class when the program is started.
• static allows main( ) to be called without having to instantiate a particular instance of
the class. This is necessary, since main ( ) is called by the Java interpreter before any
objects are made.
• void states that the main( ) method will not return any value.
• main( ) is called when a Java application begins. In order to run a class, the class must
have a main( ) method.
• String args[] declares a parameter named args, which is an array of String class. In this
case, args receives any command-line arguments present when the program is executed.
• System is a class which is present in java.lang package.
• out is a static field which is defined in System class which returns a PrintStream
object. As out is a static field it can be referenced directly with classname.
• println( ) is a method which presents in PrintStream class which can be called through
the PrintStream object returned by static field out presented in System class to print a
line to console.
class Sample{
public static void main(String args[]){
System.out.println("sample:main");
Sample s=new Sample();
s.display();
}
void display(){
System.out.println("display:main");
}
}
• The scope of a declared element is the portion of the program where the element is
visible.
Lifetime
• The lifetime of a declared element is the period of time during which it is alive.
• The lifetime of the variable can be determined by looking at the context in which they're
defined.
Control Statements
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
……
else
statement;
d) switch statement
• The switch statement is Java’s multiway branch statement. It provides an easy
way to dispatch execution to different parts of your code based on the value of
an expression. As such, it often provides a better alternative than a large series
of if-else-if statements.
2. Iteration Statements
a. while loop
• It repeats a statement or block while its controlling expression is true. Here is
its general form:
while (condition) {
// body of loop
}
• The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition becomes
false, control passes to the next line of code immediately following the loop.
• The curly braces are unnecessary if only a single statement is being repeated.
// Demonstrate the while loop.
b. do-while
• As you just saw, if the conditional expression controlling a while loop is
initially false, then the body of the loop will not be executed at all.
• However, sometimes it is desirable to execute the body of a while loop at least
once, even if the conditional expression is false to begin with.
• Syntax:
do {
// body of loop
} while (condition);
• Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will
repeat. Otherwise, the loop terminates.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
}
}
c. for loop
• Here is the general form of the for statement:
for(initialization; condition; iteration) {
// body
}
• The for loop operates as follows.
• When the loop first starts, the initialization portion of the loop is executed.
• Generally, this is an expression that sets the value of the loop control variable,
which acts as a counter that controls the loop.
• Next, condition is evaluated. This must be a Boolean expression.
• It usually tests the loop control variable against a target value.
• If this expression is true, then the body of the loop is executed. If it is false, the
loop terminates. Next, the iteration portion of the loop is executed. This is
usually an expression that increments or decrements the loop control variable.
// Demonstrate the for loop.
class ForTick {
int n;
d. foreach loop
• It starts with the keyword for like a normal for-loop.
• Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a colon,
which is then followed by the array name.
• In the loop body, you can use the loop variable you created rather than using an
indexed array element.
is equivalent to:
3. Jump Statements
ARRAYS
2. Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of arrays.
• To declare a multidimensional array variable, specify each additional index using
another set of square brackets.
• For example, the following declares a two-dimensional array variable called twoD.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
• When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension.
• You can allocate the remaining dimensions separately.
Ex: int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
• We can create a two-dimensional array in which the sizes of the second dimension
are unequal.
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Alternative Array Declaration Syntax
• There is a second form that may be used to declare an array:
type[ ] var-name;
• Here, the square brackets follow the type specifier, and not the name of the array
variable.
• For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
• The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
Output:
The length of the array is: 10
Classes and Objects
Introduction to Class
• A class is a template that defines the form of an object which contains instance
variables and methods.
• A class is the blueprint from which individual objects are created.
• When you define a class, you declare its exact form and nature. A class is
created by using the keyword class.
• The general form of a class is
class className {
//declare instance variables
type var1;
type var2
//……….
type varN;
//declare methods
type methodname1(parameter-list) {
// body of method
}
// .......
type methodnameN(parameter-list) {
// body of method
}
}
• The data, or variables, defined within a class but outside the methods are called
instance variables
Defining a Class
• Let’s define a class called Box
class Box {
double width;
double height;
double depth;
}
• A class definition creates a new data type. In this case, the new data type is Box
• We can use this name to declare objects of type Box
• A class declaration is only a type description, it does not create an actual object
Declaring an Object
• Object is an instance of a class
• When you create a class, you are creating a new data type. You can use this type to
declare objects of that type.
• However, obtaining objects of a class is a two-step process
a. Declaring a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
b. Acquiring an actual, physical copy of the object and assign it to that variable.
This can be done using the new operator. The new operator dynamically
allocates (i.e., allocates at run time) memory for an object and returns a
reference to it. This reference is, more or less, the address in memory of the
object allocated by new. This reference is then stored in the variable
• Each time you create an instance of a class, you are creating an object that contains its
own copy of each instance variable defined by the class.
• In the above programs to declare an object of type Box:
Box b = new Box();
• This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly:
Box b; // declares reference to object
b = new Box(); // allocate a Box object
• The first line declares b as a reference to an object of type Box. After this line executes,
b contains the value null, which indicates that it does not yet point to an actual object.
• Any attempt to use b at this point will result in a compile-time error.
• The next line allocates an actual object and assigns a reference to it to b. After the
second line executes; you can use b as if it were a Box object
width 20
b1 height 21
depth 20
width 30
height 20
b2
depth 25
b1.width = 12;
System.out.println(b1.width);
System.out.println(b2.width);
• After executing both of these println() statements, we get the same value for both the
statements as 12.