0% found this document useful (0 votes)
146 views

The Genesis of Java / History of Java: Unit I - Introduction To Java

- Java is an object-oriented programming language introduced by Sun Microsystems in 1995. It derives its syntax from C and C++ but aims to be simpler and more robust. - The key advantages of Java include being platform independent, secure, robust with features like automatic memory management, and high performance due to just-in-time compilation to native code. - The first Java program prints "Hello World" by defining a main method that uses System.out.println to display the message.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views

The Genesis of Java / History of Java: Unit I - Introduction To Java

- Java is an object-oriented programming language introduced by Sun Microsystems in 1995. It derives its syntax from C and C++ but aims to be simpler and more robust. - The key advantages of Java include being platform independent, secure, robust with features like automatic memory management, and high performance due to just-in-time compilation to native code. - The first Java program prints "Hello World" by defining a main method that uses System.out.println to display the message.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT I - INTRODUCTION TO JAVA

The Genesis of Java- Buzzwords- Object oriented Concepts- Lexical Issues-


Data types and variables- Arrays- Operators - Control Statements: Selection-
Iteration and jump Statement.

The Genesis of Java / History of Java


Java is a programming language introduced by the Sun Microsystems in
June 1995. Java derives its syntax from C and the object oriented features are
influenced by C++. The original name of this platform independent
programming language was called Oak.
James Gosling, a member of the Green Project Team is one of the
inventors of this programming language. The other members of this team are
Bill Joy, Frank Yellin, Patrick Naughton, Richard Tuck, Arthur Van Hoff, Chris
Wrath and Mike Sheridan.
Java was originally designed to develop software for consumer electronic
devices. It was not intended to be an Internet programming language. With the
advent of World Wide Web(WWW) that demanded software that was portable
across all the platforms. Java was then adapted as Internet Programming
language.
The key advantages of Java programming language is that the compiled
code of java is not machine specific instructions but rather an intermediate
code called as Byte Code
Byte Code
Byte code is a highly optimized set of instructions designed to be executed by
the Java runtime system (interpreter) which is called the Java Virtual Machine
(JVM)
JVM
JVM stands for Java Virtual Machine. JVM is an abstract computing machine,
or virtual machine. It is a platform-independent execution environment that
converts Java byte codes into machine language and executes it (i.e) JVM is an
interpreter for bytecode.

JVM control execution of every Java program. It enables features such as


automated exception handling, Garbage-collected heap.
JIT
Just In Time (JIT) compiler is a part of the Java Virtual Machine (JVM) and it
compiles byte code into executable code in real time, on a piece-by-piece,
demand basis

Java Buzzwords / Features of Java


Simple
Java is easy to learn and its syntax is quite simple, clean and easy to
understand. The confusing and ambiguous concepts of C++ are either left out
in Java or they have been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not in java but were an important
part of C++.
Object Oriented
Everything is an object in Java. So the focus is on the data and methods that
operate on the data in your application and not concentrate only on the
procedures. The data and methods together describe the state and the behavior
of an object.
Java has a clean, usable, pragmatic approach to objects. The object model in
Java is simple and easy to extend, while simple types, such as integers, are
kept as high performance non-objects.
Platform Independent
Unlike programming languages such as C and C++, when Java is compiled, it
is not compiled into platform specific machine code, rather into platform
independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.

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

First Java Program


Let us look at a simple java program.
class Hello
{
public static void main(String[] args)
{
System.out.println ("Hello World program");
}
}
class : class keyword is used to declare classes in Java
public : It is an access specifier. Public means this function is visible to all.
static : static is again a keyword used to make a function static. To execute a
static function you do not have to create an Object of the class. The main()
method here is called by JVM, without creating any object for class.
void : It is the return type, meaning this function will not return anything.

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

Data Types in Java


Java is a strongly typed language. This means that every variable must have a
declared type. There are two categories of data types available in Java
 Primitive data types
 Non-primitive data types

Primitive Data Types


There are eight primitive types in Java. Four of them are integer types, two are
floating types, one is character type and last is boolean type.

Data Type Size Range Default Value


byte 1 Byte (8 bits) -27 to 27 -1 0
short 2 Bytes (16 bits) -215 to 215 -1 0
int 4 Bytes (32 bits) -231 to 231 -1 0
long 8 Bytes (64 bits) -263 to 263 -1 0L
char 2 Bytes (16 bits) 0 to 216 -1 „\u0000‟
float 4 Bytes (32 bits) 0.0f
double 8 Bytes (64 bits) 0.0d
boolean 1 Bit Either true or false false
byte
 byte is an 8 bit signed two‟s complement integer
 Default value is 0
 It is used to save space in larger arrays mainly in place of integers, since a
byte is 4 times smaller than an int.
 Example
byte b = 100;
short
 short is a 16 bit signed two‟s complement integer
 Default value is 0
 short data type can also be used to save memory as byte data type. It is 2
times smaller than an int.
 Example
short s = 1000;
int
 int is a 32 bit signed two‟s complement integer
 Default value is 0
 Generally used as default data type for integer values unless there is a
concern about memory
 Example
int i = 10000;
long
 long is a 64 bit signed two‟s complement integer
 This type is used when a wider range than int is needed
 Default value is 0L
 Example
long l = 1000000L;
float
 float is a single precision 32 bit floating point No
 Default value is 0.0f
 Example
float f = 23.45f;
double
 double is a double precision 64 bit floating point No
 It is generally used as default data type for decimal values.
 Default value is 0.0d
 Example
double d = 23.45d;
boolean
 boolean represent one bit of information
 There are only two possible values – true, false
 Default values is false
 Example
boolean flag = true;
char
 char is a 16 bit Unicode charcter.
 It is used to store any character
 Default value is „\u0000‟
 Example
char c =‟A‟;
Variables
The variable is the basic unit of storage in a Java program. Variables are named
memory location which is used to store data for later use.
Rules for naming variables
 Variable name can consist of capital letters A-Z, lower case letters a-z, digits
0-9 and two special characters such as underscore and dollar sign
 First letter must be a letter
 Blank space and special characters cannot be used in variable name
 Keywords cannot be used as variable names
 Variable names can case-sensitive
 Example
Valid variable Names
s_no
n1
Student_Name
Invalid Variable Names
1no – starts with no
student no – uses space character

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);

System.out.println("Hypotenuse is " + c);


} }
Types of Variable
Java language defines three kinds of variables.
 Instance variables
 Static Variables
 Local Variables
Instance variables
 Instance variables are variables that are declared inside a class but outside
any method, constructor or block.
 Instance variable are also variable of object commonly known as field or
property.
 Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
 Access modifiers can be given for instance variables.
 Instance variables have default values. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned
during the declaration or within the constructor
 Example
class Student
{
String name;
int age;
}
Here name and age are instance variable of Student class.
Static variables
 Static variables also known as class 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 rarely used other than being declared as constant
 Static variables are created when the program starts and destroyed when the
program stops
 Static variables can be accessed by calling with the class name.
ClassName.VariableName
 Example
class Student
{
String name;
int age;
static String college=”SRM University”;
}
Here college is a static variable.
Local variables
 Local variables are declared in method, constructor or blocks.
 Local variables are initialized when method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor or
block.
 Access modifiers are not used for local variable.
 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
 Example
float getDiscount(int price)
{
float discount;
discount=price*(20/100);
return discount;
}
Here discount is a local variable.

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

Accessing Array Elements


The array elements are accessed through the index. Array indices are 0-based;
that is, they start from 0 to arrayRefVar.length -1
Array Initialization
Arrays can also be initialized when they are declared. An array initializer is a list of
comma-separated expressions surrounded by curly braces. The array will
automatically be created large enough to hold the number of elements specified in
the array initialize.
dataType[] arrayRefVar = { value0, value1,..., valuek };
Example
double[] myList = {1, 2, 3, 4, 5};
Processing Arrays
When processing array elements, we often use either for loop or foreach loop
because all of the elements in an array are of the same type and the size of the array
is known
Example
public class TestArray {
public static void main(String[] args) {
double[] myList = {1, 2, 3, 4, 5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i]);
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
} }
This would produce the following result:
1
2
3
4
5
Total is 15
Multidimensional Arrays
Multidimensional arrays are actually arrays of arrays. To declare a
multidimensional array, specify each dimension using separate square brackets.
The following statement declares a two-dimensional array variable
int twoD[][] = new int[4][5]
This allocates a 4 by 5 array and assigns it to twoD

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.

The Arrays Class:


The java.util.Arrays class contains various static methods for sorting and searching
arrays, comparing arrays, and filling array elements. These methods are overloaded
for all primitive types.
Some methods of Arrays class
 int binarySearch(Object[] a, Object key) - Searches the array for the element
„key‟
 boolean equals(long[] a, long[] a2) – compares two arrays
 void fill(int[] a, int val) – fills the array
 void sort(Object[]) – sorts the array
Operators
Java provides a rich set of operators to manipulate variables. Java‟s operators can
be divided into following groups
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Boolean Logical Operators
 Assignment Operators
 Misc Operator
Arithmetic Operators
Arithmetic operators are used in mathematical expressions. The following table lists
the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:


Operator Description Example
Addition - Adds values on either side of
+ A + B will give 30
the operator
Subtraction - Subtracts right hand
- A - B will give -10
operand from left hand operand
Multiplication - Multiplies values on
* A * B will give 200
either side of the operator
Division - Divides left hand operand by
/ B / A will give 2
right hand operand
Modulus - Divides left hand operand by
% right hand operand and returns B % A will give 0
remainder
Increment - Increases the value of
++ B++ gives 21
operand by 1
Decrement - Decreases the value of
-- B-- gives 19
operand by 1

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.

Boolean Logical Operators:


The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:
Operator Description Example
Called Logical AND operator. If both the
(A && B) is
&& operands are true, then the condition
false.
becomes true. Otherwise false
Called Logical OR Operator. If any of the two
|| operands are true, then the condition (A || B) is true.
becomes true. Otherwise false
Called Logical NOT Operator. Use to reverses
the logical state of its operand. If a condition !(A && B) is
!
is true then Logical NOT operator will make true.
false.
Assignment Operators
There are following assignment operators supported by Java language:
Operator Description Example
Simple assignment
C = A + B will assign value of A + B
= operator, Assigns values
into C
from right side operands to
left side operand
Add AND assignment
operator, It adds right
+= operand to the left operand C += A is equivalent to C = C + A
and assign the result to left
operand
Subtract AND assignment
operator, It subtracts right
-= operand from the left C -= A is equivalent to C = C - A
operand and assign the
result to left operand
Multiply AND assignment
operator, It multiplies right
*= operand with the left C *= A is equivalent to C = C * A
operand and assign the
result to left operand
Divide AND assignment
operator, It divides left
/= operand with the right C /= A is equivalent to C = C / A
operand and assign the
result to left operand
Modulus AND assignment
operator, It takes modulus
%= using two operands and C %= A is equivalent to C = C % A
assign the result to left
operand
Left shift AND assignment
<<= C <<= 2 is same as C = C << 2
operator
Right shift AND
>>= C >>= 2 is same as C = C >> 2
assignment operator
Bitwise AND assignment
&= C &= 2 is same as C = C & 2
operator
bitwise exclusive OR and
^= C ^= 2 is same as C = C ^ 2
assignment operator
bitwise inclusive OR and
|= C |= 2 is same as C = C | 2
assignment operator

Misc Operators - Conditional Operator ( ? : ):


Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the
operator is to decide which value should be assigned to the variable. The operator is
written as:
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = 5;
int big = (a > b) ? a: b;
System.out.println( "Biggest Value is : " + big );
} }
This would produce the following result:
Biggest Value is : 10
Precedence of Java Operators
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment =+ =- = * = / = % Right to left
= >> = << = &= ^=
|=
Comma , Left to right
Control Statements
A Programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program. Control statements
in java are categorized as follows
 Selection Statements
 Iteration Statements
 Jump Statements
Selection Statements
There are two types of selection statements in Java. They are:
 if statements
 switch statements
if Statement
if statement consists of a condition followed by one or more statements.
Syntax:
if(condition)
{
//Statements will execute if the condition is true
}
If the condition evaluates to true then the block of code inside the if statement will
be executed. If not, control is transferred to the statement following if statement.
Example:
public class Test {
public static void main(String args[]){
int x = 10;

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 );

System.out.println("Factorial Value = " +fact);


}
}
Output
Factorial Value is 24
while loop
The while loop repeats a statement or block while its condition is true.
Syntax
while(Condition)
{
//Statements
}
The condition can be any boolean expression. When condition becomes false,
control passes to the statement following the loop. The curly braces are unnecessary
if only a single statement is being repeated. In while loop, the loop will not execute
even once, if the condition is false in beginning itself.
Example
public class Test {
public static void main(String args[]) {
int n = 4;
int fact = 1, i=1;
while( i <= n )
{
fact = fact * i;
i++;
}
System.out.println("Factorial Value = " +fact);
}
}
Output
Factorial Value is 24
for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times. A for loop is useful when you
know how many times a task is to be repeated.
Syntax
for(initialization; condition; incrementation/decrementation)
{
//Statements
}
Here is the flow of control in a for loop:
 The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to put a
statement here, as long as a semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop does not execute and flow of control jumps to
the next statement past the for loop.
 After the body of loop executes, the flow of control jumps back up to the
incrementation / decrementation statement. This statement allows you to
update any loop control variables. This statement can be left blank, as long as
a semicolon appears after the Boolean expression.
 The Boolean expression is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then update step, then condition).
After the condition is false, the for loop terminates.
Example
public class Test {
public static void main(String args[]) {
int i, fact=1,n=4;
for(i = 1; i <= n; i++)
fact = fact * i;
System.out.println("Factorial Value = "+fact);
}
}
Output
Factorial Value is 24

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.

You might also like