Unit -1 Java -R23
Unit -1 Java -R23
Unit -1 Java -R23
UNIT I: Object Oriented Programming: Basic concepts, Principles, Program Structure in Java:
Introduction, Writing Simple Java Programs, Elements or Tokens in Java Programs, Java Statements,
Command Line Arguments, User Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of Variables, Data
Types, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants, Formatted
Output with printf() Method, Static Variables and Methods, Attribute Final, Introduction to Operators,
Precedence and Associativity of Operators, Assignment Operator ( = ), Basic Arithmetic Operators,
Increment (++) and Decrement (- -) Operators, Ternary Operator, Relational Operators, Boolean Logical
Operators, Bitwise Logical Operators.
Introduction Java is an Object Orient and high-level programming language, originally developed by Sun
Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, Linux
etc.
In Java, there are three types of programs as follows: Stand- aline application programs : These programs
are made and run on users computers
Applet programs : These programs are meant to run in a web page on the Internet.
Java Servlets : These programs run in computers that provide web services. They are also oftern called
server side programs or servlets.
STRUCTURE OF JAVA PROGRAM
class Simple
{
public static void main(String args[])
{
System.out.println("Java World");
}
}
To compile:
javac Simple.java
To execute:
java Simple
SEAGI-JAVA Page 1 of 42
UNIT-1 NB
Java is an Object oriented language. Every java program imports packages which are provides necessary
classes and interfaces.
For example:
import java.util.*;
import java.io.*;
After import statement, every java program starts with the declaration of the class. A program may have
one or more classes.
A class declaration starts with the keyword class, followed by the identifier or name of the class. Giving
the name of a package at the top is optional.
Class declaration contains name of the class and body of the class. The body of the class may consist of
several statements and is enclosed between the braces {}.
Here:
public is access specifier. This class is accessible to any outside code. Otherwise the class is accessible to
only same package classes.
The class body starts with the left brace {and ends with the right closing brace }.
A class body may comprise statements for declaration of variables. constants, expressions, and methods.
SEAGI-JAVA Page 2 of 42
UNIT-1 NB
For compiling the program, the Java compiler javac is run, specifying the name of the source file on the
command line as depicted here:
javac Start.java
The Java compiler creates a file called Start.class containing the bytecode version of the program. The java
interpreter in JVM executes the instructions contained in this intermediate Java bytecode version of the
program. The Java interpreter is called with “java” at the command prompt.
Here java command calls the Java interpreter which executes the Start.class (bytecode of Start.java).
SEAGI-JAVA Page 3 of 42
UNIT-1 NB
Java program contains different types of elements like white spaces, comments and tokens. A token is the
smallest program element which is recognized by the compiler and which treats them as defined for the
compiler. A program is a set of tokens which comprise the following elements:
• It should not start with a digit but it can start with an underscore.
• It can comprise one or more unicode characters which are characters as well as digits.
Keywords: These are special words defined in Java and represent a set of instructions.
SEAGI-JAVA Page 4 of 42
UNIT-1 NB
• A literal represents a value which may be of primitive type, String type, or null type.
• The value may be a number (either whole or decimal point number) or a sequence of characters
which is called String literal, Boolean type, etc.
Types of Literals:
Integer literals
• Sequences of digits.
• The whole numbers are described by different number systems such as decimal numbers,
hexadecimal numbers, octal numbers, and binary numbers.
• The numbers are preceded by 0x or 0X. Examples are 0x56ab o0X6AF2, etc.
SEAGI-JAVA Page 5 of 42
UNIT-1 NB
• These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
Binary Literal
Boolean literal
• These are Boolean values. There are only two values—true or false.
Character literal
• Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
String literal
• These are strings of characters in double quotes. Examples are “Delhi”, “John”, “AA”, etc.
Null literal
Separators: These include comma, semicolon, period(.), Parenthesis (), Square brackets [], etc
SEAGI-JAVA Page 6 of 42
UNIT-1 NB
Types of Operators:
Arithmetic Operators:
Operator Description
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus
Relational Operators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
SEAGI-JAVA Page 7 of 42
UNIT-1 NB
Logical Operators:
Operator Description
&& Greater than
|| Greater than or equal to
! Less than
Assignment Operators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to
Operator Description
++ Increment by one
-- Decrement by one
Bitwise Operators:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise compliment
>> Shift Right
<< Shift Left
>>> Shift right with Zero fill
Conditional Operators:
Operator Description
?: Used to construct Conditional expression
SEAGI-JAVA Page 8 of 42
UNIT-1 NB
Java Statements
Statement Description
Empty statement These are used during program development.
Variable declaration It defines a variable that can be used to store the values.
statement
Labeled statement A block of statements is given a label. The labels should not
be keywords, previously used labels, or already declared
local variables.
Expression statement Most of the statements come under this category. There are
seven types of expression statements that include assignment,
method call and allocation, pre-increment, post increment, pre-
decrement, and post decrement statements.
Control statement This comprises selection, iteration, and jump statements.
Selection statement In these statements, one of the various control flows is
selected when a certain condition expression is true. There
are three types of selection statements including if, if-else,
and switch.
Iteration statement These involve the use of loops until some condition for the
termination of loop is satisfied. There are three types of
iteration statements that make use of while, do, and for
Jump statement In these statements, the control is transferred to the
beginning or end of the current block or to a labeled
statement. There are four types of Jump statements including
break, continue, return, and throw.
Synchronization These are used with multi-threading
statement
Guarding statement These are used to carry out the code safely that may cause
exceptions (such as division by zero, and so on). These
statements make use of try and catch block, and finally
• These arguments can be passed at the time of running the program. This enables a programmer to
check the behavior of a program for different values of inputs.
• When a Java application is invoked, the runtime system passes the command line arguments to the
application's main method through an array of strings.
• It must be noted that the number of arguments in an array. To ensure this, we can make use of the
length property of the array. This is illustrated in
SEAGI-JAVA Page 9 of 42
UNIT-1 NB
class vehicle
public static void main(String args[])
{
int x = args.length;
for(int i=0; i<x; i++)
{
System.out.println(args[i]);
}
}
Output
(After compiling, type the following lines on the command prompt. It produces the
output as)
Cycle Motorbike
class Sum
{
public static void main{String args)
int s=1;
s=s+Integer.parseInt(args(1]);
Output
After compiling, the following lines are typed on the command prompt: It
produces the output as
SEAGI-JAVA Page 10 of 42
UNIT-1 NB
Declaration of Variables
• A program may involve variables: variables are objects whose values may change in the program.
• A variable is declared by first writing its type, followed by its name or identifier as illustrated here.
• However, a variable should also be initialized, that is, a value should be assigned to it before it is
used in an expression. The line ends with a semicolon (;) as shown in the above figure.
Examples:
System. out.println();
}
}
c:\>javac PrintOut.java
c:\>java PrintOut
SEAGI-JAVA Page 11 of 42
UNIT-1 NB
Name= Sunita
Str = Hello
Length 50
Width 8
HelloSunita
• The class Scanner of package java.util to carry out input to the program.
• Java Scanner class is a text scanner that breaks the input into tokens using a delimiter. The delimiter
is whitespace by default.
• Importing the class is the first step.
import java.util.Scanner;
• The object of the class Scanner is declared as follows.
Scanner scaninput = new Scanner (System. in);
• The object “scaninput” invokes the method nextInt() which reads the value typed by the user. This
value is assigned to n. The value of m is similarly obtained.
• The other useful methods of Scanner class are nextDouble() and nextLine().
import java.util.Scanner;
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scaninput = new Scanner (System. in);
int n;
int m;
System.out. print( "Enter the value of n : ");
n=scaninput.nextInt();
System.out. print( "Enter the value of m : ");
m=scaninput.nextInt();
System.out.println("Sum of two numbers is ="+(n+m));
System.out.println("Product of two numbers is ="+ n*m);
SEAGI-JAVA Page 12 of 42
UNIT-1 NB
Escape Sequences
Escape Sequences character is preceded by a backslash (\)has a special meaning to the compiler. Escape
sequences are as follows.
SEAGI-JAVA Page 13 of 42
UNIT-1 NB
class Escape
{
public static void main(String[] args)
{
int n=256, a=0, b=70;
System.out.println("Value of a =" + a + "\n b= "+b +"\n");
System.out.println("\u0041 \t" + " \u0042 \t"+"\132");
System.out.println("\"Value of b\" = "+b);
System.out.println("\'Value of n\' = " +n);
}
}
Output:
C:\>javac Escape.java
C:\>java EscapeValue of
a =0 b= 70
A B Z
"Value of b" = 70'Value of n' = 256
Comments
• Comments are Line of Text which is not a part of the compiled program.
1. Single-line comment: These comments are started with two front slash characters (//)
Example:
/* It is Multi line
Comments */
3. Documentation comment: These comments are enclosed with /** and */. It is different from multi
line comments in that it can extracted by javadoc utility to generate an HTML document for the
program.
Example:
SEAGI-JAVA Page 14 of 42
UNIT-1 NB
Programming Style.
An analysis of the programming exercises will throw some light on the look and feel of a program.
The team members should easily understand each other's code.
For a beginner, it is better to develop a habit of writing a program in a proper style so thatthere is no
conflict between the current habits and the company's imposition of style rule at a later stage.
There are no set patterns of good style and bad style: however, if the programmer takes care of a
few requirements on the programs as discussed, the resulting style will be better
1. The program should present a clean and orderly look. In order to develop a clean program,
the programmer can adapt the following measures:
(b) Indenting is another method often used to improve the looks and readability
(c) Use of Lambda expression and method reference of Java 8 enhances the look
2. The program should be easy to understand. The programmer should take care of the
following aspects:
(a) If it is team work, certain conventions about naming should be preset so that a teammember can
easily identify an item.
(b) The makers of Java have a set of rules which are followed in the Java library. The samerules or an
even better convention may be set.
(c) Judicial use of comments can increase understandability. Use of too many comments makes
confusion in the program.
(d) It is better to use already defined and tested library methods rather than user-defined methods
3. Debugging should be easy. The programmer may adopt the following measures to ensure easy
debugging.
(a) The vertical alignment of a similar item enhances the ability to find errors.
(c) The variables should be declared close to the places of their use
SEAGI-JAVA Page 15 of 42
UNIT-1 NB
(d) If it is a big program, it should be divided into small segments. In Java, it is easy because
the program may comprise separate classes.
(c) The names used should imply the output type such as price, weight, length, and so on.
(a) The program should be easily modifiable to ensure simplicity in fixing errors.
(b) The comments can help in modification of the program, fixing errors.
SEAGI-JAVA Page 16 of 42
UNIT-1 NB
I. Primitive data
4. Arrays
5. Methods
The primitive data and their types are defined independent of the classes and interfaces, and the arrays and
methods derive their types from the first three entities.
An array is n collection of items that may be of primitive type, class objects, or references. The type of an
array can be determined from the type of elements present in it.
• Java is a case-sensitive language. This means that it takes Area, area, and AREA are threedifferent
objects.
Declaration of Variables - Data Types
A variable is declared by first declaring its type followed by its identifier or name, which is given
as follows:
SEAGI-JAVA Page 17 of 42
UNIT-1 NB
Datetype Identifier;
Here type is the primitive data type and Identifier is the name of the variable.
Ex:
byte n; // declares a variable of type byte.
Non-primitive Types
These are the class and interface types. The name of a class or interface is the name of type. A class object is
declared as
Class_identifier object_identifier;
Interface_identifier reference_identifier;
Example
String str "Delhi":
Data Types
i. Integers
Integers are whole numbers, that is, they represent numbers that do not have a fractional
part.The integers can be declared in four types according to the size of memory allocated
for them
byte
short
int
long
SEAGI-JAVA Page 18 of 42
UNIT-1 NB
class DataType
//e=d+f;
Output:
SEAGI-JAVA Page 19 of 42
UNIT-1 NB
class Datachar {
ch2=ch1++;
ch3=++ch1;
} }
Output:
ch1 =E
ch2 =E
ch3 =G
Float: This type is used for single-precision decimal floating point numbers, that is, 7 digitsafter
the decimal point. These numbers are stored on 4 bytes.
{
SEAGI-JAVA Page 20 of 42
UNIT-1 NB
Output
C:\>javac FloatType.java
C:\>java FloatType
Width = 20.0
Length = 40.5
Rectangle Area = 810.0
Diameter 10.0
Area of Circle = 78.53975
If the aforementioned logical statement is correct, The value of a is true, otherwise the value
of a is false. In Java true and false are not converted into numerical values, which is
the case in other Languages. A boolean type variable is allocated to one byte, that is, 8 bits
for storing its values Program
C:\>java Boolean
a = false and b =true
Now c= false and d = true
Type Casting
Converting one data type to another data type is called as Type Casting. There are two types
of type casting. They are,
i. Implicit Type casting
ii. Explicit Type casting
iii.
i. implicit Type casting
Implicit type casting is done automatically by a compiler when we assign a value to the variable.
Example:
int a=10; double b; b=a;
Here a is integer and d is double variables. Integer value is automatically converted into double by
the compiler.
The explicit type casting is carried out by the following code: type variable = (new_type) variable;
int A = (int) D;
method scope.
• The variables declared in a block have block scope.
• Thus, the variables defined in main() at the beginning have scope in entire main() method,
however, those defined in a block have block scope.
• A block starts with the left brace ( { ) and ends with the right brace ( } ).
In the case of nested blocks of statements, the scope of variables is governed by the following
rules.
1. The scope starts from the point the variable is defined in the block (declared and value
assigned to it).
2. Although the variable may be defined anywhere in a block, it can be used only in the
statements appear ing after its definition Therefore, there is no use in defining a variable at
the end of block.
If there are nested blocks, a variable defined in the outer block is visible in the inner blocksalso
and it cannot be redefined with the same name in the inner blocks
Program 3.10: Illustration of block scope
E:\>javac ScopeA.java
E:\>java ScopeA
Class Scope variable - outside main() x = 5
Variable y Scope within main() y = 10
Variable z Scope within Anonymous Block z = 20
E:\>java ScopeA
SEAGI-JAVA Page 23 of 42
UNIT-1 NB
A Symbolic constant is a variable whose value does not change throughout the program.
Some of the examples include PL NORTH, EAST etc.
It is usually preferred to declare the symbolic constants using all the capital letters in a
program as follows:
}
}
C:\>javac SymbolicConst.java
C:\>java SymbolicConst
radius=25.0
Perimeter of circle = 157.079632675
SEAGI-JAVA Page 25 of 42
UNIT-1 NB
class FormatPrintf
{
public static void main(String args[])
{
int n = 713;
float x = 45.86f;
double d= 56.754;
String str = "Delhi";
char ch = 'A';
System.out.printf( "%d %f %f %c \t %s \n", n, x, d,ch,str);
//for conversion into hexadecimal number
System.out.printf("Hexadecimal value of 163 = %X \n", 163);
//for conversion into octal
System.out.printf("Octal value of 163 = %o\n", 163);
}
}
Output
C:\>javac FormatPrintf.java
C:\>java FormatPrintf
713 45.860001 56.754000 A Delhi
Hexadecimal value of 163 = A3
Octal value of 163 = 243
SEAGI-JAVA Page 26 of 42
UNIT-1 NB
Static Variables:
• The static variables are class variables. Only one copy of such variables is kept in the
memory and all the objects share that copy.
• The static variables are accessed through class reference, whereas the instance variables are
accessed through class object reference
• The variables in a class may be modified by modifier static.
The non-static variables declared in a class are instance variables Each object of the classkeeps a copy
of the values of these variables.
Static Methods:
The static methods are similar to class methods and can be invoked without any referenceof object
of class, however, class reference (name of class) is needed, as in the following example The method
like sart() is declared as static method in Math class and is called
Math.sqrt(5); // Finds square root of 5
The static method is called using the method name that is preceded by the class name; in this
case. Math and period ().
E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 77
Random Number 2 = 69
Random Number 3 = 83
Random Number 4 = 2
Random Number 5 = 66
SEAGI-JAVA Page 27 of 42
UNIT-1 NB
E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 67
Random Number 2 = 31
Random Number 3 = 10
Random Number 4 = 13
Random Number 5 = 40
Attribute Final
Final Variable:
The value of a variable declared final cannot be changed in the program. It makes the
variable a constant. A few examples of declarations are as follows:
• As mentioned in the comments, the values of PI, M, and x cannot be changed in their
respective scopes.
Final Method:
• The attribute final may be used for methods as well as for classes. These are basically
connected with inheritance of classes.
• When final keyword is used with Java method, it becomes the final method.
• A final method cannot be overridden in a sub-class.
Final Class:
• A Java class with final modifier is called final class A final class cannot be sub-classed or
inherited. Several classes in Java are final including String, Integer, and other wrapper
classes.
• There are certain important points to be noted when using final keyword in Java
i. New value cannot be reassigned to a variable defined as final in Java.
ii. Final keyword can be applied to a member variable, local variable, method, or class.
iii. Final member variable must be initialized at the time of declaration.
iv. Final method cannot be overridden in Java
v. Final class cannot be inheritable in Java
vi. Final is different from finally keyword, which is used on Exception handling in Java
SEAGI-JAVA Page 28 of 42
UNIT-1 NB
Example- 1:
public class Final
{
public static void main (String args[])
{
int n =10; // Normal variable
final int f = 20; // final variable
System.out.println("n = "+ n);
System.out.println("f = "+ f);
n = 50; // Now the value 50 is assigned to variable n
f = 60; // Error : f is final variable can not be changed
}
}
Output:
C:\>javac Final.java
1 error
C:\>
Example-2:
An operator is a symbol that tells the computer to perform certain mathematical and logical
calculations.
The different types of Java operators are,
a) Arithmetic operators
b) Relational operators
SEAGI-JAVA Page 29 of 42
UNIT-1 NB
c) Logical operators
d) Increment or decrement operators
e) Assignment operators
f) Conditional operators
g) Bitwise operators
h) Special operators
Assignment Operator ( = )
Assignment operators:
-Assignment operators are used to assign the result of an expression to a variable.
Operator Meaning
= Assignment
-In addition, java has a set of short-hand assignment operators of the form
V OP=EXP;
- It is equivalent to
SEAGI-JAVA Page 30 of 42
UNIT-1 NB
V=V OP EXP;
-The short-hand assignment operators are
+= , -= , *= , /= , %=
Example:
a+=b --------------- a=a+b
a-=b a=a-b
a*= b ---------------- a=a*b
a/=b ---------------- a=a/b
a%=b--------------- a=a%b
Increment (++) and Decrement (- -) Operators
-The increment operator is ++ which means +1
-The decrement operator is - - which means -1
-The operand must be either incremented or decremented by 1.
Example:
m=5;y=++m; results m=6 and y=6.
m=5;y=m++; results m=6 and y=5.
m=5;y= --m; results m=4 and y=4.
m=5;y=m--; results m=4 and y=5.
Example:
if(a>b)
System.out.println(“a is greater”);
else
System.out.println (“b is greater”);
Relational Operators
-The comparison between two operands or expressions is done with the help of relational
operators.
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equality
!= Inequality
Example:
a>b
a>=b
SEAGI-JAVA Page 31 of 42
UNIT-1 NB
a<b
a<=b
a==b
a!=b
Bitwise operators:
-‘C’ provides bitwise operators that operate on data at the bit-level.
-Bitwise operators interpret operands as string of bits.
-These bit strings are then interpreted according to data type.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
SEAGI-JAVA Page 32 of 42
UNIT-1 NB
Special Operators.
- Java supports some special operators such as,
a) instanceof operator
b) member selection operator
a) instanceof operator:
- The instanceof is an object reference operator and returns true if the object on the left-hand
side is an instance of the class given on the right hand side.
- This operator allows us to determine whether the object belongs to a particular class or not.
Example:
person instanceof student
- It is true if the object person belongs to the class student, otherwise it is false.
Control Statements:
1.Introduction
CONTROL STATEMENTS: (FLOW OF CONTROL)
A Control statement is a statement used to control the flow of execution in a Java Program
SELECTION STATEMENTS:
-Also called as conditional or decision-making control statements.
-There are two types in Selection control statements.
i) Two-way selection control statements
ii) Multi-way selection control statements
Two-way selection control statements:
SEAGI-JAVA Page 33 of 42
UNIT-1 NB
statements;
}
next statement;
Example:
if(a==2)
{
p++;
}
System.out.println(“program over”);
3.Nested if Expressions
-if within if is called as Nested-if.
Syntax:
if(condition-1)
{
if(condition-2)
{
Statement-1;
}
els
e
{ Statement-2;
} }
else
{
if(condition-3)
{
} } }
els
e
{
SEAGI-JAVA Page 34 of 42
UNIT-1 NB
Statement-
3;
Statement-4;
next statement;
Example:
if(a>b)
{
if(a>c)
{
System.out.println(“a is greater”);
}
else
{
System.out.println (“c is greater”);
}
}
else
{
if(b>c)
{
System.out.println(“b is greater”);
}
else
{
System.out.println(“c is greater”);
}
}
4. if–else Expressions
Syntax:
if(condition)
{
true-block statements;
}
else
{
false-block statements;
}
next statement;
Example:
if(a>b)
{
System.out.println(“a is greater”);
}
else
{
System.out.println(“b is greater”); }
SEAGI-JAVA Page 35 of 42
OOPJ - R(23)
Example:
if(a>b&&a>c&&a>d)
{
System.out.println(“a is greater”);
}
else if(b>a&&b>c&&b>d)
{
System.out.println(“b is greater”);
}
else if(c>a&&c>b&&c>d)
{
System.out.println(“c is greater”);
}
else
{
System.out.println(“d is greater”);
}
5. Ternary Operator ? :
In Java, the ternary operator is a type of Java conditional operator. The meaning of ternary is composed
of three parts.
The ternary operator (? :) consists of three operands. It is used to evaluate Boolean expressions. The
operator decides which value will be assigned to the variable. It is the only conditional operator that
accepts three operands.
It can be used instead of the if-else statement. It makes the code much more easy, readable, and shorter.
Syntax:
Expression1 ? Expression2 : Expression3
• The first expression is the test condition.
• If it evaluates true, the Expression2 is executed; otherwise Expession3 is executed.
Example-1:
public class Ternary
{
public static void main (String args[])
{
int a=10;
int b = (a<20)? 100 :200; // a < 20 if statement
System.out.println("b= "+b);
}
}
Output:
C:\>javac Ternary.java
C:\>java Ternary
b= 100
Example-2:
public class Ternary
{
public static void main (String args[])
{
int a=10;
int b = (a>20)? 100 :200; // a>20 – else statement
System.out.println("b= "+b);
}
}
Output:
C:\>javac Ternary.java
C:\>java Ternary
b= 200
6. Switch Statement
Syntax:
switch(expression)
{
case value-1:statement-1;break;
case value-2:statement-2;break;
………………………….
………………………….
case value-n:statement-n;break;
default: default statement;
}
next statement;
Example:
switch(digit)
{
case 0: System.out.println(“ZERO”);break;
case 1: System.out.println(“ONE”);break;
case 2: System.out.println(“TWO”);break;
case 3: System.out.println(“THREE”);break;
case 4: System.out.println(“FOUR”);break;
case 5: System.out.println(“FIVE”);break;
case 6: System.out.println(“SIX”);break;
case 7: System.out.println(“SEVEN”);break;
case 8: System.out.println(“EIGHT”);break;
case 9: System.out.println(“NINE”);break;
default: System.out.println(“Enter between 0-9”);
}
7. Iteration Statements
LOOP STATEMENTS:
The iteration control statements are also called as Repetition or Iteration control statements.
A looping process includes the following four steps.
o Setting and initialization of a counter.
o Execution of the statements in the loop body.
o Test for a specified condition (loop control expression) for execution of a loop
o Incrementing or Decrementing counter.
Pretest and Posttest loops:
In a Pretest loop, the condition is checked before we execute a loop body.
It is also called as entry-controlled loop.
In the Posttest loop, we always execute the loop body atleast once.
It is also called as exit-controlled loop.
8. while Expression
a) while statement:
Syntax:
while(condition)
{
loop body;
}
next statement;
Example:
n=10,i=1,sum=0;
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println(“sum=”+sum);
SEAGI -NB Page 38
OOPJ - R(23)
for statement:
Syntax:
for(initialization;condition;inc or dec)
{
loop body;
}
next statement;
Example:
n=10,i,sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println(“sum=”+sum);
Syntax:
for (Object obj : Collection_name)
{
Body of loop
}
Example:
public class ForEach
{
public static void main (String args[])
{
int myArray[] = {10,20,30,40,50};
for (int x:myArray)
{
System.out.println(" "+x);
}
}
}
Output:
C:\>javac ForEach.java
C:\>java ForEach
10
20
30
40
50
13.Break Statement
Unconditional control statements:
The unconditional control statements are,
a) break statement
b) continue statement
break statement:
The break statement skips from the loop or block in which it is defined.
The control then automatically goes to the first statement after the loop or block.
The general format is
break;
Example:
public class Break
{
public static void main (String args[])
{
//printing the values from 1 to 10
for(int i =0; i<10;i++)
{
if (i==5)
break; //Break Statement
System.out.println( i );
}
}
}
Output:
C:\>javac Break.java
C:\>java Break
0
1
2
3
4
Here loop is stopped due to break statement.
It is useful when we want to continue the program without executing any part of the program.
The general format is
continue;
Example:
public class Continue
{
public static void main (String args[])
{
//printing the values from 1 to 10
for(int i =0; i<10;i++)
{
if (i==5)
continue; // Continue statement
System.out.println( i );
}
}
}
Output:
-------
C:\>javac Break.java
C:\>java Continue
0
1
2
3
4
6
7
8
9
Here 5 is not printed because of continue statement. The Iteration at the condition i = =5 is
skipped or jumped to next statement.