Java R19 - Unit-1
Java R19 - Unit-1
Simple program in Java. Save this code in Text Document as “Start.java” C:\> java Start
Java compiler first converts the source code into an intermediate code, known as • It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,
bytecode or virtual machine code. To run the bytecode, we need the Java Virtual underscore (_).
Machie (JVM). JVM exists only inside the computer memory and runs on top of • It should not contain white spaces and special symbols.
the Operating System. The bytecode is not machine specific. The Java interpreter • It should not be a keyword of Java.
converts the bytecode into Machine code. The following diagram illustrates the • It should not be Boolean literal, that is, true or false.
process of compiling and running Java programs. • It should not be null literal.
• 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.
• The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is
restricted.
For compiling the program, the Java compiler javac is run, specifying the name of • keywords cannot be used as names of variables, methods, classes, or packages.
the source file on the command line as depicted here: • These are written in the lower case.
• Keywords of Java Language are as follows:
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
3 4
ii. Floating point literal
• These are floating decimal point numbers or fractional decimal numbers
with base 10. Examples are 3.14159, 567.78, etc.
v. String literal
• These are strings of characters in double quotes. Examples are “Delhi”,
“John”, “AA”, etc.
5 6
Operators: Operators are mostly represented by symbols such as +, -, *, etc Bitwise Operators:
Operator Description
Types of Operators: & Bitwise AND
| Bitwise OR
Arithmetic Operators: ^ Bitwise exclusive OR
Operator Description ~ Bitwise compliment
+ Addition or Unary plus >> Shift Right
- Subtraction or Unary minus << Shift Left
* Multiplication >>> Shift right with Zero fill
/ Division
Modulus Conditional Operators:
%
Operator Description
?: Used to construct Conditional expression
Relational Operators:
Operator Description
4. Java Statements
> Greater than A Statement is a instruction to the computer. A program is a set of statements or
>= Greater than or equal to instructions. The statements specify the sequence of actions to be performed when
< Less than some method or constructor is invoked. The statements are executed in the sequence
<= Less than or equal to in the specified order. The important Java statements are as follows.
== Equal to
Statement Description
!= Not equal to
Empty statement These are used during program development.
Variable declaration It defines a variable that can be used to store the values.
Logical Operators: statement
Operator Description Labeled statement A block of statements is given a label. The labels should not
&& Greater than be keywords, previously used labels, or already declared
|| Greater than or equal to local variables.
Expression statement Most of the statements come under this category. There are
! Less than seven types of expression statements that include
assignment, method call and allocation, pre-increment, post
Assignment Operators: increment, pre-decrement, and post decrement statements.
Operator Description Control statement This comprises selection, iteration, and jump statements.
+= Add and assign to Selection statement In these statements, one of the various control flows is
selected when a certain condition expression is true. There
-= Subtract and assign to
are three types of selection statements including if, if-else,
*= Multiply and assign to and switch.
/= Divide and assign to Iteration statement These involve the use of loops until some condition for the
%= Modulus and assign to termination of loop is satisfied. There are three types of
iteration statements that make use of while, do, and for
Increment / Decrement Operators: Jump statement In these statements, the control is transferred to the
beginning or end of the current block or to a labeled
Operator Description statement. There are four types of Jump statements including
++ Increment by one break, continue, return, and throw.
-- Decrement by one 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
7 8
Program 2.3: Illustration of command line
5. Command Line Arguments
class Sum
• A Java application can accept any number of arguments from the command line.
{
• These arguments can be passed at the time of running the program. This enables a public static void main{String args)
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 int s=1;
arguments to the application's main method through an array of strings.
• It must be noted that the number of arguments for(int i e; icargs length; 1++){
•
• in an array. To ensure this, we can make use of the length property of the array. This is s=s+Integer.parseInt(args(1]);
illustrated in
System.out.prinln(" The addition of passed arguments 15" );
Program 2.2: Example showing command line argument
}
class vehicle
public static void main(String args[]) Output
{
After compiling, the following lines are typed on the command
int x = args.length;
prompt: It produces the output as
for(int i=0; i<x; i++)
{ C:\> Java Sun 20 15 17
System.out.println(args[i]);
}
} Declaration of Variables
Output • A program may involve variables: variables are objects whose values may change in the
program.
(After compiling, type the following lines on the command prompt. It produces the output as) • A variable is declared by first writing its type, followed by its name or identifier as
C:\> Java vehicle “Car Cycle Motorbike" illustrated here.
Car
Cycle
Motorbike
• 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:
9 10
Program 2.4 illustrates the declaration and output of some data types Program 2.6: Illustration of a user's input from keyboard into
program
class PrintOut
{ import java.util.Scanner;
public static void main (String args[]) public class Arithmetic
{ {
String name = "Sunita"; //"name" is variable, value is "Sunita" public static void main(String[] args)
String str = "Hello"; //String set has value- "Hello!" {
Scanner scaninput = new Scanner (System. in);
int length = 50; // Variable name "length", value 50 int n;
int width = 8; // Variable name "width" value 8 int m;
System.out. print( "Enter the value of n : ");
System.out.print("Name= " + name); n=scaninput.nextInt();
System.out.print("Str = "+ str); //print statement System.out. print( "Enter the value of m : ");
m=scaninput.nextInt();
System. out.println();
System.out.println("Sum of two numbers is ="+(n+m));
System.out.println("Length "+ length);
System. out.println("Width " + width); System.out.println("Product of two numbers is ="+ n*m);
11 12
7. Escape Sequences 8. Comments
Escape Sequences character is preceded by a backslash (\)has a special meaning to • Comments are Line of Text which is not a part of the compiled program.
the compiler. Escape sequences are as follows. • Comments are used for documentation to explain source code.
• They are added to the source code of the program.
• Java supports three types of comments as:
1. Single-line comment: These comments are started with two front slash
characters (//)
Example:
// This is Single line comment
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:
/** It is documentation
Comments */
Program 2.9: Program on Escape Sequences
} 1. The program should present a clean and orderly look. In order to develop a clean
} program, the programmer can adapt the following measures:
C:\>javac Escape.java (b) Indenting is another method often used to improve the looks and readability
C:\>java Escape (c) Use of Lambda expression and method reference of Java 8 enhances the look
Value of a =0
b= 70 (d) Include a space before and after operators
A B Z
"Value of b" = 70
'Value of n' = 256
13 14
2. The program should be easy to understand. The programmer should take care of the
following aspects:
II. Data Types Variables and Operators :
(a) If it is team work, certain conventions about naming should be preset so that a team
member can easily identify an item. i. Introduction Data Types in Java
(b) The makers of Java have a set of rules which are followed in the Java library. The same
rules or an even better convention may be set. The Java language programs deal with the following entities:
(c) Judicial use of comments can increase understandability. Use of too many comments I. Primitive data
makes confusion in the program. 2. Classes and objects
(d) It is better to use already defined and tested library methods rather than user-defined 3. Interfaces and their references
methods
4. Arrays
(e) Expressions like z = x++ + - - c*++k; should be avoided.
5. Methods
3. Debugging should be easy. The programmer may adopt the following measures to
ensure easy debugging. 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.
(a) The vertical alignment of a similar item enhances the ability to find errors.
An array is n collection of items that may be of primitive type, class objects, or references.
(b) The code line should not be too long. The type of an array can be determined from the type of elements present in it.
(c) The variables should be declared close to the places of their use
(d) If it is a big program, it should be divided into small segments. In Java, it is easy because Data Types in Java
the program may comprise separate classes.
• Data Type is the type of the data which computer accepts. Every variable and expression
(e) The methods should not be too big. has a data type that is known at the compile time.
(f) Each source code file should have one class. • The declaration of data type with a variable or expression limits the types of values that a
(g) The braces should be vertically aligned, if possible. variable can have or the expression it can evaluate.
• Java is an object-oriented programming language based on classes and interfaces.
4. The program should be easy to use. The following points • Java defines some primitive (basic) data types that are not reference types of any class or
interface. Eight primitive (basic) types of data are defined in Java. The type names are
(a) The input into program should be easy, also the keywords shown here in bold letters
1. Integral types—byte, short, int, long
(b) The output should be self-explanatory should be taken care of
2. Floating point types - float, double
(c) The names used should imply the output type such as price, weight, length, and so on. 3. Character type -char
4. Boolean type – Boolean values – True, False
(d) Confusing and long names must be avoided.
There is a non-data type called void and no data can be of type void. This type is used for
5. The program should be easy to maintain methods that do not return any value.
(a) The program should be easily modifiable to ensure simplicity in fixing errors. Java is a case-sensitive language. This means that it takes Area, area, and AREA are three
different objects.
(b) The comments can help in modification of the program, fixing errors.
6. The program should be fail-safe. The failure of a program should not be catastrophic.
15 16
2. 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:
type Identifier;
Here type is the primitive data type and Identifier is the name of the variable.
Ex:
Program 3.1 illustrates the integer data types.
byte n; // declares a variable of type byte.
class DataType
short m = 67; // declares and initiates a short number {
public static void main (String args[])
int length; //declares length-a variable of type int
{
length - 50; // value is re-assigned after declaration byte a= 4, b=8 ;// variables of type byte
short c = 67, d = 98; // variables of type short
char ch = ‘A’; // declares a character variable ch. int e = 7000, f = 20000; // variables of type int
long secondsInYear = 365 * 24 * 60 * 60; // long type
Non-primitive Types //e=d+f;
System.out.println("(b + a) = " + (b+a));
These are the class and interface types. The name of a class or interface is the name of type.
System.out.println("b + a = " + b + a);
A class object is declared as System.out.println("c = "+ c + " \td = " + d);
Class_identifier object_identifier; System.out.println("e = " + e + "\t f= " + f);
System.out.println("Seconds in a year = "+ secondsInYear);
Similarly, an interface reference is declared as }
}
Interface_identifier reference_identifier; Output:
Example: C:\ >javac DataType.java
C:\ >java DataType
String str "Delhi":
(b + a) = 12
Data Types b + a = 84
c = 67 d = 98
i. Integers e = 7000 f= 20000
Integers are whole numbers, that is, they represent numbers that do not have a fractional part. Seconds in a year = 31536000
The integers can be declared in four types according to the size of memory allocated for them
ii. Characters
byte • A variable may have value in terms of a character in which the type of variable is char.
• These characters represent integer values.
short
• Java supports Unicode for the representation of characters.
int • Unicode supports all the character sets of all the major languages of the world.
• The initial version of Unicode allocated 2 bytes for storing characters.
long • The range of values for characters in the initial version of Unicode comprised from
‘\u0000’ to ‘\uffff ’ that is from 0 to 65535 both end values inclusive.
17 18
Output
Program 3 2 illustrates anthmetic operations on character constants and variables C:\>javac FloatType.java
C:\>java FloatType
class Datachar { Width = 20.0
public static void main (String args[]) Length = 40.5
{ Rectangle Area = 810.0
char ch1='E', ch2, ch3 ; Diameter 10.0
Area of Circle = 78.53975
System.out.println("ch1 =" +ch1); // printing ch1
iv. Boolean Type - Data
ch2=ch1++;
System.out.println("ch2 =" + ch2); // printing ch2 • For dealing with logical statements, variable of type boolean is supported.
• The value of boolean type variable is either true or false.
ch3=++ch1;
• The boolean type variables are unsigned as similar to char type variables.
System.out.println("ch3 =" + ch3); // printing ch3
• The variable may be declared as follows :
}
} boolean a;
Output: a = x > y;
C:\ >javac Datachar.java
C:\ >java Datachar If the aforementioned logical statement is correct, The value of a is true, otherwise the value
ch1 =E of a is false. In Java true and false are not converted into numerical values, which is
ch2 =E the case in other Languages. A boolean type variable is allocated to one byte, that is, 8 bits
ch3 =G
for storing its values Program
iii. Floating Point Numbers
• The numbers that are not whole numbers, or those that have fractional part, Examples are
3.5 illustrates the application of boolean type variables,
3.141, 476.6, and so on.
• Java supports two types of such numbers. class Boolean
Float: This type is used for single-precision decimal floating point numbers, that is, 7 digits {
after the decimal point. These numbers are stored on 4 bytes. public static void main (String args[])
{
Program 3.4: Illustration for working with float and double data double x= 5.5, y=10.5, p=4.0;
class FloatType int n=40, m=50;
{ boolean a,b,c,d;
public static void main (String args[])
a= x>y;
{
b= y>p;
float width =20.0f, length = 40.5f;
c= y==x;
float rectArea = length * width;
d= x<=y;
System.out.println("Width = "+ width); System.out.println("a = " + a +" and b =" +b);
System.out.println("Length = "+ length); System.out.println("Now c= "+c+ " and d = "+d);
System.out.println("Rectangle Area = "+ rectArea); }
}
double dia=10.0, pi=3.14159;
double areaCircle = pi* dia * dia / 4; C:\>javac Boolean.java
If there are nested blocks, a variable defined in the outer block is visible in the inner blocks
int a=4, b = 8, c = 9, d,e;
double x= 3.0, y=6.5, z,k; also and it cannot be redefined with the same name in the inner blocks
21 22
E:\>javac ScopeA.java Program 3.13 illustrates the use of symbolic constant
It is usually preferred to declare the symbolic constants using all the capital letters in a • The formatting string specifics the output format for each variable that consists of
program as follows: percent (%) sign followed by a conversion letter.
• Thus, the format string for output of an integer and character is "X" and or
public static final int c =299792458; respectively.
public static final double PI = 3.21415; • The order of variables in variable list should match with the list of formats in
formatting string.
• The following Table lists the conversion letters for different types of variables.
23 24
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
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 class
keeps a copy of the values of these variables.
Static Methods:
Program 3.14: illustration of formatting strings for output of different types of variables • The static methods are similar to class methods and can be invoked without any reference
of object of class, however, class reference (name of class) is needed, as in the following
class FormatPrintf example The method like sart() is declared as static method in Math class and is called
{
public static void main(String args[]) 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
int n = 713; case. Math and period ().
float x = 45.86f;
double d= 56.754; Program 3.18: illustration of using static methods of class Math
//for conversion into hexadecimal number System.out.println("The Square root root of 16 = "+ Math.sqrt(16));
System.out.printf("Hexadecimal value of 163 = %X \n", 163); System.out.println("The cubroot root of 27 = "+ Math.cbrt(27));
//printing five random variables
//for conversion into octal for(int i =1; i<=5;i++)
System.out.printf("Octal value of 163 = %o\n", 163); System.out.println("Random Number " + i + " = " +
} (int)(100 *Math.random()));
} }
}
25 26
E:\>javac StaticMethods.java • 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.
E:\>java StaticMethods ii. Final keyword can be applied to a member variable, local variable, method, or class.
The Square root root of 16 = 4.0
iii. Final member variable must be initialized at the time of declaration.
The cubroot root of 27 = 3.0
Random Number 1 = 77 iv. Final method cannot be overridden in Java
Random Number 2 = 69 v. Final class cannot be inheritable in Java
Random Number 3 = 83 vi. Final is different from finally keyword, which is used on Exception handling in Java
Random Number 4 = 2
Random Number 5 = 66 Example- 1:
public class Final
E:\>java StaticMethods {
The Square root root of 16 = 4.0 public static void main (String args[])
The cubroot root of 27 = 3.0 {
Random Number 1 = 67
int n =10; // Normal variable
Random Number 2 = 31 final int f = 20; // final variable
Random Number 3 = 10
Random Number 4 = 13 System.out.println("n = "+ n);
Random Number 5 = 40 System.out.println("f = "+ f);
• As mentioned in the comments, the values of PI, M, and x cannot be changed in their Example-2:
respective scopes.
public class Final
Final Method: {
public static void main (String args[])
• 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. int n =10; // Normal variable
final int f = 20; // final variable
• A final method cannot be overridden in a sub-class.
System.out.println("n = "+ n);
Final Class: System.out.println("f = "+ f);
• A Java class with final modifier is called final class A final class cannot be sub-classed or n = 50; // Now the value 50 is assigned to variable n
inherited. Several classes in Java are final including String, Integer, and other wrapper System.out.println("n = "+ n);
classes. }
}
27 28
C:\>javac Final.java
11. Assignment Operator ( = )
C:\>java Final Assignment operators:
n = 10
-Assignment operators are used to assign the result of an expression to a variable.
f = 20
n = 50 Operator Meaning
= Assignment
9. Introduction to Operators
-In addition, java has a set of short-hand assignment operators of the form
An operator is a symbol that tells the computer to perform certain mathematical and
V OP=EXP;
logical calculations.
- It is equivalent to
-The different types of Java operators are,
V=V OP EXP;
a) Arithmetic operators
-The short-hand assignment operators are
b) Relational operators
+= , -= , *= , /= , %=
c) Logical operators
Example:
d) Increment or decrement operators
a+=b ------------- a=a+b
e) Assignment operators
a-=b ------------- a=a-b
f) Conditional operators
a*= b -------------- a=a*b
g) Bitwise operators
a/=b --------------- a=a/b
h) Special operators
a%=b ------------- a=a%b
33 34
III. Control Statements: 3. Nested if Expressions
-if within if is called as Nested-if.
1. Introduction Syntax:
CONTROL STATEMENTS: (FLOW OF CONTROL) if(condition-1)
- A Control statement is a statement used to control the flow of execution in a Java Program. {
if(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
if(condition-3)
{
SELECTION STATEMENTS: Statement-3;
-Also called as conditional or decision-making control statements. }
-There are two types in Selection control statements. else
i) Two-way selection control statements {
ii) Multi-way selection control statements Statement-4;
i) Two-way selection control statements: }
-The different two-way selection statements are, }
a) if-else statement next statement;
b) null else statement
c) Nested-if statement Example:
if(a>b)
2. if Expression - also called as “ null else statement ”
{
Syntax: if(a>c)
if(condition) {
{ System.out.println(“a is greater”);
statements; }
} else
next statement; {
System.out.println (“c is greater”);
Example: }
if(a==2) }
{ else
p++; {
} if(b>c)
System.out.println(“program over”); {
System.out.println(“b is greater”);
}
else
{
System.out.println(“c is greater”);
}
}
35 36
4. if–else Expressions
Syntax: Example:
if(condition) if(a>b&&a>c&&a>d)
{ {
true-block statements; System.out.println(“a is greater”);
} }
else else if(b>a&&b>c&&b>d)
{ {
false-block statements; System.out.println(“b is greater”);
} }
next statement; else if(c>a&&c>b&&c>d)
{
Example: System.out.println(“c is greater”);
if(a>b) }
{ else
System.out.println(“a is greater”); {
} System.out.println(“d is greater”);
else }
{
System.out.println(“b 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.
b) else-if ladder statement: The ternary operator (? :) consists of three operands. It is used to evaluate Boolean
Syntax: expressions. The operator decides which value will be assigned to the variable. It is the only
if(condition-1) conditional operator that accepts three operands.
{ It can be used instead of the if-else statement. It makes the code much more easy, readable,
Statement-1; and shorter.
}
else if(condition-2) Syntax:
{ Expression1 ? Expression2 : Expression3
Statement-2;
} • The first expression is the test condition.
………………… • If it evaluates true, the Expression2 is executed; otherwise Expession3 is
……………..….. executed.
else if(condition n-1)
{ Example-1:
Statement-(n-1);
} public class Ternary
else {
{ public static void main (String args[])
Statement-n; {
}
next statement; int a=10;
int b = (a<20)? 100 :200; // a < 20 if statement
System.out.println("b= "+b);
}
}
37 38
Output:
C:\>javac Ternary.java 7. Iteration Statements
LOOP STATEMENTS:
C:\>java Ternary -The iteration control statements are also called as Repetition or Iteration control statements.
b= 100 -A looping process includes the following four steps.
Example-2: -Setting and initialization of a counter.
-Execution of the statements in the loop body.
public class Ternary -Test for a specified condition (loop control expression) for execution of a loop
{ -Incrementing or Decrementing counter.
public static void main (String args[]) i) Pretest and Posttest loops:
{ -In a Pretest loop, the condition is checked before we execute a loop body.
int a=10; -It is also called as entry-controlled loop.
int b = (a>20)? 100 :200; // a>20 – else statement -In the Posttest loop, we always execute the loop body atleast once.
System.out.println("b= "+b); -It is also called as exit-controlled loop.
}
} 8. while Expression
Output: a) while statement:
C:\>javac Ternary.java Syntax:
while(condition)
C:\>java Ternary {
b= 200 loop body;
}
6. Switch Statement next statement;
Syntax:
switch(expression) Example:
{ n=10,i=1,sum=0;
case value-1:statement-1;break; while(i<=n)
case value-2:statement-2;break; {
…………………………. sum=sum+i;
…………………………. i++;
case value-n:statement-n;break; }
default: default statement; System.out.println(“sum=”+sum);
}
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”);
}
39 40
9. do–while Loop - for Loop 11. Nested for Loop
Syntax: Syntax:
do
{ for(initialization;condition;inc or dec)
loop body; {
}while(condition);
next statement; for(initialization;condition;inc or dec)
{
Example: Inner loop body;
n=10,i=1,sum=0; }
do
{ Outer loop body;
sum=sum+i; }
i++; next statement;
} while(i<=n);
System.out.println(“sum=”+sum); Example:
n=10,i, j, sum=0;
10. for Loop for(i=1;i<=n;i++)
{
for statement:
Syntax: sum=sum+i;
for(initialization;condition;inc or dec) }
{ System.out.println(“sum=”+sum);
loop body;
}
next statement;
Example:
n=10,i,sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println(“sum=”+sum);
41 42
12. For–Each for Loop 13.Break Statement
Unconditional control statements:
The Java for-each loop or enhanced for loop. It provides an alternative approach to traverse the array -The unconditional control statements are,
or collection in Java. It is mainly used to traverse the array or collection elements. The advantage of a) break statement
the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is b) continue statement
known as the for-each loop because it traverses each element one by one.
break statement:
Advantages: -The break statement skips from the loop or block in which it is defined.
1. Less clutter in code, especially when iterators are used. -The control then automatically goes to the first statement after the loop or block.
2. Less chances of errors. -The general format is
3. Improves overall readability of program. break;
Limitations: Example:
1. It is designed to iterate in forward direction only.
2. In iteration, it takes a single step at a time. public class Break
3. It cannot simultaneously traverse multiple arrays or collections. {
Syntax: public static void main (String args[])
{
for (Object obj : Collection_name)
{ //printing the values from 1 to 10
Body of loop for(int i =0; i<10;i++)
} {
if (i==5)
Example: break; //Break Statement
System.out.println( i );
public class ForEach }
{ }
public static void main (String args[]) }
{
Output:
int myArray[] = {10,20,30,40,50}; C:\>javac Break.java
C:\>javac ForEach.java
C:\>java ForEach
10
20
30
40
50
43 44
14. Continue Statement.
-The continue statement is used for continuing next iteration of loop statements.
-When it occurs in the loop, it does not terminate but it skips the statements after it.
-It is useful when we want to continue the program without executing any part of the program.
-The general format is
continue;
Example:
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.
45