The Genesis of Java / History of Java: Unit I - Introduction To Java
The Genesis of Java / History of Java: Unit I - Introduction To Java
Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on
compile time error checking and runtime checking. The main areas which Java
improved were Memory Management and mishandled Exceptions by
introducing automatic Garbage Collector and Exception Handling.
Secure
When it comes to security, Java is always the first choice. Java enables us to
develop virus free, temper free system. Java program always runs in Java
runtime environment (JRE) with almost null interaction with system OS, hence
it is more secure.
Multithreaded
With Java's multithreaded feature, it is possible to write programs that can do
many tasks simultaneously. This design feature allows developers to construct
smoothly running interactive applications.
Interpreted and High Performance
Java enables the creation of cross-platform program by compiling into an
intermediate representation called Java Byte code. This code can be interpreted
on any system that provides a Java Virtual Machine.
Java Byte code was carefully designed so that it would be easy to translate
directly into native machine code by using a Just-in-Time(JIT) compiler for very
high performance.
Distributed
Java is designed for the distributed environment of the internet. RMI and EJB
are used for creating distributed applications.
Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount
of run-time information that can be used to verify and resolve accesses to
objects at run-time
main : main() method is a place that all Java applications start. The class,
which does not have a main method, can be successfully compiled but cannot
be executed as it does not have a starting point of execution, which is the main
method
System.out.println : This is used to print anything on the console like printf
in C language.
Lexical Issues / Tokens of Java
The smallest unit of a program is known as Token. There are many atomic
elements of Java. Java programs are a collection of whitespace, identifiers,
comments, literals, operators, separators and keywords.
Whitespace
Java is a free-form language. It means we do not need to follow any special
indentation rules. In java whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names and variable names. An
identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters. An identifier must not
begin with a number.
Some examples of valid identifiers are
AvgTemp Count $calculate s5 Student_No
Some examples of invalid identifiers are
2no high-temp not/ok
Literals
A constant value in Java is created by using a literal representation of it.
Examples
Integer literal : 100
Floating-point literal : 98.6
Character literal : „s‟
String literal : “sample”
Comments
A comment describes the operation of the program to anyone who is reading its
source code. In java there are three types of comments. They are single-line,
multi-line and documentation comment.
Single-line comment
Two slashes characters are the single-line comment (i.e.) //
Example- // This comment extends to the end of the line.
Multi-line comment
To add a comment of more than one line, we can precede our comment
using /* and end with delimiter */.
Example-
/*..............
multi-line comments are given
in this comment
.......................................................
.....................................................*/
Documentation comment
This is a special type of comment that indicates documentation
comment. This type of comment is readable to both, computer and
human. To start the comment, use /** and end with */.
Example-
/**....... Documentation comments..........*/
Separators
Separators are used to terminate statements. In java there are few characters
that are used as separators . They are parentheses (), braces {}, brackets [],
semicolon ;, period ., and comma,.
Keywords
Keywords are reserved words that have a predefined meaning in the language.
Hence programmers cannot use keywords as names for variables, methods,
classes, or as any other identifier.
boolean int void
char long if
byte float else
short double switch
case while continue
default for return
do break class
interface extends implements
try
catch throw throws
finally
Declaring a Variable
In Java, all variables must be declared before they can be used. A variable is defined
by the combination of an identifier, a type and an optional initializer
The basic form of a variable declaration is
type identifier [=value][, identifier[=value] …];
The type is one of Java‟s data type. The identifier is the name of the variable. You
can initialize the variable by specifying an equal sign and a value. To declare more
than one variable of the same type, use a comma-separated list.
Example
int i,j;
double total=0,averge;
Dynamic Initialization of Variables
Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared. The initialization expression may use any element
valid at the time of the initialization, including calls to methods, other variables or
literals
Example
public class Sample {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
Arrays
An array is a collection of like-typed variables that are referred to by a common
name. Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. Arrays of any
type can be created and have one or more dimensions.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array,
and you must specify the type of array the variable can reference. Here is the syntax
for declaring an array variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way
Example
double [] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Creating Arrays
You can create an array by using the new operator with the following syntax:
arrayRefVar =new dataType[arraySize];
The above statement does two things
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar
Declaring an array variable, creating an array, and assigning the reference of
the array to the variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[ arraySize ];
Example:
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList:
double[] myList = new double [10];
Following picture represents array myList. Here, myList holds ten double values and
the indices are from 0 to 9
When you allocate memory for a multidimensional array, you need only specify the
leftmost (first) dimension. You can allocate the remaining dimensions separately.
The following statements create a two-dimensional array in which second dimension
are not same.
int twoD[][] = new int[3][] ;
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
The array created by the above statements will have the following elements
[0][0]
[1][0] [1][1]
[2][0] [2][1] [2][2]
Multidimensional arrays can also be initialized by enclosing each dimension‟s
initializer within its own set of curly braces.
Ragged Array
A Jagged or also called Ragged array is a n-dimensional array that need not be
rectangular.
Relational Operators
The following are the relational operators supported by Java language
Operator Description Example
Checks if the values of two operands
== are equal or not, if yes then condition (A == B) is not true.
becomes true.
Checks if the values of two operands
!= are equal or not, if values are not (A != B) is true.
equal then condition becomes true.
Checks if the value of left operand is
greater than the value of right
> (A > B) is not true.
operand, if yes then condition
becomes true.
Checks if the value of left operand is
< less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition
becomes true.
Checks if the value of left operand is
less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition
becomes true.
Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60;
and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
Operator Description Example
Binary AND Operator
(A & B) will give 12 which is 0000
& copies a bit to the result if
1100
it exists in both operands.
Binary OR Operator copies
(A | B) will give 61 which is 0011
| a bit if it exists in either
1101
operand.
Binary XOR Operator
(A ^ B) will give 49 which is 0011
^ copies the bit if it is set in
0001
one operand but not both.
Binary Ones Complement
(~A ) will give -61 which is 1100
~ Operator is unary and has
0011 in 2's complement form
the effect of 'flipping' bits.
Binary Left Shift Operator.
The left operands value is
A << 2 will give 240 which is 1111
<< moved left by the number
0000
of bits specified by the
right operand.
Binary Right Shift
Operator. The left
operands value is moved
>> A >> 2 will give 15 which is 1111
right by the number of
bits specified by the right
operand.
Shift right zero fill
operator. The left
operands value is moved
right by the number of A >>>2 will give 15 which is 0000
>>>
bits specified by the right 1111
operand and shifted
values are filled up with
zeros.
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
Output
This is if statement
if...else Statement
An if statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
Syntax
if(condition)
{
//Executes when the condition is true
}else
{
//Executes when the condition is false
}
Example
public class Test {
public static void main(String args[]){
int a, b;
a=20;
b=5;
if( a > b )
System.out.print(a+"is big");
else
System.out.print(b+"is big");
}
}
Output
20 is big
if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement
Syntax
if(Condition 1)
{
//Executes when the Condition 1 is true
}
else if(Condition 2)
{
//Executes when the Condition 2 is true
}
else if(Condition 3)
{
//Executes when the Condition 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
Example
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 )
System.out.print("Value of X is 10");
else if( x == 20 )
System.out.print("Value of X is 20");
else if( x == 30 )
System.out.print("Value of X is 30");
else
System.out.print("This is else statement");
} }
Output
Value of X is 30
Nested if...else Statement
It is always legal to nest if statements which means you can use if statement inside
another if statement.
Syntax
if(Condition 1)
{
//Executes when the Condition 1 is true
if(Condition 2)
{
//Executes when the Condition 2 is true
}
}
Example
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}
Output
X = 30 and Y = 10
switch Statement:
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
case.
Syntax
switch(expression)
{
case value1 :
//Statements
break; //optional
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
/Statements
}
The following rules apply to a switch statement:
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch
and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.
Example
public class Test {
public static void main(String args[]){
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Output
Well done
Your grade is a C
Iteration Statements
There may be a situation when we need to execute a block of code several number of
times, and is often referred to as a loop.
Java‟s iteration statements are
do – while loop
while loop
for loop
do-while loop
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax
do
{
//Statements
}
while(Condition);
Notice that the Condition appears at the end of the loop, so the statements in the
loop execute once before the Condition is tested.
If the Condition is true, the flow of control jumps back up to do, and the statements
in the loop execute again. This process repeats until the Condition is false
Example
public class Test {
public static void main(String args[]) {
int n = 4;
int fact = 1, i=1;
do
{
fact = fact * i;
i++;
}
while( i <= n );
Jump Statements
Jump statements allow your program to execute in a nonlinear fashion. These
statements transfer control to another part of your program. Java supports three
jump statements
break
continue
return
break
In java, the break statement has three uses
It terminates a statement sequence in a switch statement
It can be used to exit a loop.
It can be used as a specialized form of goto
Using break to exit a loop
The break will stop the execution of the innermost loop and start executing the next
line of code after the block.
Example
public class Test {
public static void main(String args[]) {
for(int i =1;i<=5 ;i++
{
if( i == 3 )
break;
System.out.println( i );
}
}
}
Output
1
2
Using break as a form of goto
The general form of the labeled break statement is
break label;
Here, label is the name of the label that identifies a block of code. When this form of
break executes, control is transferred out of the named block of code. To name a
block, put a label at the start of it. Labeled break statement is often used exit from
nested loops.
continue
The continue keyword can be used in any of the loop control structures. It causes
the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to
the incrementation / decrementation statement.
In a while loop or do/while loop, flow of control immediately jumps to the condition.
As with break statement, continue may specify a label to describe which enclosing
loop to continue
Example
public class Test {
public static void main(String args[]) {
for(int i =1;i<=5 ;i++ )
{
if( i == 3 )
continue;
System.out.println( i );
}
}
}
Output
1
2
4
5
return
The return statement is used to explicitly return from a method. It causes program
control to transfer back to the caller of the method. Thus the return statement
immediately terminates the method in which it is executed.