You are on page 1of 40

1

11
INTRODUCTION TO JAVA
1.1 Advantages of Java
1.2 Features of Java
1.3 Data types, variables and array
1.4 Operators
1.5 Overview of control statements
1.6 Input and output in Java

1.1 Advantages of Java:


JAVA is an object oriented programming language. It offers following
advantages to its user:
 It is an open source, so users do not have to purchase license version of
the software.
 It is Platform independent language. Means the program written on one
computer can be easily run without any modification on another computer
with different OS.
 It has a large set of API's that can be easily accessed by programmers.
 Memory management in JAVA is done automatically using Garbage
Collection utility so programmers don’t have to worry about it.
 Java always allocates objects on the stack.
 Java embraced the concept of exception specifications.
 Multi-platform support language and support for web-services.
 Using JAVA you can develop dynamic web applications.
 It allows you to create modular programs and reusable codes using
object oriented concept such as class, object, inheritance and
polymorphism.
 It allows you to develop multithreading application which performs
more then one task of the same application at the same time
simultaneously.
 It allows you to develop a program called applet that can be accessed on
internet.
 It allows you to develop Graphical User Interface application using
Abstract Window Toolkit. In which you can add various controls.
1.2 Features of Java
Following are the features of JAVA that makes it powerful language.
 Simple: Java was developed by adopting some of the best features from
other programming languages such as C and C++. So Java utilizes the
methodologies that are already proven. Error prone tasks such as pointers
and memory management have either been eliminated or are handled by
the Java environment automatically rather than by the programmer. Thus
it is very simple to use.
 Object Oriented: Even though Java has the look and feel of C++, it is a
wholly independent language which has been designed to be object-
oriented from the ground up. In object-oriented programming (OOP), data
is treated as objects to which methods are applied. Java's basic execution
unit is the class. Advantages of OOP include: reusability of code,
extensibility and dynamic applications.
 Distributed: Commonly used Internet protocols such as HTTP and FTP as
well as calls for network access are built into Java. Internet programmers
can call on the functions through the supplied libraries and be able to
access files on the Internet as easily as writing to a local file system.
 Interpreted: When Java code is compiled, the compiler outputs the Java
Byte code which is an executable for the Java Virtual Machine. The Java
Virtual Machine does not exist physically but is the specification for a
hypothetical processor that can run Java code. The byte code is then run
through a Java interpreter on any given platform that has the interpreter
ported to it. The interpreter converts the code to the target hardware and
executes it.
 Robust: Java compels the programmer to be thorough. It carries out type
checking at both compile and runtime making sure that every data
structure has been clearly defined and typed. Java manages memory
automatically by using an automatic garbage collector. The garbage
collector runs as a low priority thread in the background keeping track of
all objects and references to those objects in a Java program. When an
object has no more references, the garbage collector tags it for removal
and removes the object either when there is an immediate need for more
memory or when the demand on processor cycles by the program is low.
 Secure: The Java language has built-in capabilities to ensure that
violations of security do not occur. At compile time, pointers and memory
allocation are removed thereby eliminating the tools that a system
breaker could use to gain access to system resources. Memory allocation
is deferred until runtime. Even though the Java compiler produces only
correct Java code, there is still the possibility of the code being tampered
with between compilation and runtime. Java guards against this by using
the byte code verifier to check the byte code for language compliance
when the code first enters the interpreter, before it ever even gets the
chance to run.
The byte code verifier ensures that the code does not do any of the
following: Forge pointers, Violate access restrictions, incorrectly access
classes, Overflow or underflow operand stack, Use incorrect parameters of
byte code instructions, Use illegal data conversions. At runtime, the Java
interpreter further ensures that classes loaded do not access the file
system except in the manner permitted by the client or the user.
 Architecturally Neutral: The Java compiler compiles source code to a
stage which is intermediate between source and native machine code. This
intermediate stage is known as the byte code, which is neutral. The byte
code conforms to the specification of a hypothetical machine called the
Java Virtual Machine and can be efficiently converted into native code for
a particular processor.
 Portable: By porting an interpreter for the Java Virtual Machine to any
computer hardware/operating system, one is assured that all code
compiled for it will run on that system. This forms the basis for Java's
portability.
Another feature which Java employs in order to guarantee portability is by
creating a single standard for data sizes irrespective of processor or
operating system platforms.
 High-Performance: The Java language supports many high-performance
features such as multithreading, just-in-time compiling, and native code
usage. Java has employed multithreading to help overcome the
performance problems suffered by interpreted code as compared to native
code. Since an executing program hardly ever uses CPU cycles 100 % of
the time, Java uses the idle time to perform the necessary garbage
cleanup and general system maintenance that renders traditional
interpreters slow in executing applications. Since the byte code produced
by the Java compiler from the corresponding source code is very close to
machine code, it can be interpreted very efficiently on any platform. In
cases where even greater performance is necessary than the interpreter
can provide, just-in-time compilation can be employed whereby the code
is compiled at run-time to native code before execution. An alternative to
just-in-time compilation is to link in native C code. This yields even
greater performance but is more burdensome on the programmer and
reduces the portability of the code.
 Dynamic: By connecting to the Internet, a user immediately has access
to thousands of programs and other computers. During the execution of a
program, Java can dynamically load classes that it requires either from
the local hard drive, from another computer on the local area network or
from a computer somewhere on the Internet.
1.3 Data types, variables and array
1.3.1 Data Types
Data type determines the kind of the value that can be stored in a variable.
While declaring variables you must have to specify the Data Type for those
variables to instruct compiler how much memory to be allocated for each
variable and which kind of the value can be stored in each variable.
Type checking is performed strictly in Java. For example in C and C++ you
can assign floating point value to an integer variable while in Java you can not
do so.
In JAVA basic Data Types are divided into following four categories:
(1)Integer:
 This category contains four data types: byte, short, int and long.
 Following table summarize the four data types with their size in byte
and their range.
Data Type Byte Range
Byte 1 –128 to 127
Short 2 –32,768 to 32,767
Int 4 –2,147,483,648 to 2,147,483,647
Long 8 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
 All the data types mentioned in the above table are signed data type
which means they can store both positive as well as negative
numbers. In Java there are no unsigned data types.
(2)Floating Point:
 This category contains two data types: float and double.
 Following table summarize the two data types with their size in byte and
their range.
Data Type Byte Range
Float 4 1.4e−045 to 3.4e+038
Double 8 4.9e–324 to 1.8e+308
 Floating point data type is used to store numbers with decimal points.
 float data type is known as single precision. It is useful when accuracy
is not an issue. It is useful in the situation where better accuracy is not
required.
 double data type is known as double precision. It is useful when
accuracy is an issue. It is useful in the situation where accuracy is
important.
(3)Character:
 This category contains only one data type called char.
 char data type is used to store single character that is enclosed
between single quotation mark.
 char data type occupies 2 bytes in memory.
 The range of a char is 0 to 65,536.
 Default value for this data type is NULL.
(4)Boolean:
 This category contains only one data type called boolean.
 boolean data type is used to store the value true or false.
 Default value for this data type is false.
1.3.2 Variables
A variable is a named location in computer’s memory. When we declare the
variable in the program the compiler allocates fixed bytes of memory to that
variable at the time of compiling the program and assigns a name to that
allocated memory space.
A variable is used to store data temporary during the execution of the
program.
A Variable has a name and value of specific type.
One of the important characteristic of variable is that the value of the variable
may change during the execution of the program.
 Declaring a Variable:
Like C and C++, in Java, all variables must be declared before they can be
referenced in the program.
The general syntax for declaring variable is given below:
DataType VariableName [=value];
Data Type determines which kind of the value can be store in the variable and
how much memory to be allocated for that variable.
You can assign initial value for the variable at the time of declaring it.
However it is optional.
You can also declare multiple variables of the same data type in the single
statement by separating each of them using comma operator.
Consider Following examples:
int a;
int a=5;
float b=3.5;
int a, b, c;
int a=5, b=6, c=7;
1.3.3 Arrays
An array is a collection of variables of same data type where all the variables
in array share common name.
Elements in the array can be identified using name of the array and an index.
In array index starts from 0.
In Java memory allocation for the array is done dynamically at run time.
There are two types of array in Java:
(1) One Dimension Array:
 Collection of variables that can be represented using only single
dimension is known as One Dimension Array.
 One dimensional array can be created using following two statement:
Data Type Array_Name [];
Here,
Data Type determines which kind of the value can be stored in the
variables of array.
When you declare an array using above syntax it will not allocate
memory for the variables of array. In order to allocate actual physical
memory to variables of array you have to write following statement:
Array_Name = new Data Type [Size];
Here,
Array_Name is the name of the array that you just declare.
new operator allocates memory to array variables.
Size indicates how many variables can be contained in the array.
 Thus in order to create one dimension array you need to follows two
steps:
Data Type Array_Name [];
Array_Name = new Data Type [Size];
 You can combine above two statements in to single statement using
following syntax:
Data Type ArrayName [] = new DataType [Size];
 Example:
int Mark [] = new int [5];
It will create an array of 5 integer variables and allocates memory for
5 integer variables and initialize them with default value which is 0.
 You can refer to the individual element of an array using array name
and index variable as below:
Mark [0] = 35;
Mark [1] = 45;
Mark [2] = 55;
Mark [3] = 85;
Mark [4] = 65;
 It is also possible to initialize all the elements of an array at the time
of creating an array.
 The general syntax is given below:
Data Type Array_Name [] = {Valu1, Value2, Value3… ValueN};
 Example:
public class OneDimArrayDemo1
{
public static void main(String[] args)
{
int Mark [] = {23,45,56,75,67};
int i = 0;
int sum=0;
for (i = 0;i<5;i++)
{
sum+=Mark[i];
}
System.out.println("Total marks="+sum);
}
}
 Output:

(2) Multi Dimension Array:


 Collection of variables that can be represented using more then one
dimension is known as Multi Dimension Array.
 Multi Dimension Array is used to represents value in the form of row
and columns.
 Multi Dimensional Array can be created using following two statement:
Data Type Array_Name [] []… [];
Here,
Data Type determines which kind of the value can be stored in the
variables of array.
When you declare an array using above syntax it will not allocate
memory for the variables of array. In order to allocate actual physical
memory to variables of array you have to write following statement:
Array_Name = new Data Type [Dim1] [Dim2]…. [DimN];
Here,
Array_Name is the name of the array that you just declare.
new operator allocates memory to array variables.
Dim1, Dim2 and DimN indicates size of each dimension.
 The number of elements that can be stored in the array can be find
using:
Dim1 * Dim2 * … * DimN
 Thus in order to create one dimension array you need to follows two
steps:
Data Type Array_Name [] []… [];
Array_Name = new Data Type [Dim1] [Dim2]…. [DimN];
 You can combine above two statements in to single statement using
following syntax:
Data Type ArrayName [] [] …. [] = new DataType [Dim1]
[Dim2]…. [DimN];
 Example:
int Matrix [][] = new int [3][3];
It will create an array of 3 by 3 which contains 9 elements.
 You can refer to the individual element of an array using array name and
index variable as below:
Matrix [0][0] Matrix [0][1] Matrix [0][2]
Matrix [1][0] Matrix [1][1] Matrix [1][2]
Matrix [2][0] Matrix [2][1] Matrix [2][2]
 It is also possible to initialize all the elements of an array at the time
of creating an array.
 The general syntax is given below:
 Data Type Array_Name [] []…[] = {Valu1, Value2, Value3…
ValueN};
 It is not compulsory to define size for each dimension in Multi
Dimension Array. You need to define size for only first dimension. The
size for remaining dimension can be defined manually by you.
 Consider the following example:
 Example:
public class OneDimArrayDemo1
{
public static void main(String[] args)
{
int Matrix [][] = new int [3][3];
int i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
Matrix[i][j]=10;
}
}
System.out.println("Elements of array are:");
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
System.out.print(Matrix[i][j]+ " ");
}
System.out.println();
}
}
}
 Output:

1.4 Operators
Operator (Definition): An Operator is a one type of symbol that instruct
computer to perform certain operations on the operands.
Operators are always associated with operands. Based on the operands
operators can be classified into following three categories:
(1)Unary Operator:
 Operator having only one operand is known as Unary operator.
 For Example: -a
(2)Binary Operator:
 Operator having two operands is known as Binary Operator.
 For Example: +, *, / etc…
(3)Ternary Operator:
 Operator having three operands is known as Ternary Operator.
 For Example: ? :
Based on the type of the operation that is performed by the operators it can
be classified into following seven categories:
(1)Arithmetic Operator:
 Arithmetic Operators are used to perform arithmetic calculations on its
operands.
 Following are the list of Arithmetic Operators:
(1) Unary Plus (+):
 It multiplies its operand by +1.
 It is Unary Operator.
 Example:
int a = 5;
System.out.println (“+a:”+ (+a));
It display +a: +5
(2) Unary Minus (-):
 It multiplies its operand by -1.
 It is Unary Operator.
 Example:
int a = 5;
System.out.println (“-a:”+ (-a));
It display -a: -5
(3) Binary Plus (+):
 It will add the value of operand to its right to the value of
operand to its left.
 It is Binary Operator.
 Example:
int a=5,b=6;
System.out.println (“a + b:”+ (a + b));
It display a + b: 11
(4) Binary Minus (-):
 It will subtract the value of operand to its right from the value
of operand to its left.
 It is Binary Operator.
 Example:
int a=5,b=6;
System.out.println (“a - b:”+ (a - b));
It display a - b: -1
(5) Multiplication (*):
 It will multiply the value of operand to its right with the value of
operand to its left.
 It is Binary Operator.
 Example:
int a=5,b=6;
System.out.println (“a * b:”+ (a * b));
It display a * b: 30
(6) Division (/):
 It will divide the value of operand to its left by the value of
operand to its right.
 It is Binary Operator.
 If both the operands are of type integer then it will ignore the
portion after the decimal point of the result. If any of the
operand is of type floating point then it display the result with
decimal portion.
 Example:
int a=5,b=6;
System.out.println (“a / b:”+ (a / b));
It display a / b: 0
int a=5;
float b=6;
System.out.println (“a / b:”+ (a / b));
It display a / b: 0.8333333
(7) Modulo (%):
 It will divide the value of operand to its left by the value of
operand to its right and return the remainder of the division.
 It is Binary Operator.
 It can be applied to both integer as well as floating point
numbers.
 Example:
int a=5,b=6;
System.out.println (“a % b:”+ (a % b));
It display a % b: 5
int a=5;
float b=6;
System.out.println (“a % b:”+ (a % b));
It display a % b: 5.0
 Example:
public class ArithmeticDemo1
{
public static void main(String[] args)
{
int a = 5, b = 6;
System.out.println("+a :"+ (+a));
System.out.println("-a :"+ (-a));
System.out.println("a + b :"+ (a+b));
System.out.println("a - b :"+ (a-b));
System.out.println("a * b :"+ (a*b));
System.out.println("a / b :"+ (a/b));
System.out.println("a % b :"+ (a%b));
}
}
 Output:

(2)Relational Operator:
 Relational Operators are used to determine relation between its two
operands.
 Normally they are used to test condition in the program. If the
condition is true then it returns true otherwise it returns false.
 Following are the list of Relational Operators:
(1) Equal To (==):
 It compares it’s to operands for equality.
 If both operands are equal then it returns true otherwise it
returns false.
 Example:
int a = 5, b = 6
System.out.println ((a==b));
It returns false.
(2) Not Equal To (! =):
 It compares it’s to operands for equality.
 If both operands are not equal then it returns true otherwise it
returns false.
 Example:
int a = 5, b = 6
System.out.println ((a!=b));
It returns true.
(3) Less than (<):
 It compares it’s operands to test weather the value of operand
to its left is less than the value of operand to its right.
 If the value of operand to its left is less than the value of
operand to its right then it returns true otherwise it returns
false.
 Example:
int a = 5, b = 6
System.out.println ((a<b));
It returns true.
(4) Greater than (>):
 It compares it’s operands to test weather the value of operand
to its left is greater than the value of operand to its right.
 If the value of operand to its left is greater than the value of
operand to its right then it returns true otherwise it returns
false.
 Example:
int a = 5, b = 6
System.out.println ((a>b));
It returns false.
(5) Less than or Equal To (<=):
 It compares it’s operands to test weather the value of operand
to its left is less or equal to the value of operand to its right.
 If the value of operand to its left is less than or equal to the
value of operand to its right then it returns true otherwise it
returns false.
 Example:
int a = 5, b = 6
System.out.println ((a<=b));
It returns true.
(6) Greater than or Equal To (>=):
 It compares it’s operands to test weather the value of operand
to its left is greater than or equal to the value of operand to its
right.
 If the value of operand to its left is greater than or equal to the
value of operand to its right then it returns true otherwise it
returns false.
 Example:
int a = 5, b = 6
System.out.println ((a>=b));
It returns false.
 Example:
public class RelationalDemo1
{
public static void main(String[] args)
{
int a =5, b=6;
System.out.println("a equal to b:" + (a==b));
System.out.println("a not equal to b:" + (a!=b));
System.out.println("a less than b:" + (a<b));
System.out.println("a greater than b:" + (a>b));
System.out.println("a less than or equal to b:" + (a<=b));
System.out.println("a greater than or equal to b:" + (a>=b));
}
}
 Output:

(3)Logical Operator:
 Logical Operators are operates on Boolean values. You can use Logical
Operator to combine two Boolean operands to represent a single
Boolean expression.
 Logical Operators are used when we want to combine two conditions
and produce the result based on that combined condition.
 Following are the list of Logical Operators:
(1)Logical NOT (!):
 It will complement (inverts) the value of its operand.
 It is Unary Operator.
 Truth Table for Logical NOT:
Operand Result
true False
false True
(2)Logical OR (|):
 It will combine its two operand and returns true if any of its
operand is true. If its both operands are false then it returns
false.
 It is Binary Operator.
 Truth Table for Logical OR:
Operand1 Operand2 Result
False False False
False True True
True False True
True True True
(3)Logical AND (&):
 It will combine its two operand and returns true if and only if
both of its operand is true. If any of its operand is false then it
returns false.
 It is Binary Operator.
 Truth Table for Logical OR:
Operand1 Operand2 Result
False False False
False True False
True False False
True True True
(4)Logical XOR (^):
 It will combine its two operand and returns true if and only if
it’s both operand is not equal. If it’s both operands is equal
then false.
 It is Binary Operator.
 Truth Table for Logical OR:
Operand1 Operand2 Result
False False False
False True False
True False False
True True True

(5)Short circuit OR (||):


 It works same as Logical OR operator. It will combine its two
operand and returns true if any of its operand is true. If its both
operands are false then it returns false.
 It is Binary Operator.
 It is called Short circuit OR because if it’s left operand is true
then it will not evaluate its right operand and returns true
which is very efficient.
(6)Short circuit AND (&&):
 It works same as Logical AND operator. It will combine its two
operand and returns true if and only if both of its operand is
true. If any of its operand is false then it returns false.
 It is Binary Operator.
 It is called Short circuit AND because if it’s left operand is false
then it will not evaluate its right operand and returns false
which is very efficient.
 Example:
public class LogicalDemo1
{
public static void main(String[] args)
{
boolean a,b;
a=true;
b=false;
System.out.println ("!a :"+ (!a));
System.out.println ("a | b :"+ (a | b));
System.out.println ("a & b :"+ (a & b));
System.out.println ("a ^ b :"+ (a ^ b));
System.out.println ("a && b :"+ (a && b));
System.out.println ("a || b :"+ (a || b));
}
}
 Output:

(4)Assignment Operator:
 Assignment Operators are used to assign the value of the operand or
expression to its right to the operands to its left.
 Following are the list of Assignment Operators:
(1)Assignment (=):
 It will assign the value of the operand or expression to its right
to the operand to its left.
 It is Binary Operator.
 The value to the right of the = operator must compatible with
the type of the operand to the left of the = operator.
 Example:
int a=5,b=5;
int c = a + b;
 If the operand to the both side of the assignment operator is
same in the expression then you can write them in short as
shown below:
a = a + 5;
a += 5;
 Here += is known as short hand assignment operator.
Following are other short hand assignment operators supported
by Java:
-=, *=, /=, %=
 Example:
public class AssignmentDemo1
{
public static void main(String[] args)
{
int a = 5, b=5, c=6;
int d;
d = a+=(b-c);
System.out.println("D="+d);
}
}
 Output:

(5)Increment and Decrement Operator:


 Arithmetic Operators are used to perform arithmetic calculations.
 Following are the list of Increment and Decrement Operators:
(1)Increment Operator:
 Increments the value of its operand by one.
 It is Unary Operator.
 There are two forms of Increment Operator:
(A) Postfix Increment Operator (a++): It will first use the
value of the operand to its left and then increment the value of
its operand.
For Example:
int a = 5, b;
b = a++
After Execution:
b=5
a=6
(B) Prefix Increment Operator (++a): It will first
increments the value of its operand to its right and then use the
value of its operand.
For Example:
int a = 5, b;
b = ++a
After Execution:
b=6
a=6
(2)Decrement Operator:
 Decrements the value of its operand by one.
 It is Unary Operator.
 There are two forms of Decrements Operator:
(A) Postfix Decrement Operator (a--): It will first use the
value of the operand to its left and then Decrements the value
of its operand.
For Example:
int a = 5, b;
b = a--
After Execution:
b=5
a=4
(B) Prefix Decrement Operator (--a): It will first
decrements the value of its operand to its right and then use
the value of its operand.
For Example:
int a = 5, b;
b = --a
After Execution:
b=4
a=4
 Example:
public class IncreDecreDemo1
{
public static void main (String[] args)
{
int a = 5,b=5;
a=++a;
b=--b;
System.out.println ("Value of a after Increment:"+ a);
System.out.println ("Value of b after Decrement:"+ b);
}
}
 Output:

(6)Bitwise Operator:
 Bitwise Operators are used to manipulate operands at bit level.
 Bitwise Operators perform operation individually on each bit of the
operands.
 Following are the list of Bitwise Operators:
(1)Bitwise NOT (~):
 Bitwise NOT operator complements (inverts) each individual bit
of the operand to its right.
 It is Unary Operator.
 Example:
22 = 00010110
~22 = 11101001 = -23
(2)Bitwise OR (|):
 Bitwise OR operator performs OR operation on each individual
bits of its two operands. It produces 0 if both bits at the same
position are equal to 0. If any of the bits is 1 then it produces
1.
 It is Binary Operator.
 Example:
22 | 23 = 23
23 = 00010111
22 = 00010110
23 | 23 = 00010111 = 23
(3)Bitwise AND (&):
 Bitwise AND operator performs AND operation on each
individual bits of its two operands. It produces 1 if both bits at
the same position are equal to 1. If any of the bits is 0 then it
produces 0.
 It is Binary Operator.
 Example:
22 & 23 = 22
23 = 00010111
22 = 00010110
23 & 22= 00010110 = 22
(4)Bitwise XOR (^):
 Bitwise XOR operator performs XOR operation on each
individual bit of its two operands. It produces 1 if both bits at
the same position are not equal. If both bits at the same
position are equal then it produce 0.
 It is Binary Operator.
 Example:
23 ^ 22 = 1
23 = 00010111
22 = 00010110
23 ^ 22 = 00000001 = 1
(5)Bitwise Shift left (<<):
 Bitwise Shift left operator shifts each bit specified number of
position to left side.
 It is unary operator.
 Example:
22<<2
22 = 00010110
22<<2 = 01011000 = 88
It will shift each bit of the operands two position to the left
side. So the left most two bits from the number are shifted out
and it will be replaced by two zeros at right side.
(6)Bitwise Shift right (>>):
 Bitwise Shift right operator shifts each bit specified number of
position to right side.
 It is unary operator.
 Example:
22>>2
22 = 00010110
22>>2 = 00000101 = 5
It will shift each bit of the operands two position to the right
side. So the right most two bits from the number are shifted
out and it will be replaced by two zeros at left side.
(7)Ternary Operator (? :):
 It is also known as the conditional operator.
 It is called ternary operator because it has three operands.
 The general syntax of the Ternary Operator is given below:
(Expression1)? Expression2: Expression3;
 Expression1 should contain the condition to be checked using
relational operators.
 First it will check the Expression1. If the Expression1 is true then it will
executes the Expression2 otherwise it will executes the Expression3.
 It can be useful in the place of If … Else Statement.
 Example:
public class TernaryDemo1
{
public static void main(String[] args)
{
int a = 5, b=6;
int max;
max = (a>b)? a: b;
System.out.println (max + " Is maximum");
}
}
 Output:

 Operator Precedence:

Highest
() [] .
++ –– ~ !
* / %
+ –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest
1.5 Overview of control statements
Control statements in JAVA can be classified into two categories:
(1) Conditional Control Statements:
 Conditional Control Statement first test for the condition or expression
and based on the outcome of that condition or expression allows you
to control execution of the different portion of the code at run time.
 Following are the list of Conditional Control Statements:
(1) Simple if
(2) if … else
(3) Nested if statement
(4) if … else if ladder statement
(5) switch case statement
(2) Looping Control Statements:
 Looping control statements allows you to execute certain portion of the
code repeatedly based on the condition.
 Sometimes it is required to execute some portion of the code
repeatedly for specific number of times or until some condition is
satisfied at that time you can use Looping Control statements.
 Following are the list of Looping Control Statements:
(1) for
(2) while
(3) do … while
1.5.1 Conditional Control Statement
Conditional Control Statement first test for the condition or expression and
based on the outcome of that condition or expression allows you to control
execution of the different portion of the code at run time.
Following are the list of Conditional Control Statements:
(1) Simple if Statement:
The general syntax of simple if statement is given below:
if (condition)
{
Statement block;
}
Statement-x;
In simple if statement first condition is checked.
If the condition is true then it will executes the statement block and then
executes the statement-x that is followed by simple if statement.
If the condition is false then it will not execute the statement block and
executes the statement-x that is followed by simple if statement.
If the statement block contains only one statement inside it then there is no
need to use curly brackets. But if statement block contains more then one
statements inside it then you must have to write them inside curly brackets.
Flowchart:
Statement Block Conditio
n

Statement-X

Example:
public class SimpleIfDemo
{
public static void main (String[] args)
{

int mark = 32;


if (mark<35)
System.out.println ("Sorry! You Fail");
}
}
Output:

(2) if … else statement:


The general syntax of if … else statement is given below:
if (condition)
{
true statement block;
}
else
{
false statement block;
}
Statement-x;
In if … else statement first condition is checked.
If the condition is true then it will executes the true statement block and then
executes the statement-x that is followed by if … else statement.
If the condition is false then it will executes the false statement block and
then executes the statement-x that is followed by if … else statement.
If the true statement block and false statement block contains only one
statement inside it then there is no need to use curly brackets. But if they
contain more then one statements inside it then you must have to write them
inside curly brackets.
Flowchart:

True False

True Statement Conditio


False Statement
Block n
Block

Statement-X

Example:
public class IfElseDemo
{
public static void main(String[] args)
{
int a = 5, b = 6;
if (a>b)
System.out.println (a + " Is Maximum");
else
System.out.println (b + " IS Maximum");
}
}
Output:

(3) Nested if statement:


When one if statement is placed within another if statement then it is known
as Nested if statement.
The general syntax of nested if statement is given below:
if (conditiion1)
{
if (condition2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-X;
In the above syntax first condition1 is check.
If condition1 is true then it will check condition2. If condition2 is true then it
will executes statement1 and then statement-X followed by nested if
statement. If condition2 is false then it will executes stetement2 and then
statement-X followed by nested if statement.
If condition1 is false then it will executes statement3 and then statement-X
followed by nested if statement.
While writing Nested if statement care should be taken that each if statement
must associated with matching else statement.
Flowchart:
True False

Ststement3
Conditio
n1

True False

Statement1 Conditio Statement2


n2

Statement-X

Example:
public class NestedIfDemo
{
public static void main(String[] args)
{
int temp=38;
if (temp>40)
{
if (temp>45)
System.out.println("Very Hot");
else
System.out.println("Hot");
}
else
System.out.println("Average");
}
}
Output:

(4) if … else if ladder statement:


The general syntax of if…else if ladder is given below:
if (condition1)
statement1;
else if (condition2)
statement2;
………..
………..
else if (conditionN)
statementN;
else
default statement;
In if…else if ladder statement first condition1 is checked.
If condition1 is true then statement1 will executes but if condition1 is false
then condition2 is checked.
If condition2 is true then statement2 will executes but if condition2 is false
then condition3 is checked.
This process is repeated until any of the condition specified becomes true.
If all the condition specified in the if…else if ladder statement evaluates to
false then default statement associated with else will executes.
Flowchart:

False

Condition
1

True
False

Statement1 Condition
2

True
False

Statement2 Condition
N

True

StatementN

Default
Statement

Statement X

Example:
public class IfElseIfLadderDemo
{
public static void main(String[] args)
{
int per=66;
if (per >=66)
System.out.println("Distinction");
else if (per <66 && per >=60)
System.out.println("First Class");
else if (per <60 && per >=50)
System.out.println("Second Class");
else if (per <50 && per >=40)
System.out.println("Pass Class");
else
System.out.println("Fail");
}
}
Output:

(5) switch case statement:


switch case statement is useful when you are given list of choices and from
which you have to select only one option at a time.
It is also known as multiple choice statement. It is an alternative option of if…
else if ladder statement.
The general syntax of switch case statement is given below:
switch (expression)
{
case value1:
Statement Block1;
break;
case value2:
Statement Block1;
break;
…………………………………….
……………………………………
case valueN;
Statement BlockN;
break;
default:
Default statement block;
}
In switch case statement first the expression is evaluated. After evaluating
the expression the value of expression is compared with the value of case
specified inside the switch block. When the value of expression matches with
any case value the statement block associated with that case will executed.
If the value of expression does not match with any case value then the
default statement block associated with default will executed.
Each case statement followed by colon symbol (:).
Note that there is a break statement at the end of each case statement block.
If you don’t specify the break statement then all the statement blocks
followed by the matching case statement block also executed. If you specify
the break statement then after executing the matching statement block
control of the program transfer to the end of switch case statement and
executes the statement followed by switch case statement.
Flowchart:

Expression

Value N No Match
Value 1 Value 2

Statement Statement Statement Default


Block 1 Block 2 Block N Block

Example:
public class SwitchCaseDemo
{
public static void main(String[] args)
{
float a=5,b=6,c;
int ch=3;
switch (ch)
{
case 1:
System.out.println("a + b = " + (a+b));
break;
case 2:
System.out.println("a - b = " + (a-b));
break;
case 3:
System.out.println("a * b = " + (a*b));
break;
case 4:
System.out.println("a / b = " + (a/b));
break;
default:
System.out.println("Wrong Choice");
}
}
}
Output:

1.5.2 Looping Control Statement


Looping control statements allows you to execute certain portion of the code
repeatedly based on the condition.
Sometimes it is required to execute some portion of the code repeatedly for
specific number of times or until some condition is satisfied at that time you
can use Looping Control statements.
Following are the list of Looping Control Statements:
(1) while:
while loop is used to repeatedly perform some task until condition
specified within while loop is satisfied. It is also known as iterative
statement.
The general syntax of while loop is given below:
while (condition)
{
Body of Loop
}
In while loop first the condition is checked. If condition is true then the
statements written inside body of loop are executed. After executing
statements inside body of loop again the condition is checked.
This process is repeated until condition specified within while loop
becomes false. As the condition becomes false the statements inside
body of loop is not executed and the statements followed by the while
loop is executed.
It is also known as entry controlled loop because the condition is
checked first and then body of the loop is executed based on the
condition. So if condition is false at the first trial the body of loop will
never executes.
Flowchart:

False
Condition

True

Body of Loop

Example:
public class WhileDemo
{
public static void main(String[] args)
{
int i=1,sum=0;
while (i<=10)
{
sum+=i;
i++;
}
System.out.println ("Sum of 1 to 10 is:"+sum);
}
}
Output:

(2) do … while:
do …while loop is used to repeatedly perform some task until condition
specified within do … while loop is satisfied. It is also known as
iterative statement.
The general syntax of do … while loop is given below:
do
{
Body of Loop
} while (condition);
In do … while loop first statements written inside body of the loop are
executed. After executing statements inside body of the loop condition
is checked. If condition is true then the statements written inside body
of loop are executed again.
This process is repeated until condition specified within do … while loop
becomes false. As the condition becomes false the statements inside
body of loop is not executed and the statements followed by the do …
while loop is executed.
It is also known as exit controlled loop because the condition is
checked at last and then body of the loop is executed based on the
condition. So even if condition is false at the first trial the body of loop
executes at least once.
Flowchart:

Body of Loop

Condition

True False

Example:
public class WhileDemo
{
public static void main(String[] args)
{
int i=1,sum=0;
do
{
sum+=i;
i++;
} while (i<=10);
System.out.println ("Sum of 1 to 10 is:"+sum);
}
}
Output:

(3) for:
for loop is used to repeatedly perform some task for specific number of
times. It is also known as iterative statement. It is useful when you
know in advance how many times you want to repeat the task.
The general syntax of for loop is given below:
for (initialization; condition; iteration)
{
Body of loop
}
Here,
Initialization: It indicates the starting point for the loop. Starting
point specifies from which value the loop will start the iteration.
Condition: It indicates control condition for the loop. Control condition
determines when loop will stop.
Iteration: It indicates how the value of the counter variable that holds
the starting value will vary. You can either increment or decrement the
value of the counter variable based on your requirement.
In for loop first the counter variable is initialized with the starting value
in the initialization part. After initialization the condition is checked. If
the condition is true then the statements written inside body of loop
will executes. After executing statements inside body of loop the
control goes to the Iteration part where the value of the counter
variable is incremented decremented. After changing the value of the
counter variable it again check the condition.
This process is repeated until condition specified within for loop
becomes false. As the condition becomes false the statements inside
body of loop will not executes and control transfer immediately to the
statement followed by for loop.
Flowchart:

Initialization

False
Condition

True

Body of Loop

Iteration
(Increment or
Decrement)

Example:
public class ForLoopDemo
{
public static void main(String[] args)
{
int a=0,b=1,c;
int i;
System.out.println ("Fibonacci Series :");
System.Out.print (a+" ");
System.Out.print (b+" ");
for (i=1;i<=5;i++)
{
c=a+b;
System.Out.print (c+" ");
a=b;
b=c;
}
}
}

Output:
1.5.3 break and continue:
 break:
break statement allows you to:
(1)Transfer the control of the program immediately after the loop
either conditionally or unconditionally.
 It allows you to transfer the control of the program outside the loop in
which it exist.
 You can break the execution of the loop either conditionally or
conditionally.
 If you write break statement inside the nested loop then it will transfer
program control to the outside loop in which it exist.
 Consider following example:
public class breakDemo
{
public static void main(String[] args)
{
int i;
for (i=1;i<10;i++)
{
if (i%5==0)
break;
else
System.Out.print(i+" ");
}
}
}
 Output:

(2)Transfer the control of the program immediately after the switch


case statement.
 It allows you to transfer the control of the program outside the switch
case statement after executing matching case statement.
 You need to write break statement at the end of each case block. If you
don’t specify the break statement in case block then it will executes all
case block after the matching case block.
 Consider following example:
public class breakDemo
{
public static void main(String[] args)
{
int ch=1;
switch(ch)
{
case 1:
System.out.println("Blue");
break;
case 2:
System.out.println("Green");
break;
case 3:
System.out.println("Red");
break;
}
}
}
 Output:

 Now consider the following program without writing break in each case
block:
public class breakDemo
{
public static void main(String[] args)
{
int ch=1;
switch (ch)
{
case 1:
System.out.println ("Blue");
case 2:
System.out.println ("Green");
case 3:
System.out.println ("Red");
}
}
}
 Output:
 Here, it will execute each case block because you don’t specify break
statement in the case blocks.
(3) Transfer the control of the program after specific loop in nested
loop.
 It allows you to specify label with break statement. Using this statement
you can transfer the control of the program outside the specified loop.
 It is useful while dealing with nested loop. When you write break
statement inside the inner loop it will transfer the control of the program
only after that inner loop. However sometimes it is required to transfer
program control outside all the loops or outside specific loop.
 This form of break statement is also known as labeled loop.
 The label must be specified at the starting of loop and it must ends with
colon.
 Consider following example:
public class breakDemo
{
public static void main(String[] args)
{
int i,j;
outerloop:
for(i=1;i<10;i++)
{
innerloop:
for(j=1;j<=i;j++)
{
if (i%j==0)
System.out.print(j);
else
break outerloop;
}
System.out.println(" ");
}
}
}
 Output:

It must appear inside for, while, do while or switch case statement.


 continue:
continue statement allows you to skip the statements immediately after the
continue statement and transfer the control of the program to the next
iteration in the loop.
It must appear inside for, while or do while loop.
Consider the following example:
public class continueDemo
{
public static void main(String[] args)
{
for (int i =0;i<10;i++)
{
if (i%2==0)
System.Out.print(i+" ");
else
continue;
}
}
}
Output:

1.6 Input and output in Java


In Java all the Input and Output operations are performed using the stream.
A stream is a sequence of bytes that is transferred from source to destination.

You might also like