Java First Unit
Java First Unit
Unit 1
Procedural Abstraction:
Procedural abstraction provides mechanisms for abstracting well defined procedures or
operations as entities.
The implementation of the procedure requires a number of steps to be performed.
In a Bank, credit and debit operations which involves various steps is a well defined
procedural abstraction.
Data Abstraction
Data abstraction refers to, providing only essential information to the outside world and
hiding their background details, i.e., to represent the needed information in program
without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of
interface and implementation.
Real Life Example: TeleVision, which you can turn on and off, change the channel, adjust the
volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not
know its internal details, that is, you do not know how it receives signals over the air or through a
cable, how it translates them, and finally displays them on the screen.
Inheritance
Inheritance concept in OOP allows us to create a new class using existing classes.
Objects of one class acquires the properties of another class.
Class which is giving its properties is known as Base Class or Super Class.
Class which acquires the properties is known as Derived or Sub Class
Additional functionality can be added to derived class (Extensibility). New class will have the
combined features of both.
Using inheritance the hierarchical relationships are established. For example, Grand Father,
Son and Grand Son hierarchy.
inheritance allows the reusability of existing operations and extending the basic unit of a class
without creating from the scratch.
Real Life Example A bike manufacturer uses same mechanism of existing version of the bike while
launching a new version with some added functioflai1tes. This allows him to save time and efforts.
Polymorphism
The word polymorphism means the ability to appear in many forms.
In object oriented programming polymorphism refers to a programming language’s ability to
process objects differently depending on their data type or class.
It is the ability to redefine methods for derived classes.
An operation may exhibit different behavior in different instances. The behavior depends on
the types of data used in the operation.
polymorphism allows objects having different internal structures to share the same external
interface
Shape is the base class, where Circle, Box and Triangle are derived classes but having same external
interface Draw() to draw their respective shapes.
Shape Draw()
Examples: Addition Operation: For o numbers + operator produces the sum. For two strings, it
produces the concatenation of the strings to produce the third string. A word in English having
several different meanings dependingonthe context.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
Dynamic binding is determining the method to invoke at runtime instead of at compile time.
Dynamic binding is also referred to as late binding.
It is associated with inheritance and polymorphism.
Static binding occurs at compile time, while dynamic binding occurs at run time.
Static binding uses data type, whereas dynamic binding uses object types.
Message Passing
Objects communicates with each other by sending and receiving information.
Message for an object is a request for execution of a procedure. It will invoke a method in the
receiving object.
Objects can be created and destroyed.
Communication with an object is feasible as long as it is alive.
Two objects can communicate by passing each otherts objects to their methods
Example:
Employee.salaray(name);
Here, Employee is the object, salary is the message, name is the information sent.
Employee.Salary(BankAccount Act);
Here, Employee calls its own method Salary and passes BankAccount object Act to it. In this way
two objects of Employee and BankAccount classes communicate.
Benefits of OOP
Applications of OOP
The following are the application areas of OOP:
User Interface design in windowing systems
Real-business systems
Real-time systems
Object-Oriented databases
Hypertext, hypermedia and expertext
Al and Expert Systems
Neural Networks and Parallel Programming
Decision Support and Office Automation Systems
CAD(Computer Aided Design), CAM(Computer Aided Manufacturing),
CIM (Computer Integrated Manufacturing) systems
Java Evolution
Java is a general-purpose, object-oriented programming language developed by Sun Microsystems,
USA in 1991.
Originally called Oak by James Gosling, one of the inventors of the language
Initially, Software for consumer electronic devices were designed using Java.
Java overcomes the limitations of C and C++ such as portability and reliability.
Problematic sources in C and C++ were removed in Java
Java was made as a simple, reliable, portable and powerful language
1990 -Sun microsystems started developing a software for consumer electronic devices
l991 - The new language is named as Oak
1992 -The team own as Green Project demonstrated their applications developed in oak.
1993 -Development of web applet for WWW graphical environment
1994 -Development of web browser Hot Java
1995 -Oak was renamed as Java
1996 -Java Development Kit 1.0 (JDK) was released. Java established itself as leader of internet
programming
1997 -JDK 1.1 released
1998 -JAVA 2 released with JDK 1.2
1999 -J2SE (JAVA 2 Standard Edition), J2EE (JAVA 2 Enterprise Edition)
2000 -J2SE with SDK 1.3 was released
2002- J2SE with SDK 1.4 was released
2004- J2SE with JDK 5.0 (Instead of JDK 1.5) was released. It is known as J2SE 5.0
JAVA Features
The inventors of Java wanted to design a language that is portable, reliable and distributed but
simple.Fol1owing are the features of Java:
Compiled and Interpreted - Java is both compiled and interpreted. It is a two-stage process. Java
compiler translates source code into byte code. Java interpreter generates machine code for the target
machine that is running the Java program.
Platform Independent and Portable - Java programs are portable. That is, they can be easily moved
from one computer to another, anywhere and anytime. Platform Independent means, changes and
upgrades in operating systems, processors and system resources will not force any changes in Java
programs. This is why Java is suitable for programming on Internet which connects different kinds of
systems worldwide. Size of the primitive data types is machine independent.
Object Oriented - Java is true object-oriented language. Almost everything in java is an
object. All program code and data reside within objects and classes. Java comes with
extensive set of classes arranged in packages. Object model of Java is simple and easy to
extend.
Robust and Secure - Java is Robust in the following ways:
• It provides many safeguards to ensure reliable code
• Strict compile time and run time checking for data types
• As it is garbage collected language, it relieves programmers from memory
management problems.
• Exception handling features which eliminates the risk of system crash.
Security is a primary concern for a language like Java used in Internet programming.
Java ensures no viruses are communicated with an applet
It checks all memory access.
Absence of pointers in java avoids unauthorized access to memory locations.
High Performance
Java interpretation is fast and comparable to native C/C++.
Java architecture reduces overheads during runtime.
Multithreading also enhances overall execution speed of Java Programs
Remote Applet
Internet
Web Browser A program that provides access to WWW and runs Java Applets
APPLET tag HTML tag that places Java applets on web page
ByteCode Compiled Java Code given in APPLET tag and transferred to the user computer
Java Environment
Java Environment or Architecture includes a large number of development tools called Java
Development Kit(JDK) and the classes and methods called Java Standard Library(JSL). JSL is also
known as API(Application Programming Interface).
They are:
appletviewer- to run Java applets by reading and interpreting bytecodes
javac - Java compiler translates source code to bytecode and stores in .class file.
Java - Java interpreter
javap- Java disassembler to convert bytecode into program description
javah - to handle C header file
javadoc - to create java documentation as HTML files, using documentation comments included in
source code.
jdb - Java debugger for debugging a java program to find errors
The flowchart given below shows the process of building and running Java application programs:
Text Editor
Javac
Java Jdb
Package Purpose
Language Support package Java.lang Class for the implementation of basic features of java
Utilities packages Java.util Classes for the utility functions such as date, time etc.
Input/output Package Java.io Classes for i/o opertations
Networking package Java.net Classes for communicating with other computers via
internet
AWT package Java.awt Classes that implement platform-independent
Applet package Java.applet Classes that provides basic functionality for applets
Java Source Code —> Java Compiler —> Java Enabled Web Browser —> Output
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions
Main Method Class
{
Main Method Definition
Main Method Class is essential and all the other entries are optional.
Documentation Section
The documentation section contains comments about the program being written: In addition to two
types of comments in C and C++, Java includes a third type called documentation comment.
Single line comment begins with//(double slash)
Multi line comment begins with /* and ends with */
Documentation comment begins with /** and ends with */
Single and multiline comments tell why, what and how of the program being written.
Documentation comments are written with special documentation tags as shown below
/** @author Kumar */
/** @version 1.1 */
/** @since 2015-03-31 */
javadoc utility collects these doc tags to create documentation about the program in the form of
HTML file.
Package Statement
The first statement in a Java program is package statement.
This statement declares a package name and informs the compiler that the classes defined
here, belongs to this package.
package statement is optional, if we omit, java creates an empty package for it.
A named package can contain any number of classes
Example:
package employee;
classemp\
{
------
}
Import Statement
Next to package statement, there may be a number of import statements. This is equivalent to
#include statement in C/C++.
Examples:
importemployee.emp;
instructs the interpreter to load emp class alone that belong to employee package.
import employee.* ;
instructs the interpreter to load all the classes contained in employee package. * denotes all classes.
Interface Statements
An interface is like a class but includes a group of method declarations. It is optional, and
used only when multiple inheritance is implemented.
Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential
elementsof a Java program. A simple Java program may contain only this pan. The main method
creates objectsof various classes and establishes communication between them. On reaching the end
of main, theprogram terminates and the control passes back to the operating system.
}
Explanation:
Java Tokens
Smallest individual units in a program are known as tokens. The compiler recognizes them. In
simple terms, a Java program is a collection of tokens; comments and white spaces. Java language
includes five types of tokens. They are:
Reserved keywords
Identifiers
Literals
Operators
Separators
Keywords
Keywords are essential part of a language definition.
Java language reserved 50 words-as keywords.
Keywords have specific meaning in Java.
We can’t use them as names of variables, classes, methods and so on.
Java is case-sensitive.
All the keywords are to be written in lower-case letters.
The following are keywords in Java.
Examples:
Public methods
average sum
Identifiers with more than one word:
dayTemperature firstDayOfMoflth totalMarks
Private and Local variables(Iower case letters only)
length batch_strength
All classes and interfaces (each words first letter should be in upper case)
Student HelloJava Vehicle MotorCycle
Variables that represent constant values (all upper case letters and underscore between the words)
TOTAL FMAX PRINCIPAL_AMOUNT
Java Separators
Separators define the shape and function of code in a Java program. They are symbols used
for grouping and arranging the code.
Java Statements
A statement is an executable combination of tokens ending with a semicolon.
There are 8 types of statements in Java
D:\jdkl.3\bin>javac Hello.java
If there are no errors in source code, java compiler creates a file called Hello.class containing
bytecodeS of the program. .class extension is automatically given by the compiler.
Java Program —* Java Compiler —* Bytecode(virtual machine) —* Java Interpreter — Machine Code (Real Machine)
Here, the command line arguments contain 3 values. They are assigned as String value elements of
the array args[] as
args[0]—>ABC
args[11 —> Java
args[21 —>123
Constants, Variables and Data Types
Constants
Constants in Java are fixed values that do not change during the execution of a program. The
values are also called literals.
Literals
Literals are constants values to be stored in variables. Five types of literals in Java are:
o Integer literals
o Floating point literals
o Character literals
o String literals
o Boolean literals
Each of them is associated with a data type.
Type tells how the values behave and stored.
Java Constants
Numeric Non-Numeric
Constants Constants
Integer Constants
An integer constant is a sequence of digits. There are 3 types: decimal integer, octal integer
and hexadecimal integer.
Decimal integers consists of digits 0 to 9.
They can be negative (preceded by - sign)
Examples : 329 -45 78234
Real Constants
Real constants are used to represent quantities that vary continuously such as distance,
temperature, height, prices etc.
These quantities are numbers with fractional parts.
There are two notations used in real constant representation, namely, Decimal Notation and
Exponential notation.
Constants may or may not have digits before or after the decimal point.
Decimal point is compulsory
Mantissa is a real number in decimal notation. Exponent can be a +ve or -ye integer.
Example: 123.82 can be written as 1.2382e2 or 1.2382E2, where e2 stands for 102 -3 .08E-2
Exponent notation is useful for representing very large or very small numbers.
String Constants
A string constant is a sequence of characters enclosed between double quotes. The characters
may be alphabets, digits, special characters and blank spaces.
Variables
A variable is an identifier that denotes a storage location used to store a data value.
A variable may take different values at different times during the execution of a program.
Variable names may consists of alphabets, digits, underscore ( _ )and dollar character, subject
to the following conditions:
o They must not begin with a digit
o Uppercase and lower case are distinct. i.e. Total, total and TOTAL are different
variable names.
o It should not be a keyword.
o White space (space bar) is not allowed.
o Variable names can be of any length
Data Types
Data types specify the size and type of values that can be stored in a variable.
Java language is rich in its data types.
There are two major categories namely, primitive types(built-in or intrinsic) and
derived(reference) types
Integer Types
Integer types can hold whole numbers (34, -78, 1000)
Java supports 4 types of integers.
They are: byte, short, intand long
All integer types are signed one. unsigned type is not supported by Java
Table shows each type, their memory size and values that can be stored in them:
Wider the data types, they require more memory and longer execution time.
We have to choose smaller type for small numbers to improve execution speed.
long values are appended with character I or L. Example: a = 123456L
Floating Point Types
Floating point types can hold numbers containing fractiohal part(real numbers) such as
12.45, -0.03
There are two kinds of floating point storage namely, float and double.
float type values are single precision numbers (6 decimals accuracy)
double types values are double precision numbers (12 decimals accuracy)
float type values are appended with for F. Example d=34.567F
doubletype values are used when greater precision is needed in computation.
By default all floating point values are treated as double.
Explicitly double type values are appended with d or D.
Example m =234.34217890d
Boolean
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Character
The size of char type is 2 bytes, but it can hold single Unicode character
Unicode character set is an international character mapping scheme that supports more than
50 languages all over the world.
Minimum value is ‘\u0000’ (or 0).
Maximum value is ‘\uffff (or 65,535).
Variable Declaration
Variable declaration perform three things:
1. It tells the compiler what the variable name is.
2. it specifies the type of data the variable can hold.
3. Scope of the variable is determined by its place of declaration.
o More than one variable of same data type can be declared in a line
o Each one is separated by a comma
o Declaration must end in a semicolon (;)
Examples:
int quantity;
float angle, height;
double radius;
byte slno;
char sex;
Assignment statement:
start=0;
end=15;
sex=’M’;
Multiple assignments:
X= y = z = 0;
At the time of declaration:
inta=5;
double d =75.36;
long b = 1234567L;
float m = 5.67f;
char sex=M’;
byte s=5;
short k=32000;
Read Statement:
Variables can be given values interactively through keyboard using readLine() method as shown
below:
DatalnputStream d new DatalnputStream(System.in);
inta;
float b;
a Integer.parselnt(d.readLine());
b = Float.valueOf(d.readLine()).floatValue();
Scope of variables
Area of the program where the program is accessible is called its scope.
Java variables are classified into three kinds:
o instance variables
class variables
localvaries
instance variable is declared inside a class
instance variables are created when objects are created
they take different values for each object
separate memory location is allocated for them
class variables are global to a class
they belong to entire set of objects
only one memory location is allocated for them
local variables are declared and used inside methods
they are not available outside the method definition
local variables can be declared inside program blocks ({ })
when program control leaves the block, all the variables inside the block are destroyed and
memory freed.
Symbolic Constant
Certain constants may appear repeatedly in a number of places of a program.
Assignment of a symbolic name to such constants relieves us from typing the same value in
all the places. Symbolic constant is declared with the keyword final as given below:
Modifiability means, the modification of the value is done in one place only, which changes the
value in all the formulas which use it. Using symbolic constants in place of literals makes the
program easy to understand.
After defining a symbolic constant P1, final float P1 = 3.14f; the same formulae are in more
understandable form as shown below:
Area_of_Circle =P1 * r * r;
Area_of_Cylinder = P1 * r * r * h;
Circumference = 2 * P1 * r;
Moreover, accuracy can be improved by modifying the value in one place as final float P1 = 3.141
59f;
Note that:
o Symbolic name declaration takes the same form as variable declaration.
o They are written in uppercase letter (not a rule) to differentiate them from variables.
o After declaration, symbolic constants should not be assigned any other value.
o They cannot be declared inside a method. They should be declared as class data members or
in interface.
Examples:
Int m=50;
long n = (long) m; // which stores the value as long integer
float a = (float) m; //which stores the value 50 as 50.0
float, double integer types can be cast to any other type except boolean
Casting to smaller type can result in a loss of data
Casting a float value to integer results in loss of fractional part.
Examples:
Byte b=75;
int a = b; // widening
long a =100L;
int b = a; // narrowing
char c = ‘A’;
int n = c; // It stores the ASCII value of A, 65 in integer variable n.
int n=65;
char c =n; //It stores the character ‘A’ corresponding to the ASCII value 65 in variable c.
println() method (print in a line) method of out class in System package displays a given set of results on a
line followed by a line feed (\n).
Examples:
system.out.Print(”Oh!“);
system.out.print(“God! \n”);
System.out.Print(“save me”);
output: Oh! God!
Save me
Here, Oh! and God! are displayed in the same line and \n inserts a line feed. Save me is
displayed on the next line.
1.Arithmetic Operators
Arithmetic operators are used to construct mathematical expressions.
Arithmetic operators can operate on any built-in java numeric data types
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modula Division(Remainder)
If both operands are integer, integerarithmetic is performed and the result is integer e.g.
5/2=2 (result is not 2.5)
If both operands are real, floating point arithmetic is performed and the result is real
2.2/1 .1=2.0
For modulo division, sign of the results is always sign of the first operand
e.g. -l0 % 3= -l and l0 %-3= l
If one of the operands is integer and the other is real, the expression is called mixedmode
arithmetic expression. Computer performs higher order arithmetic. i.e. integer is converted to
real and the arithmetic is performed. Compared to integer, real is higher order, compared to
float, double is higher order.
2.Relational Operators
Relational operators compare two quantities.
We take decision depending on their outcome.
An expression containing relational operator is called relational expression.
The value of a relational expression (outcome) is either true or false.
Syntax: ae-1 relational operator ae-2
ac-1 and ae-2 can be variables or constants or arithmetic expressions. Arithmetic expressions are
evaluated first before comparison.
Operator Meaning
< Is less than
> Is greater than
<= Is less than or equal
>= Is greater than or equal
== Is equal to
!= Is not equal to
Examples:
a=5, b=8, c=10, d=7
3. Logical Operators
Logical operators are used to form compound conditions by combining tw or more relations.
Two or more relational expressions are combined to form logical expressions or compound
relational expression.
Logical expressions result in true or false values.
Java has three frequently used logical operators:
&&-Logical AND
|| - Logical OR
! - Logical NOT
Examples: if (experience>=5 && age<=35) mark =5; Here, the if statement checks the test
condition experience >=5 and age <=3 5, if both conditions are true the result will be true and 5
marks will be given to a candidate attending an interview. If one or both of them is false, the result
will be false.
if(experience =>5 j age<=25) mark 2; Here, if anyone of the condition is true, the result will be true
and 2 marks will be given to a candidate attending an interview. If both of them is false, the result
will be false.
Logical NOT operator complements false to true and vice versa. !(age>35) if age is 36 then condition
is true, ! will make it false. If age is 20 the condition is false. ! will make it true.
4. Assignment Operator
Assignment operator = is used to assign the value of an expression to a variable.
Java also supports shorthand assignment operators +=, -=, ,/=, %=.
Examples:
a=a+5; a+=5;
aa- b; a-b;
a a * (x+y); a = (x+y);
a’a/5, a15;
aa%S; a%5;
Examples:
a = 5;
a++; or ++a; mean the same, which increments the value of a by 1 and it becomes 6.
case 1: b=++a;
case2: b=a++;
o In case 1, Pre increment increments the value of a and assign the result 6 to b.
o In case 2, Post increment assigns the current value of a 5 to b and then increments it to 6.
o In both cases, value of a becomes 6, but what is assigned to b is different.
6. Conditional Operator
The conditional operator is a temary operator.
It requires three operands.
Syntax: expi ?exp2 : exp3
7. Bitwise Operators
Bitwise operators manipulate data values at bit level.
They are used for testing the bits or shifting them to the left or right.
Bitwise operators cannot be applied to float or double.
& - Bitwise AND
|-Bitwise OR
^- Bitwise Exclusive OR
~- Bitwise NOT (l’s complement)
<<-Shift left
>> - Shift right
>>> - Shift right with zero fill
Examples:
inta=5, b=4,c;
1 0 1
The first bit 1moves out, following bits are moved 1 position left. The last position is filled with 0.
The value becomes 010. Similarly, the right shift>> moves the last bit out and the blank in first
position is filled with 0. If the number is negative, it fills the blank position with 1.
1 0 1
>>> right shift with zero fill, fills the blank position always with zero irrespective of the sign of the
number.
8. Special Operators
Java supportS two special operators
They are: instanceof operator and .(dot) member operator
instanceof operator returns true if an object belongs to aclass we check.
Example mango instanceof fruit yields the result true if mango is an object of class fruit.
false otherwise.
dot operator is used to access the instance variables and methods of objects.
employee.age - accesses the age data member of employee object
employee.Tax_calc() - access the Tax_calc() method of employee object
Example:
x =10;
y=5;
if(x == 10+15 && y<10)
1.Simpleif statement
2. if.. else statement
3. Nested if..else statement
4. elseif ladder
1.Simpleif statement
if(test expression)
{
statement-block
}
statement-X
o Statement-block may be a single statement or a group of statements.
o If test expression is true then the statement-block is executed otherwise it is skipped and the
execution will jump to statement-x.
o If the condition is true both the statement-block and statement-X are executed.
Example:
ticketprice = 100;
if(age>=65)
{
tic ket_price5 0;
}
System.out.println(ticket_price);
The if statement given above fix the ticket_price as 50 for senior citizens and 100 for others.
Example:
if(sex’m’)
{
boy_countboy_count+ 1;
}
else
{
girl_count= girl_count+ 1;
}
start=l;
If sex is equal to ‘m’ (male), the statement boy_count=boy_count+ 1 is executed and the control is
transferred to statement start= 1.
Syntax:
if (test condition-i)
{
if(test condition-2)
{
statement-i;
}
else
{
statement-2;
}
}
else
{
Statement-3
}
statement-x;
Example:
if(sex== ‘m’)
{
if (age> 50)
{
medical_leave_days=30;
}
else
{
medical_leave_days=20;
}
}
else
{
medical_leae_Y5 = 50;
}
System.out.Println(sex + “ “+medical_leave_days);
Here, male employees aged more than 50 years are given 30 days of medical Icave and 20 days for
those males aged upto 50. For females it is 50 days with no restriction on age limit.
4. else if ladder
else if ladder is used when multipath decision are made. It is called as ladder as each statement
associated with else is another if statement.
Syntax: if (condition-i)
statement-i;
else if(condition-2)
statement-2;
else if (condition-3)
statement-3;
------------
else if(condition-n)
statement-n;
else
default-statement;
statement-x;
The conditions are evaluated from top.
As soon as the true condition is found, the statement associated with it is executed and the
control is transferred to statement-x.
If all the conditions are false, the default-statement is executed.
Example:
if(marks> 74)
grade =“Distinction”;
else if(marks>59)
grade=”First”;
else if(marks>49)
grade=” Second”;
else if(marks> 39)
grade=”Third”;
else grade = “Fail”;
5. Swtich Statement
When the number of alternatives increases, use of else if ladder makes the program difficult to read
and understand. Java supports another multi-way decision statement called switch statement. Switch
statement test the value of the given variable against a list of case values. When the match is found,
block of statements associated with a case is executed. If no match is found, default block is executed.
Syntax: switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
--------------
default:
default-block;
}
statement-X;
The expression is an integer expression or characters. value-1, value-2…... are constants or
constant expressions.
They are called case labels. The value of the expression is successively compared against
value-1, value-2…
When a match is found, block of statements that follow the case is executed.
break causes exit from switch statement.
default is an optional case. Block of statements in default case is executed if there is no match
with other cases.
Example:
switch(n)
{
case I: System.out.println(”ONE”);
break;
case 2: System.out.println(”TWO”);
break;
case 3 :System.out.println(”THREE”);
break;
case 4:System.out.println (”F0UR”)
break;
defauit:System.out.println(“Value of n should be in the range 1 -4”);
}
?: Operator
This operator has been discussed in Java Operators section.
This operator takes three operands.
It is known as conditional operator.
It makes two-way decisions.
It can be nested for more complex decisions
Use of conditional operator makes the code concise and efficient, but realability is
poor when it is nested.
The conditional expression is evaluated first. If the result is true, expression 1 is evaluated and
returned as value of the conditional expression, otherwise, expression2 is evaluated and returned.
Example: if(a> b)
big=a;
else
big=b;
The if statement given above can be written as
big= (a >b) ? a : b;
sign=(x==0)?0 : (x <0)? -l : +1 ;//Nested?:to get sign ofa number as 0 or-i or +1.
Looping –
Examples:
for(i=4 ;i< =10;i=i+l)
{
system.out.println(i);
}
system.out.println(“LOOP OVER”);
Here, loop control variable i varies from1 to 10 and the body of the loop is executed 10 times. It
displays every value of i (l,2,3...10). When i is incremented to 11, loop exits and displays LOOP
OVER message.
for(i=10; i>=1; i =i - 1)
{
System.out.println(i)
}
System.out.println(“LOOP OVER”) ;
Here, for loop allows negative increment. Values from 10 to 1 are printed in decreasing order.
The above program code will print multiplication table I to 5 with 10 entries for each table as shown
below:
1x1= 1
2x1= 2
3 x 1=3
-----
-----
10x 1= 10
upto 5 tables.
while Loop
Syntax: initialization
while (test condition)
{
body of the loop
} Statement-x;
Test condition is evaluated and if the condition is true, then the body of the loop is executed.
The process is repeated until the test condition finally becomes false.
When the condition becomes false, control is transferred out of the loop and Statement-x
following the loop is executed.
Compared to for loop initialization is done outside the loop, increment is inside the body of
the loop.
Body of the loop may have one or more statements. Braces are needed only if the body
contains two or more statements.
n= 1;
sum=0;
while(n<=10)
{
sum = sum + n;
n = n +1;
}
This while loop finds the sum of numbers 1+2+3+4..upto 10. The condition may also be written as
n<11.
This while loop repeats the input statement until the user enters a positive value for n. Initially a
negative va’ue is given to n to make the condition true when tested for the first time.
do while loop
do while loop is exitcontroed loop. It is used when we want to execute the body of the loop
before the test is performed.
Syntax: initialization;
do
{
Body of the loop;
}
while (test condition);
statement-x;
On reaching the do statement, body of the loop is executed first.
Test condition is evaluated at the end of the loop.
If the condition is true, the program continues to evaluate the body of the loop once again.
The process continues until the condition remains true.
Loop terminates when the condition becomes false and statemefltx following the loop will be
executed.
do while loop is suitable for menudriVen program5 where the menu is to be displayed first
followed by user response in making a choice from the menu.
Example:
i =101;
do
{
System.out.println(i);
i=i+l;
}
while(i<100);
Here, initial value of i (101) is displayed even though the condition is false. When it tests the
condition at the end of the loop, the condition becomes false( 102 <=100 is false) and the loop is
terminated, do while loop executes the body atleast once irrespective of the true or false nature of the
test condition.
Jumps in Loops
It may be desirable to perform early exit from a loop before its normal exit. It may be
necessary to skip part of the loop and continue with next value of loop c ntrol variable.
break statement
break statement performs early exit (aborting the ioop based on some conditions)
on encountering break statement, the ioop is immediately stopped and the statement following
the body of the ioop is executed.
When the loops are nested, break statement exits from the loop containing it. i.e. break will
exit only a single loop
continue statement
continue statement causes the ioop to be continued with next iteration
It skips any statements given after the continue statement until the end of the body of the
loop.
It causes the control to go directly to the test condition and continues the loop with next
value of the ioop control variable.
continue statement restarts the current loop.
Labelled Loops
Any statement or block of statements can be given a label. A label is a valid Java variable
name followed by a colon(:).
With the use of labels, we can break any loop in case of nested loops.
With the use of labels, we can continue any loop in case of nested loops.
labelled continue
Example:
outer: for(i=1 ;i<=1000;i++)
{
inner: for(j=1 ;j<=500;j++)
{
if(i % 8 = =0) continue outer;
if(i == 750) continue inner;
-----
-----
}
}
Here, if the value of i is a multiple of 8 (8, 16, 24,32 and so on) , next iteration of i loopwhose label is
outer: is continued skipping remaining part of the inner ioop. If i reaches the value 750, remaining
part of the j loop is skipped and the next iteration of j loop is continued.