0% found this document useful (0 votes)
29 views21 pages

Java - Unit1 2023-24 (CS Major)

JAVA

Uploaded by

web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views21 pages

Java - Unit1 2023-24 (CS Major)

JAVA

Uploaded by

web
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT-1

Introduction to Object-Oriented concepts


Object oriented programming
Simula is considered as the first object-oriented programming language. Popular object-oriented
languages are Java, C#, PHP, Python, C++ etc.
Oriented Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
o Dynamic Binding
Object:
Definition-1: Object means a real word entity such as pen, chair, table etc. It is a thing or instance of
class.
Definition-2: Any entity that has state and behaviour is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
An object contains an address and takes up some space in memory. Objects can communicate without
knowing details of each other's data or code, the only necessary thing is that the type of message accepted and
type of response returned by the objects.
Representation of object with an example in OOP is shown below.

Example: A Student is an object because it has states i.e. name, rollnumber,section etc. as well as behaviours
i.e. add, delete, edit student data and learn etc.
In java Object is created with following statement:
Classname Objectname =new Classname();
Students obj = new Students ();
Real Life Examples for Objects : Table, fan, pen etc.
UNIT-1

Class:
Collection of similar objects (same methods and properties) is called class. It is a logical entity.In
another way, a class can be defined as a template/blueprint that describes the behavior/state that the object of
its type supports.
Consider many student objects and logically group all student objects as class Students i.e.) shown below.
Objects: Student1 Student2 Student3 Student4
Class : Students
Class Symbolic notation in OOP is shown below.

Class Notation in java:


class ClassName
{
//body of class
}
Example for class:
class Students
{
String name;
void addStudent()
{
//body of function
}
}
Abstraction
Abstraction is process of hiding internal details and showing functionality of system is known as abstraction.
Example: 1.phone call, we don't know the internal processing.
2. Bike for riding, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) programme code and data together into a single unit is known as encapsulation.

Example: capsule, it is wrapped with different medicines.


UNIT-1
A java class is the example of encapsulation. It was encapsulated with private, public, protected data.
Inheritance
Deriving new class/object from existing class/object is called as inheritance.
It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
Ability to shown one thing in many forms. In another way, when one task is performed by different ways i.e.
known as polymorphism. In java, we use method overloading, method overriding to achieve
polymorphism.
Example1: cat speaks meow, dog barks woof etc

Example 2 (Operator Overloading): “+” symbol is used in different purposes in our programs shown
below.
2 + 2=4 (Integer addition)
“Ram” + “Krishna “ =”Ram Krishna “ (String Concatenation )

Procedural Oriented Programming VS Object-Oriented Programming


Procedural Oriented Programming Object-Oriented Programming
In procedural programming, the program is In object-oriented programming, the program is
divided into small parts called functions. divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows a bottom-
approach. up approach.
Procedural programming is based on the unreal Object-oriented programming is based on
world. the real world.
It is not appropriate for complex problems. It is appropriate for complex problems.
There is no code reusability present in procedural It offers code reusability by using the feature of
programming. inheritance.
It does not provide any inheritance. It achieves inheritance
UNIT-1

Adding new data and functions is not easy. Adding new data and function is easy.
It does not provide any inheritance. It achieves inheritance
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
In procedural programming, overloading is not Overloading is possible in object-oriented
possible. programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Java Programming
Introduction to java
Java is a programming language developed by James Gosling with other team members named Mike
Sheridan and Patrick Naughton also called as Green Team in 1995 for Sun Microsystems for digital
devices such as set-top boxes, televisions etc.
Java is a general-purpose, concurrent, object-oriented, class-based, and the runtime environment (JRE)
which consists of JVM which is the cornerstone of the Java platform.
Where Java used?
Java has been used in different domains. Some of them are listed below.
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications like irctc.co.in, http://www.nannayauniversity.info/ etc.
3. Enterprise Applications such as banking applications.
4. Mobile Applications.
5. Embedded Systems.
6. Smart Cards.
7. Robotics.
8. Games etc.
Features of JAVA
The main objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some awesome features which play important role in
the popularity of this language. The features of Java are also known as java buzzwords.
Lists of most important features of Java language are given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
UNIT-1
Simple:
Java is very easy to learn and its syntax is simple, clean and easy to understand. According to Sun, Java
language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many confusing and rarely-used features e.g. explicit pointers, operator overloading
etc.
o There is no need to remove unreferenced objects because there is Automatic Garbage Collection in
java.
Object-oriented
Java is object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporates both data and behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++ etc. which are compiled
into platform specific machines while Java is a write once, run anywhere language. A platform is the
hardware or software environment in which a program runs.

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox
Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There are lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
o There is exception handling and type checking mechanism in java. All these points make java robust.
UNIT-1
Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed.
Portable
Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't require
any type of implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g. C++). Java is an interpreted
language that is why it is slower than compiled languages e.g. C, C++ etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in java. This feature of
Java makes us able to access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes & dynamic linking. It means
classes are loaded on demand. Java supports automatic memory management (garbage collection).

JAVA VIRTUAL MACHINE


All language compilers translate source code into machine code for a specific computer. Java compiler
also does the same thing. Then, how does Java achieve architecture neutrality? The answer is that the Java
compiler produces an intermediate code known as bytecode for a machine that does not exist. This machine is
called the Java Virtual Machine and it exists only inside the computer memory. It is a simulated computer
within the computer and does all major functions of a real computer. This is shown in below fig.

.
UNIT-1
Java Program Structure
Java Program has the following specified sections:

Documentation Section:
The documentation section comprises a set of comment lines describing the programme for easy maintenance
and understand ability .Comments in java program are shown below.
1. // Single line comment
2. /*
Multiple line comments
*/
Package Statement:
The first statement allowed in a Java file is a package statement. This statement declares a package name and
informs the compiler that the classes defined here belong to this package.
Example: package packagename;
Import Statements:
The next thing after a package statement (but before any class definitions) may be a number of import
statements. This is similar to the #include statement in C. The below statement instructs the interpreter to load
io –classes contained in the sub package io.
Example : import java. io.*;
Interface Statements:
An interface is like a class but includes a group of method declarations. This is also an optional section and is
used only when we wish to implement the multiple inheritance features in the program.
Class Definitions:
A Java program may contain multiple class definitions. Classes are the primary and essential elements of a
Java program. But every java program must contain one class with main method. This main method defines
the execution flow of program.
Example java program:
//Example program
package Example;
import java.io.*;
class SarnpleOne
{
public static void rnain(String args[ ])
{
Systerm.out.println("Java is better than C++.");
}
}
UNIT-1

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two types of data
types in Java:
1. Primitive data types: The primitive data types include Integer, Character, Boolean, Floating Point.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the most basic
data types available in Java language. All variables must be declared before its use. There are 8 types of
primitive data types:
o boolean data type byte data type
o char data type short data type
o int data type long data type
o float data type double data type
Syntax: Datatypename variable_name ;
Example: int a;

Data Type Default Value Default size(in bytes) Default size(in bits)
boolean FALSE 1 bit 1 bit
char '\u0000' 2 byte 16 bits
Byte 0 1 byte 1 bit
short 0 2 byte 16 bits
Int 0 4 byte 32 bits
Long 0L 8 byte 64 bits
float 0.0f 4 byte 32 bits
double 0.0d 8 byte 64 bits
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false
UNIT-1
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement integer.
Its value range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example: byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768
to 32,767 (inclusive). Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about
memory.
Example: int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It
is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. It is generally used as the default data type for decimal values. Its default value is 0.0d.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
UNIT-1

Java Variables
A variable is a container which holds the value while the program is executed. A variable
is assigned with a data type. Variable is a name of memory location. There are three types of
variables in java.
1. local
2. instance
3. static

Example: int data=50; //Here data is variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared
among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class. Memory
allocation for static variable happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
1. class A
2. {
3. int data=50; //instance variable
4. static int m=100; //static variable
5. void method()
6. {
7. int n=90; //local variable
8. }
9. }//end of class
UNIT-1

Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example:
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types.
 Widening Casting(Implicit)

 Narrowing Casting(Explicitly done)

Widening or Automatic type conversion:


Automatic Type casting take place when,
 the two types are compatible
 the target type is larger than the source type
Example:
public class Test{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}

Int value 100


Long value 100
Float value 100.0
Narrowing or Explicit type conversion:
When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit
type casting.
Example:
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
UNIT-1
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}

Double value 100.04


Long value 100
Int value 100
Constants in Java
Java does not directly support constants. However, a static final variable is effectively a constant.
The static modifier causes the variable to be available without loading an instance of the class where it is
defined. The final modifier causes the variable to be unchangeable.
Java constants are normally declared in ALL CAPS. Words in Java constants are normally separated
by underscores.An example of constant declaration in Java is written below:
1 public class PI {
2 public static final float PI = 3.14;
3 }

Operators in Java

Java provides a rich set of operators environment. Java operators can be divided into following categories:
 Arithmetic operators
 Relation operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Misc operators
Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in algebra.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
UNIT-1

Example Program:
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}
Output :
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27
Relation operators:
The following table shows all relation operators supported by Java.
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Example Program:
public class Test {
public static void main(String args[]) {
UNIT-1

int a = 10,b = 20;


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("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
Example:
public class Test {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
This will produce the following result −
a && b = false
a || b = true
!(a && b) = true
Bitwise operators:
Java defines several bitwise operators that can be applied to the integer types long, int, short, char and byte
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
UNIT-1

>> left shift


<< right shift

Now lets see truth table for bitwise &, | and ^


A B a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shift the bit value. The left operand specifies the value to be shifted and the right
operand specifies the number of positions that the bits in the value are to be shifted. Both operands have the
same precedence.
Example:
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010
public class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
}
}
This will produce the following result −
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
UNIT-1

Assignment Operators
Assignment operator supported by Java are as follows:
Operator Description Example
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to a+=b is same
left as a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b
*= mutiply left operand with the right operand and a*=b is same
assign the result to left operand as a=a*b
/= divides left operand with the right operand and a/=b is same
assign the result to left operand as a=a/b
%= calculate modulus using two operands and a%=b is same
assign the result to left operand as a=a%b
Misc operator
There are few other operator supported by java language.
Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression,
epr1 ? expr2 : expr3
If epr1 Condition is true? Then value expr2: Otherwise value expr3
Example:
instanceOf operator
This operator is used for object reference variables. The operator checks whether the object is of particular
type (class type or interface type)

Reading Input with Java.util.Scanner Class


The java.util.Scanner class in Java is a versatile tool for reading input from various sources, including user
input from the console, files, and strings. Here's a quick guide on how to use the Scanner class for reading
user input from the console:
Steps to use Scanner class:
Import the Scanner Class: To use the Scanner, you need to import it at the top of your Java file:
import java.util.Scanner;
Create a Scanner Object: Instantiate a Scanner object to read input from System.in (the console):
Scanner scanner = new Scanner(System.in);
Reading Different Data Types: The Scanner class provides various methods to read different types of
input:
 Reads String: nextLine()
 Reads Integer: nextInt()
 Reads Double: nextDouble()
 Reads Boolean: nextBoolean()
 Read Long: nextLong()
UNIT-1
//Example of how to read different types of input:
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Reading a string
System.out.print("Enter your name: ");
String name = scanner.nextLine();

// Reading an integer
System.out.print("Enter your age: ");
int age = scanner.nextInt();

// Reading a double
System.out.print("Enter your height (in meters): ");
double height = scanner.nextDouble();

// Displaying the input


System.out.println("Hello, " + name + ". You are " + age + " years old and " + height + " meters tall.");

// Close the scanner


scanner.close();
}
}
Displaying Formatted Output with String.format()
In Java, String.format() is a powerful method for creating formatted strings. It allows you to insert variables
into a string and format them in various ways. Here's how it works:
Basic Syntax
String formattedString = String.format(format, arguments);

 format: A format string that specifies how the output should be structured.
 arguments: The values to be formatted and inserted into the format string.
Common Format Specifiers
 %s: String
 %d: Integer
 %f: Floating-point number
 %x: Hexadecimal
 %t: Date and time
Examples
1. Basic Formatting
int age = 25;
String name = "Alice";
String formatted = String.format("%s is %d years old.", name, age);
UNIT-1
System.out.println(formatted); // Output: Alice is 25 years old.
2. Floating-Point Precision
double pi = 3.14159;
String formatted = String.format("Value of Pi: %.2f", pi);
System.out.println(formatted); // Output: Value of Pi: 3.14

Control Statements
A Control statement is a statement that controls the flow of execution of the program. Java‟s program control
statements are divided into 3 categories
● Selection Statements
● Iteration Statements
● Jump Statements
1)Selection Statements:
Selection statement controls the flow of the program depending on the result of the conditional expression
or the state of a variable. There are two selection statements: if and switch
a. if statement:
„if‟ is a selection statement that is used to choose two choices in a program.
Syntax: Example
if(condition) if(condition)
statement1; System.out.println(“if block”);
else else
statement2; System.out.println(“else block”);
 „condition‟ is any expression that returns a Boolean value (i.e., true/false). Statement is a single
or multiple statements.
 If the condition is true then the control goes to the statement1 and it is executed. Otherwise, the
statement2 is executed.

b. Nested if statement:
It means an if statement under another if statement.
Syntax:
if(condition)
{
if(condition)
statement;
}
c. If - else- if ladder:
if-else-if statement is a sequence of if-else statements. In if-else-if ladder if a condition is not met then the
control flows from top to bottom until the last if statement.
Syntax:
if(condition)
statement1;
else if(condition)
statement2;
else if(condition)
UNIT-1
statement3;
. …..
else statementn;

d. switch statement: It provides more than one choice to choose. It‟s a better alternative to if-else-if
ladder.
Syntax:
switch(expression) public class Test {
{ public static void main(String args[]) {
case value1: statement1; // char grade = args[0].charAt(0);
break; char grade = 'C';
case value2: statement2; switch(grade) {
break; case 'A' :
case value3: statement3; System.out.println("Excellent!");
break; break;
. case 'B' :
. case 'C' :
case valueN: statementN; System.out.println("Well done");
break; break;
default : statement; case 'F' :
} System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

Here, the expression may be of type byte, short, int or char only. the case values must be of type expression
and each value should be unique. When control comes to the switch statement then the value of the expression
is compared with the case values, if a match is found then the statement(s) corresponding to that case is
executed. If none of the case is matched then the default statement is executed.
2) Iteration Statements: These statements allow the part of the program to repeat one or more times until
some condition becomes true. There are 3 iteration statements: while, do-while and for.
a. while statement: „while‟ is an iteration statement, that repeats a statement or block of statements until
some condition is true.
Syntax:
Syntax Example
while(condition) public class Test {
{ public static void main(String args[]) {
// body of the loop int x = 10;
} while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
UNIT-1
where the condition may be any boolean expression. The body of the loop will be executed as long as the
condition is true. Once the condition becomes false, the control passes to the statement immediately after
the while loop.
b. do-while statement:
„do-while‟ statement is very much similar to while statement with little difference. In while
statement, if the condition is initially false then the body of loop will not be executed at all. Where as
in do-while statement, body of the loop will be executed at least once since the condition of do-while
is at the bottom of the loop.

Syntax Example
Do public class Test {
{ public static void main(String args[]) {
// body of the loop int x = 10;
} while(condition); do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Each iteration of do-while executes the body of loop first and evaluates the condition later. If condition
is true, the loop repeats. Otherwise, the loop terminates.
c. for statement:
„for‟ statement also repeats the execution of statements while its condition is true.
Syntax:
Syntax Example
for(initialization; public class Test {
condition; iteration) public static void main(String args[]) {
{ for(int x = 10; x < 20; x = x + 1) {
// body of the loop System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
}
Where initialization portion of the loop sets the value of the variable that acts as a counter. This
portion is executed first when the loop starts. And it is executed only once. When the control goes to
condition, condition is evaluated. If condition is true, the body of loop is executes. Otherwise the loop
terminates. Next iteration portion is executed. This helps to increment or decrement the control
variable.
The loop then iterates evaluating condition, then executing the body and then executing the
iteration portion each time it iterates.
2) Jump Statements:
Jump statements allow the control to jump to a particular position. There are 3 types of jump
statements.
a. break statement:
In java, there are 3 uses of break statement.
i. It helps to terminate a statement sequence in switch statement.
UNIT-1
ii. It can be used to exit or terminate the loop
iii. It can be used as another form of goto
Example:
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
if(i==10)
break; // terminates loop if i is 10
System.out.println(“i :”+i);
}
}
}
b. continue statement: The continue statement starts the next iteration of the immediately enclosing
iteration statements (while, do-while or for). When the control goes to continue statement, then it skips
the remaining statements and starts the next iteration of enclosing structure. Example shown below.
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
System.out.println(“i :”+i);
if(i%2==0)
continue;
System.out.println(“ “);
}
}
}
c. return statement: This is used to return from a method. When the control reaches to return
statement, it causes the program control to transfer back to the caller of the method. Example shown
below.
class A
{
public static void main(String arg[])
{
boolean t=true;
if(t)
return;
System.out.println(“Hi”); // This won‟t execute
}
}

You might also like