OOP Using JAVA Unit-I
OOP Using JAVA Unit-I
UNIT-I
Object-Oriented Paradigm
1
OOP using JAVA
OOP Principles
Class
Object
Data Abstraction and Data Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
Class:
2
OOP using JAVA
The entire set of data and code of an object can be made a user defined data
type using the concept of a class. In fact Objects are treated as variables of the type
Class. Once a Class has been defined, we can create any number of objects
belonging to that Class.
Class <clsname>
{
Variable Declaration;
Methods Definition;
}
Object:
Definitions of an Object
3
OOP using JAVA
Data Abstraction:
Abstraction represent taking out the behavior from how exactly it’s
implemented.
Data Encapsulation:
Inheritance:
Polymorphism:
Polymorphism means the ability to take more than one form. For example,
an operation may exhibit different behavior in different instances. The behavior
depends upon the type of data used in the operation. The following is an example
for polymorphism concept.
Dynamic Binding:
5
OOP using JAVA
Message passing:
Objects have a life cycle. They can be created and destroyed. Communication with
an object is feasible as long as it is alive.
Benefits of OOP:
OOP offers several benefits to the program designer and the user. The
principal advantages are:
Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
6
OOP using JAVA
The principle of data hiding helps the programmers to built secure program.
Applications of OOP
Real-time systems
Simulation and modeling
Object oriented databases
Hypertext, hypermedia and expert text.
AI and expert systems.
Neural networks and parallel programming.
Decision support and office automation systems.
*************************************************************
Procedural and Object-Oriented Programming paradigm
Below are some of the differences between procedural and object-oriented
programming:
7
OOP using JAVA
4. Adding new data and functions is not 4. Adding new data and function is easy.
easy.
5. Procedural programming does not 5. Object-oriented programming provides
have any proper way of hiding data so it data hiding so it is more secure.
is less secure.
6. In procedural programming, 6. Overloading is possible in object-oriented
overloading is not possible. programming.
7. In procedural programming, there is 7. In object-oriented programming, the
no concept of data hiding and concept of data hiding and inheritance is
inheritance. used.
8. In procedural programming, the 8. In object-oriented programming, data is
function is more important than the data. more important than function.
9. Procedural programming is based on 9. Object-oriented programming is based on
the unreal world. the real world.
10. Procedural programming is used for 10. Object-oriented programming is used
designing medium-sized programs. for designing large and complex programs.
11. Procedural programming uses the 11. Object-oriented programming uses the
concept of procedure abstraction. concept of data abstraction.
12.Code reusability absent in procedural 12. Code reusability present in object-
programming, oriented programming.
Examples: C, FORTRAN, Pascal, Examples: C++, Java, Python, C#, etc.
Basic, etc.
*******************************************************************
8
OOP using JAVA
An Overview of Java
To write a java program, we first define classes and then put them together.
A Java program may contain one or more sections as shown in below.
9
OOP using JAVA
Documentation Section
The documentation section contains a set of comment lines giving the name
of the program, the author and other details.
There are three types of comments in java – single line, multi line, and Java
documentation.
Example:
These comments start with /** and end with */. These comments are used
to provide description for every feature in a java program.
Package Statement
Example
package student;
10
OOP using JAVA
Import Statement
This statement instructs the interpreter to load the test class contained in the
package student.
Interface Statements
Class Definitions
A Java program may contain multiple class definitions. Classes are the
primary and essentials of a Java program.
Since every Java stand-alone program requires a main method as its starting
point, this class is the essential part of a java program. A simple java program may
contain only this part. The main method creates objects of various classes and
establishes communications between them. On reaching the end of main, the
program terminates and the control passes back to the operating system.
//Sample.java
Class Sample
11
OOP using JAVA
Class Declaration
class Sample
Opening Brace
Every class definition in java begins with an opening brace “{“ and ends
with a matching closing brace “ } ”.
defines a method named main. Every Java application program must include
the main () method. This is the starting point of the interpreter to begin the
execution of the program.
A Java program can have any number of classes but only one of them must include
a main method to initiate the execution.
public: The keyword public is an access specifier that declares the main
method is accessible to all other classes.
12
OOP using JAVA
The method println() always append a new line character to the end of the string.
*******************************************************************
History of JAVA
13
OOP using JAVA
14
OOP using JAVA
**Platform Independent
A program or technology is said to be platform independent if and only if
which can run on all available operating systems.
The language JAVA will have a common data types and the common
memory spaces on all operating systems. The JAVA software contains the special
programs which converts the format of one operating system to another format of
other operating system. Hence JAVA language is treated as platform independent
language.
**Architectural Neutral
A language or technology is said to be architectural neutral which can run on
any available processors in the real world. The languages like C, C++ are treated as
architectural dependent. The language Java can run on any of the processor
irrespective of their architecture and vendor.
Portable
A portable language is one which can run on all operating systems and on all
processors irrespective of their architectures and providers. The languages like C,
C++ are treated as non-portable languages whereas the language Java is called
Portable language.
Portability= Platform Independent + Architectural Neutral
15
OOP using JAVA
Multithreaded
Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. This means that we need not wait for the application to
finish one task before beginning another. For example, we can listen to an audio
clip while scrolling a page and at the same time download an applet from a remote
computer.
Distributed
Java is designed as a distributed language for creating the applications on
networks. It has the ability to share both data and programs. Java programs can
open and access remote objects on Internet as easily as they can do in a local
system.
Robust
Java is one of the Robusted programming language. Since java programming
language effectively addresses the run time errors. In Java programming runtime
errors are known as Exceptions.
The languages like C, C++ are treated as week programming languages (Not
Robust), since they are unable to deal with runtime errors. Runtime errors are
occurred when we enter invalid input.
Note:
Compile time errors are occurring when the programmer is not following
syntax rules of the programming language.
Secure
Java is one of the most secured programming languages. To provide the
security to our java real time applications, we need not to write our own security
code. Since java library (API) contains readily available security programs for
protecting confidential information from unauthorized users.
Hence java is one of the powerful secured programming languages.
High Performance
Java is one of the High-Performance programming languages because of the
following reasons.
Automatic memory management (Garbage Collector).
16
OOP using JAVA
Interpreted
In the older versions of java, compilation phase is so fast than the
interpretation phase. It was the industry complaint on older versions of java.
In the newer versions of java, to speed up the interpretation phase, sun micro
system had developed JIT (Just in Time) compiler and added to JVM.
In the current versions of java interpretation phase is so faster than
compilation phase. Hence java is one of the highly interpreted programming
languages.
Dynamic
In any programming language memory can be allocated in two ways. They
are
Static Memory Allocation
Dynamic Memory Allocation
Java programming does not follow the static memory allocation but it always
follows dynamic memory allocation.
Dynamic memory allocation is one in which memory will be allocated at run
time. In java programming to allocate the memory space dynamically we use an
operator called “new”. “new” operator is known as dynamic memory allocation
operator.
Object Oriented
Any programming language that satisfies all the principles of OOP is called
as an Object-Oriented Programming Language. The Java language satisfies all the
principles of OOP. Hence it is called an Object-Oriented Programming Language.
Java is a true object-oriented language. Almost everything in java is an object.
******************************************************************
17
OOP using JAVA
Java Environment:
Java Environment includes a large number of development tools and
hundreds of classes and methods. The development tools are part of the system
known as Java Development Kit (JDK) and the classes and methods are part of the
Java Standard Library (JSL), also known as the Application Programming
Interface (API).
18
OOP using JAVA
*****************************************************************
19
OOP using JAVA
“Data types are used for representing the data in main memory of the computer.”
In java we have eight data types which are grouped in four groups. They
are Integer category Data types, Floating point data types, Character category
data types, Boolean category data types.
20
OOP using JAVA
Whatever the data type we should not exceed the predefined value
C/Cpp JAVA
1 byte 2 bytes
ASCII UNICODE
21
OOP using JAVA
UNICODE character set is one which contains all the characters which are
available in 18 international languages and it contains 65536 characters.
Boolean category data types is used for representing logical values i.e.,
TRUE or FALSE values.
To represent logical values we use a keyword called Boolean.
This data type takes o bytes of memory space.
*****************************************************************
Types of constants:
Ex: 123,-12, 0, 22
22
OOP using JAVA
The real numbers are formed with two parts known as mantissa and
exponent where mantissa is either decimal or integer and exponent is an integer
either positive (or) negative
******************************************************************
Variables in java
Example:
While declaring the variable we should follow some precautions. Which are
given below.
23
OOP using JAVA
******************************************************************
Operators in Java
Java supports a rich set of operators. An Operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. Operators are
used in programs to manipulate data and variables.
Arithmetic Operators
Relational Operators
Logical Operators.
24
OOP using JAVA
Assignment Operators
Increment and Decrement Operators.
Conditional Operators.
Bitwise Operators
Special Operators
Arithmetic Operators
Java provides all the basic arithmetic operators. They are listed below. These
can be used to construct the mathematical expressions. The operators work the
same way as they do in any other languages. These can operate on any built-in
numeric data type of java.
Operator Meaning
+ Addition or unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo Division
Arithmetic Operators are used as follows
where a and b are may be variables or constants and are known as operands.
Relational Operators
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
25
OOP using JAVA
here exp1 and exp2 are any two arithmetic expressions, which may be
simple constants, variables or combination of them. When arithmetic expressions
are used on either side of a relational operator, the arithmetic expressions will be
evaluated first and then the results compared. That is, arithmetic operators have a
higher priority over relational operators.
Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators && and || are used when we want form compound
conditions by combining two or more relations.
26
OOP using JAVA
Assignment Operators
var op=exp
Example:
x+=y+4
x=x+(y+4).
There are three advantages using the shorthand operators, they are
What appears on the left hand side need not be repeated and therefore it
becomes easier to write.
The statement is more concise and easier to read.
Use of shorthand operator’s result in a more efficient code.
Java has two very useful operators called the increment (++) and decrement
(--) operators. The operator ++ adds one to the operand while the operator –
subtracts one. Both are unary operators.
Though ++a and a++ mean the same thing when they form statements
independently, they behave differently when they are used in expressions on the
right-hand side of an assignment statement.
Example:
27
OOP using JAVA
a=5;
b=++a;
a=5;
b=a++;
A prefix operator fist adds one to the operand and then the result is assigned to the
variable on left. On the other hand, a post fix operator first assigns the value to the
variable on left and then increments the operand.
Here first the expression exp1 was evaluated, if it is true, exp2 is evaluated. If it is
false, exp3 is evaluated. However, it has to be clearly understood that among both
exp2 and exp3, only one of it is evaluated at any time.
Example:
a=10;
b=15;
x=(a>b) ? a : b;
28
OOP using JAVA
Bitwise operators:
These operators are act on individual bits(0 and 1) of the operands. They act on
only integer datatypes i.e. byte, short, int, long. There are different types of
operators, they are:
This operator gives the complement form of a given number. This operator symbol
is ~ which is pronounced as tilde.
Complement form of a positive number can be obtained by changing 0’s as 1’s and
visa versa.
This operator performs and operations on the individual bits of the number. The
symbol for the operator is (&) which is called ampersand.
X=10=0000 1010 1 1 1
Y=11=0000 1011 1 0 0
------------------------- 0 1 0
X&Y=00001010 0 0 0
From the above table, by multiply the bits, we get X&Y=0000 1010.
29
OOP using JAVA
This operator performs or operations on the individual bits of the number. The
symbol for the operator is (|) which is called pipe.
1 1 1
X=10=0000 1010
1 0 1
Y=11=0000 1011
0 1 1
-------------------------
0 0 0
X|Y=00001011
From the above table, by adding the bits, we get X|Y=0000 1011.
This operator performs (exclusive or) xor operations on the individual bits of the
number. The symbol for the operator is (^) which is called cap,carat.
1 1 0
X=10=0000 1010
1 0 1
Y=11=0000 1011
0 1 1
-------------------------
0 0 0
X^Y=00000001
From the above table, when odd numbers of 1’s are there, we can get a 1 in the
output.
The left shift operator will shift the bits towards left for the given number of times.
30
OOP using JAVA
int a=2<<1;
Let’s take the binary representation of 2 assuming int is 1 byte for simplicity.
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 0 1 0
Now shifting the bits towards left for 1 time, will give the following result
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0
Now the result in decimal is 4. You can also note that, 0 is added as padding the in
the position 0.
The right shift operator will shift the bits towards right for the given number of
times.
int a=8>>1;
Let’s take the binary representation of 8 assuming int is 1 byte for simplicity.
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 1 0 0 0
Now shifting the bits towards right for 1 time, will give the following result
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0
Now the result in decimal is 4. Right shifting 1 time, is equivalent to dividing the
value by 2.
31
OOP using JAVA
class bits
{
public static void main(String[] args)
{
byte x,y;
x=10;
y=11;
System.out.println("~x=" +(~x));
System.out.println("x&y="+(x&y));
System.out.println("x|y="+(x|y));
System.out.println("x^y="+(x^y));
System.out.println("x<<2="+(x<<2));
System.out.println("~x>>2"+(x>>2));
}
}
OUTPUT:
Special Operators:
a. Instanceof Operator
b. Dot(.) Operator
Instanceof Operator
This operator returns “true” if an object given at the left hand side is an instance of
the class given at right hand side. Otherwise, it returns “false”.
32
OOP using JAVA
class person
{
String name;
int age;
void talk()
{
System.out.println("my name is"+ name);
System.out.println("my age is"+ age);
}
}
class Demo1
{
public static void main(String[] args)
{
person raju=new person();
raju.name="ravindra";
raju.age=29;
raju.talk();
boolean k=raju instanceof person;
System.out.println(k);
}
}
Output:
Dot operator
Example 1
33
OOP using JAVA
raju.name;
Example 2
Syntax:
raju.talk();
****************************************************************
In Java, type casting is a method or process that converts one data type into
another data type in both ways manually and automatically. The automatic
conversion is done by the compiler and manual conversion performed by the
programmer. In this section, we will discuss type casting and its types with proper
examples.
Type Casting
Convert a value from one data type to another data type is known as type casting.
34
OOP using JAVA
Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes place
when:
byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not
done automatically. Also, the char and Boolean data types are not compatible with
each other. Let's see an example.
Example:
class Implicitcast
System.out.println("===Implicit Typecasting===");
System.out.println("Before Conversion:x="+x);
35
OOP using JAVA
System.out.println("After Conversion:y="+y);
Output:
Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
Example:
class Explicitcast
{
public static void main(String args[])
{
double x=10.5;
int y=(int)x;
System.out.println("====Explicit Typecasting====");
System.out.println("Before Conversion:x="+x);
System.out.println("After Conversion:y="+y);
}
}
36
OOP using JAVA
Output:
Boolean casting:
A boolean value cannot be assigned to any other data type. Except boolean,
all the remaining 7 data types can be assigned to one another either implicitly or
explicitly; but boolean cannot. We say, boolean is incompatible for conversion.
Maximum we can assign a boolean value to another boolean.
Following raises error.
boolean x=true;
int y=x; // error
boolean x=true;
int y=(int)x; // error
******************************************************************
The Scanner class in Java is part of the java.util package and provides a simple
way to read input from various sources, such as keyboard input, files, or streams. It
is commonly used for reading user input from the console.
37
OOP using JAVA
Program:
import java.util.*;
class Addition
int a,b,c;
a=sc.nextInt();
b=sc.nextInt();
c=a+b;
System.out.println("After Addition="+c);
Output:
38
OOP using JAVA
The DataInputStream class in Java is part of the java.io package and is used to read
primitive data types from an input stream in a portable way. It provides methods to
read Java primitive types (like int, float, double, etc.) from an underlying input
stream.
Key Features
Program:
import java.io.*;
class Student
int num;
39
OOP using JAVA
String name;
num=Integer.parseInt(d.readLine());
name=d.readLine();
System.out.println("Student Number:"+num);
System.out.println("Student Name:"+name);
Output:
******************************************************************
System.out.printf() in Java is a method used to format and print text to the console
with precise control over the output's appearance. It allows you to create formatted
strings with placeholders that are replaced by values provided as arguments. This
method is part of the PrintStream class, which is used to output data to the console.
40
OOP using JAVA
Basic Syntax
format: A format string that specifies how the output should be formatted. It
includes text and format specifiers.
args: Arguments that are inserted into the format specifiers in the format
string.
Format Specifiers
Format specifiers are placeholders in the format string that are replaced with the
corresponding arguments. Each specifier starts with a % symbol and ends with a
conversion character.
%s: String
%d: Decimal integer
%f: Floating-point number
%x: Hexadecimal integer
%o: Octal integer
%c: Character
%b: Boolean
Program:
Output:
Syntax
format: A format string that specifies how the output should be formatted. It
contains text and format specifiers.
args: The arguments to be formatted according to the format string.
42
OOP using JAVA
Format Specifiers
The format specifiers used in String.format() are the same as those used in
System.out.printf(). Here are some common ones:
%s: String
%d: Decimal integer
%f: Floating-point number
%x: Hexadecimal integer
%o: Octal integer
%c: Character
%b: Boolean
Program:
System.out.println(formattedString);
43
OOP using JAVA
Output:
**********************************************************
Control Statements:
Introduction:
Decision Making :
Simple if statement
If-else statement
Nested if-else statement
else if ladder
Syntax: if(expression)
{
Statements;
}
Statement-x;
Example Program
45
OOP using JAVA
System.out.println("Success");
}
System.out.println("Executed successfully");
}
}
Output
if-else statement:
Syntax:
if(condition)
Statement block 1;
else
Statement block2;
Statement-n
If the condition is true ,then the statement block1 and then statement-n and so on
executed in order. If the condition is false, statement block2 and then statement-n
46
OOP using JAVA
and so no are executed in order. In either case, only one of the statement statement
block1 or statement block2 is executed but not both.
public class si
{
Output:
47
OOP using JAVA
Syntax:
if(condition)
{
if(condition)
{
Statement block1;
}
else
{
Statement block 2;
}
}
else
{
if(condition)
{
Statement block 3;
}
else
{
Statement block 4;
}
Statement-n;
Example Prograam
Class ifelsenesting
{
public static void main(String args[])
{
int a=325,b=712,c=478;
System.out.println(“largest value is:”);
if(a>b)
{
if(a>c)
{
System.out.println(a);
}
else
48
OOP using JAVA
{
System.out.println(a);
}
}
else
{
if(b>c)
{
System.out.println(b);
}
else
{
System.out.println(c);
}
}
}
Output: Largest value is :712
else if ladder:
Syntax:
if (condition1)
statement1;
else if (condition2)
statement2;
else if(condition3)
statement3;
…………………
…………………
49
OOP using JAVA
else if(condition n)
statement n;
else
default-statement;
statement-x;
This construct is known as the else if ladder. The conditions are evaluated
from the top of the ladder. As soon as the true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x.
When all the n conditions becomes false, then the final else containing the default-
statement will be executed.
Example Program:
class ei
{
public static void main(String args[])
{
int marks=70;
if(marks>79)
{
System.out.println("honours");
}
else if(marks>59)
{
System.out.println(" I Division");
}
else if(marks>79)
{
System.out.println("II Division");
}
else
{
System.out.println(" Fail");
50
OOP using JAVA
}
}
Output:
Syntax:
switch(expression)
{
case value1:
block-1
break;
case value2:
block-2
break;
. . . . . . . . ..
..........
default:
default-block
51
OOP using JAVA
break;
}
Statement-x;
The optional default label is used to specify the code segment to be
executed, when the value of the variable or expression does not match with any of
the case values. If there is no break statement as the last statement in the code
segment for a certain case, the execution will continue on into the code segment for
the next case clause without checking the case value.
Example Program:
class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month)
{
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");
}
52
OOP using JAVA
}
}
Output:
Looping
while construct
do construct
for construct
While statement
Initialization:
while (test condition)
{
Body of the loop;
}
The while is an entry-controlled loop statement. The test condition is
evaluated and if the condition is true, then the body of the loop is executed. After
execution of the body, the test condition is once again evaluated and if it is true,
the body is executed once again. This process is repeated until the test condition
returns a false value.
53
OOP using JAVA
Aim: To read a string from the keyboard character by character and to display it on
the screen.
Program:
import java.io.*;
class WhileTest
{
public static void main(String[] args) throws IOException
{
int i=1;
while(i<=10)
{
System.out.println("i=" + i);
i++;
}
}
}
Output:
Initialization;
54
OOP using JAVA
do
{
Body of the loop;
} while (test condition);
On reaching the do statement, the program proceeds to execute the body of
the loop first. At the end of the loop, the test condition in the while statement is
evaluated. If the condition is true, the program continues to evaluate the body of
the loop once again. This process continues as long as the condition is true. When
the condition is false, the loop will be terminated.
Since the test condition is evaluated at the bottom of the loop, the do…while
constructs provides an exit-controlled loop and therefore the body of the loop is
always executed at least once.
Program:
class dow {
int i=0;
do{
System.out.println(i);
i++;
}while(i<10);
55
OOP using JAVA
Output:
while Do…while
It is a looping construct that will It is a looping construct that will
execute only if the test condition is execute at least once even if the test
true. condition is false.
It is entry controlled loop. It is an exit controlled loop.
It is generally used for implementing It is typically used for implementing
common looping situations. menu based programs where the menu
is required to be printed at least once.
The for loop is another entry controlled loop that provides a more concise
loop control structure. The general form of the loop is as follows.
56
OOP using JAVA
2. The value of the control variable is tested using the test condition. If the test
condition is true, the body of the loop is executed; otherwise the loop is
terminated.
3. When the body of the loop is executed, the control is transfer back to the for
statement after evaluating the last statement in the loop. Now, the control
variable is incremented or decrement.
The for loop has several capabilities that are not found in other loop
constructs. They are
1. More than one variable can be initialized at a time in the for statement.
The statements
p=1;
for(n=0;n<10;n++)
Can be written as
for(p=1,n=0;n<10;n++)
2. Like the initialization section, the increment section may also have more
than one part. For example
for(n=1,m=50;n<=m;n++,m--)
3. The test condition may have any compound relation and the testing need
not be limited only to the control variable. Consider the following
sum=0;
for(i=1;i<20&&sum<100;i++)
{
………………
……………..
}
4. Another unique aspect of for loop is that one or more sections can be
omitted, if necessary. Consider the following example
…………..
………….
m=5;
for( ; m!=100 ; )
57
OOP using JAVA
{
System.out.println(m);
m=m+5;
}
………….
………….
Example:
Nesting of loops means one for statement within another for statement, is
allowed in java. The for loops can be nested as follows
Program:
class NestedLoop
{
public static void main(String[] args)
{
int i,j;
System.out.println("The right angle triangle of @ is shown in
below:\n");
for(i=1;i<=9;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("@");
}
System.out.println(" ");
}
}
}
58
OOP using JAVA
Output:
The enhanced for loop, also called for each loop. This feature helps us to
retrieve the array of elements efficiently rather than using array indexes.
import java.util.*;
import java.lang.*;
class foreach
{
public static void main(String[] args)
{
int arr[]={1,2,3,4};
for(int i : arr)
{
59
OOP using JAVA
System.out.println(i);
}
}
}
Output:
Java permits a jump from one statement to the end or beginning of a loop as
well as a jump out of a loop.
This statement can also be used within while, do or for loops as illustrated below.
60
OOP using JAVA
Example:
class Breakdemo
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i==5)
break;
System.out.println("i="+i);
}
}
}
Output:
Like the break statement java supports another similar statement called
continue statement. Whenever the continue statement is encountered within the
loop, that causes the loop to be continued with the next iteration after skipping any
statements in between. The continue statement tells the compiler “ SKIP THE
FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT
ITERATION”.
61
OOP using JAVA
Example:
class Continuedemo
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
System.out.println("i="+i);
}
}
}
Output:
62
OOP using JAVA
3. return:
The return keyword finishes the execution of a method, and can be used to return a
value from a method.
Example:
int display()
{
return 10;
}
public static void main(String[] args) {
ReturnExample1 e =new ReturnExample1();
System.out.println(e.display());
}
}
Output:
10
63