You are on page 1of 85

Fundamentals of Java

Programming Language

1
Basic Elements of
Programming Languages
● The smallest pieces of source code, which are
meaning full to the compiler, are known as tokens.
● In any Programming Language including Java, the
tokens are divided into five categories:
1. Identifiers
2. Keywords
3. Literals
4. Operators
5. Separators 2
Java Identifiers
Identifiers: are names used to identify such
programming entities as variables, constants, methods,
classes and packages.
● Rules for naming identifiers are:
– Sequence of characters consist of letters, digits,
underscore(_), and dollar sign($).
– Start with letter, an underscore(_), or dollar sign($). Cannot
start with a digit.
– Cannot be a reserved keyword.
– Cannot be the literals 'true', 'false' or 'null'.
– Can be any length(max 255 characters). 3
Java Keywords
Keywords: are reserved words and have special
meaning for the compiler.
– Can’t be used as identifiers in a program.
● Some of java keywords:
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
4
try void violate while
Java Literals
Literals: are elements that are used in an invariant
manner, also known as constants.
– They can be numbers, characters, or string.
● eg. Numeric Literals: 1, 2, 3.9; Character Literals: 'a', 'b', '1',
'2'; String Literals: “Abebe”, “1234.56”, “Anything enclosed
with in double quotes”
– Numeric literals can be an integer, floating point number
or Boolean.
– Numeric literals are integer in case of full numbers and
double in case of real numbers.

5
Java Operators
Operators: specify the evaluations to be performed
on data objects(Operands).
● Java operators are broadly divided into:
– Arithmetic operators (+, -, *, /, %)
– Assignment operator (=, +=, -=, *=, /=, %=)
– Relational operators (<, <=, >, >=, !=, ==)
– Logical operators (&, |, &&, II, !)
– Increment/Decrement operators (++, --)

6
Java Separators
Separators: are used to inform the java compiler,
how statements are grouped together in the code.
– Java supports the following separators: {, }, ;, , , :, ., ( , ),
etc.

7
Anatomy Of A Java Program
● Any application program has the following
components:
– Comments
– Reserved words
– Modifiers
– Statements
– Blocks
– Classes
– Methods
– The main method

8
Anatomy Of A Java Program
● Comments: Java supports the following three types of
comments:
// single line comment
/* multi-line comment*/
/**java doc comments*/
● Modifiers: are keywords that specify:
– the properties of the data, methods, and classes, and how they can be
used.
– Example: public, static, private, final, abstract, and protected.
● A public datum, method, or class can be accessed by other
classes; and a private datum or method can’t be accessed by
other classes. 9
Java Statements
● A statement is a simple command written in a
programming language that causes something to
happen.
● All statements in Java are separated by
semicolons ';'.
● Some statements produce a value and are known
as expressions.
● It forms a complete unit of execution.

10
Java Statements
● Java statements are categorized as follows:

11
Java Statements
● Labeled statements: are any statements
beginning with the keyword “label”. The
“label” keyword is in combination with “goto”.
● Synchronization statement: are statements
used for handling issues related with multi-
threading (multi tasking).
● Guarding statements: are statements used for
handling errors (exceptions). The three keywords
used in handling exceptions are: try, catch,
and finally.
12
Java Statements
● Blocks: A block is a group of zero or more statements
between a pair of braces and can be used anywhere even
for a single statement.
● Example:
if(Character.isUpperCase(aChar)){
System.out.println("The character " +
aChar + " is upper case.");
} else {
System.out.println("The character " +
aChar + " is lower case.");
}
13
Constants, Variables
and
Data Types

14
Constants
● Constants: are fixed values (literals to be
stored in variables) that do not change during
the execution of a program.

15
Constants
Numeric Constants Non-Numeric Constants
'A’ ---- character constants
23411 --- integer constant
O425 --- octal constants
’7' ---- character constants
(begin with the letter ‘O’) ’\' ---- character constants
0x7 ---- hexadecimal constants “WELCOME” ---- string constatns
00X ---- hexadecimal constants “THE-END” ---- string constatns
0A2B ---- hexadecimal constants “BYE …BYE” ---- string constatns
0.0234 ---- real constants “A” ---- string constatns
0.777 ---- real constants
-1.23 ---- real constants

16
Symbolic Constants
● Symbolic Constants: are names given to numbers
instead of using the numbers in programs directly.
– Example: instead of using 3.14, we may name it as PI &
use the word PI instead of 3.14 in our programs.
● Symbolic constants:
– Should be in capital letters
– Re-assigning after declaration is illegal
– Cannot be declared inside methods
– Are declared as:
final var_type symbolic_name = value;
● Eg: final float PI = 3.14; 17
Backslash Character Constants
● Java supports some special character constants in
which if we want to display them from our program.
● These constants are given in following table.

18
Variables
What is a Variable: Variables are a place where
information can be stored while a program is running.
● Their value can be changed at any point in the
program.
● In order to create a variable, you must give it a name
and identify what type of information it will store.
● Variables are identifiers that denote a storage
location that store data values i.e., they are names of
storage locations.

19
Naming Variables
● The name that you choose for a variable is called an
identifier.
● An identifier can be of any length, but must start with:
– a letter (a – z)
– an underscore ( _ )
– or a dollar sign ($)
● The rest of the identifier can include any character
except those used as operators in java such as + , - ,
*, /, %.

20
Pop Quiz
● Which of the following are valid variable names?
1)$amount
2)6tally
3)my*Name
4)salary
5)_score
6)first Name
7)total#

21
Data Types
● All kinds of data that can be stored in computer do:
– not take the same space and
– same operations cannot be made on them.
● Example: Consider the two data values: 20 and
“Abebe”
– The two data values do not take the same memory
space and also operations.
– Multiplication operation can be made on the number
item but not on the string item.
● So, to handle these issues, a “data typing” system
is used. 22
Data Types
● Data type means “ the type of item (value) to be
stored in memory”.
● They are used to identify:
– amount of memory size that should be assigned to a
given data/item and
– kinds of operations that could be made on the item.
● In Java programming language, data types are
categorized as:
– primitive/built-in data types and
– derived/user-defined data types.
23
Data Types

24
Data Types
Integer Types: can hold the integer numbers (the
number can be positive number or negative number).
– In Java, there are four types of integer data types: byte,
short, int, and long.
Floating Point Types: also called as Real number. We
use floating point types to represent decimal numbers
upto certain accuracy(precision).
– There are two types of decimal numbers: float and
double.
Character Type: It is used to store single character in
memory.
– char type is used to characters enclosed in single quote25 ' '.
Data Types
Boolean Data Type: It is used when we want to test a
particular condition during the execution of the program.
– There are only two values that a boolean type can hold: true
and false.
– Boolean type is denoted by the keyword boolean and uses
only one bit of storage, i.e.,
● Bit 1 for boolean value true and
● Bit 0 for boolean value false.
The following table shows
– the 8 primitive data-types,
– the memory size they take and
26
– the ranges of values they can hold.
Data Types

Data Type Size in byte Value Range


byte 1 byte -128 to 127
boolean 1 bit true or false
char 2 bytes A-Z, a-z, 0-9, etc
short 2 bytes -32768 to 32767
int 4 bytes -2^32 to (2^32)-1
long 8 bytes -2^64 to (2^64)-1
float 4 bytes 1.4e(-45) to 3.4e(+38)
double 8 bytes 4.9e(-324) to 1.7e(+308)

27
Pop Quiz
● What data types would you use to store the following
types of information?

1)The number of students in the room


2)Location of a point on screen
3)Speed of light
4)Open/Closed status of a file
5)The first letter of your name
6)$237.66

28
Variable Declaration
● Variable declaration does three things:
– Tells the compiler what the variable name is.
– It specifies what type of data(value) the variable will hold.
– The place of declaration in the program decides the scope of the
variable.
● Syntax to declare a variable is:
[data-type][variable_name];
● Syntax to initialize a variable is:
[variable_name] = [value];
● Initialization and declaration can be done at one time as:
[data-type][variable_name] = [value]; 29
Variable Declaration
Examples:
int a, b, c; //Declares three ints, a, b, and c.

int a = 10, b = 10; //Example of initialization.


byte B = 22;//Declares and initializes a byte type variable B.
double pi=3.14159; //Declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
● Giving values to variables is done in two ways:
– By using assignment statement: variable_name=value;
– By using readLine() function.
● To initialize characters, the characters are placed under
30
single quotes while strings are under double quotes.
Scope and Life Time of Variables
Java variables are three types: Instance variables, Class
variables and Local variables.
● Instance variables: are created when objects are instantiated.
– They are associated with objects.
– They take different values for different object.
● Class variables: are global to a class and belong to the entire
set of objects that the class creates.
– Only one memory location is created for each class variable.
– They are declared as “static” data members.
● Local variables: are declared and used inside methods /
functions.
– And their scope and life time is inside the body of the function. 31
Scope and Life Time of Variables
Scope of a Variable: is the region of a program within which
the variable can be referred to by its simple name.
● A scope also determines when the system creates and
destroys memory for the variable.
● A block defines a scope: Each time you create a block of
code, you are creating a new, nested scope.
● Variables are created when their scope is entered, and
destroyed when their scope is left.
● Thus, the lifetime of a variable is confined to its scope.
● Objects declared in the outer block will be visible to code
within the inner block down from the declaration.
(The reverse is not true). 32
Operators

33
Operators
● Operators are the most basic units of a program.
– They perform operations on primitive data types.
● Operators are special symbols used for:
– mathematical functions,
– assignment statements, and
– logical comparisons.
● As you know, expressions are statements that
produce a value.
● Some of the most common expressions are
mathematical and make use of operators
34
Operators
● An operator performs a function on one, two, or three
operands.
● An operator that requires one operand is called a
unary operator.
● The unary operators support either prefix or postfix
notation.
– Prefix notation means that the operator appears before its
operand.
– Postfix notation means that the operator appears after its
operand
operator operand; //prefix notation
operand operator; //postfix notation 35
Conditional Operator
● The character pair ?: is a conditional, which is a
ternary operator of Java, and is used to construct
conditional expressions of the following form:
(Expression1)?(Expression2):(Expression3)
variable x = (expression)? value if true : value if false
● The operator ?: works as follows:
– Expression1 is evaluated if it is true then is evaluated
and becomes the value of the conditional expression.
– If Expression1 is false then Expression3 is
evaluated and its value becomes value of the conditional
expression.
36
Conditional Operator
Example:
public class Test{
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20 : 30;
System.out.println("Value of b is : " + b );
b = (a == 10) ? 20 : 30;
System.out.println("Value of b is : " + b );
}
}
This would produce the following result:
Value of b is : 30
37
Value of b is : 20
Types of Operators
● Java operators are broadly divided into:
– Arithmetic operators (+, -, *, /, %)
– Assignment operator (=,+=,-=,*=,/=,%=)
– Relational operators (<,<=,>,>=,!=,==)
– Logical operators (&, |, &&, ||, !)
– Increment/Decrement operators (++, --)

38
Arithmetic Operators
● Java has 4 basic arithmetic operators +,-,*, and /,
which have the usual meanings – add, subtract,
multiply, and divide.
● The order of operations or precedence that applies
when an expression using these operators is evaluated
is the same as you learned at school (BODMAS).
For Example:
int number = 20 – 3*3 – 9/3 ;
●will produce the value 8
int number = (20 – 3)*(3 – 9)/3;
● is equivalent to 17*(-6)/3 will produce the value
-34 39
Assignment Operators
● Assignment operators include = as well as the
arithmetic operators (+,-,/,*, and %) used in
conjunction with it.

● For example:
– count += 5; is equivalent to count = count + 5;
– result /= a % b/(a+b); is equivalent to
result = result / (a % b/(a+b));

40
Relational Operators
Operator Description
Produces the value true if the left operand is greater than the
> right operand, and false otherwise
Produces the value true if the left operand is greater than or
>= equal to the right operand, and false otherwise
Produces the value true if the left operand is equal to the right
== operand, and false otherwise
Produces the value true if the left operand is not equal to the
!= right operand, and false otherwise
Produces the value true if the left operand is less than or equal
<= to the right operand, and false otherwise

Produces the value true if the left operand is less than the right
< operand, and false otherwise
41
Relational Operators
For example:
int x = 3;
int y = 5;
boolean state;
● state = (x > y);
● now state is assigned the value false because x is not greater
than y

● state = (15 == x*y);


● now state is assigned the value true because the product of x
and y equals 15

● state = (x != x*y);
● now state is assigned the value true because the product of x
and y is not equal to x
42
Logical Operators
● Logical operators are only used to combine
expressions that have a value of true or false.
● Because they operate on boolean values they are
also referred to as boolean operators.
Symbol Long Name
& Logical AND
&& Conditional AND
| Logical OR
|| Conditional OR
! Logical negation (NOT)
43
Logical Operators
● Truth Table for Logical Operators:

x&y x|y
x y !x
x && y x || y

True True True True False

True False False True False

False True False True True

False False False False True

44
Logical Operators
For example:
boolean x = true;
boolean y = false;
boolean state;
● Let state = (x & y);
● now state is assigned the value false (see truth
table!)
● Let state = ((x | y) & x);
● now state is assigned the value true: (x | y) gives
true (see truth table!) and then (true & x) gives true

45
Logical Operators
For example:
boolean x = true;
boolean y = false;
boolean state;
● Let state =(((x || y) | (!x)) & ((! y) & x))
● now state is assigned the value true:
– (x II y) gives true; (!x) gives false;
so ((x || y) | (! x)) is equivalent to (true | false)
which gives true.
– (!y) gives true; so ((!y) & x) is equivalent to
(true & x) which gives true.
● So the whole expression for state is equivalent to
(true & true), that state is true.
46
Logical Operators
&& versus &:
● The difference between && and & is that:
– The conditional && will not bother to evaluate the right-hand
expression if the left-hand expression is false, since the result
is already determined in this case to be false.
– The logical & operator will evaluate both terms of the expression.
|| versus |

The difference between || and | is that:
– The conditional || will not bother to evaluate the right-hand
expresion if the left-hand expression is true, since the result is
already determined in this case to be true.
– The logical | operator will evaluate both terms of the expression.
47
Logical Operators
● As we saw in the previous examples in most cases the
two operators are interchangeable.
● Here are examples of where it matters which operator we
use.
if(++value%2 == 0 & ++count<limit) {
// Do something
}
● Here the variable count will be incremented in any event.
● If you use && instead of &, count will only be incremented if
the left operand of the AND operator is true.
● You get a different result depending on which operator is
used. 48
Logical Operators
if(count > 0 && total/count > 5) {
// Do something
}
● In this case the right operand for the && operation
will only be executed if the left operand is true –
that is, when count is positive.
● Clearly, if we were to use & here, and count
happened to be zero, we will be attempting to
divide the value of total by 0, which will terminate
the program.
49
Increment/Decrement Operators
● Let
int count;
count = count + 1;
● The statement above can be written as
++count;//This operator is called the increment operator.
● The decrement operator has the same effect on
count for subtracting 1.
count = count – 1;
is equivalent to
--count; 50
Increment/Decrement Operators
● The increment/decrement operator has two forms:
The prefix form: ++count, --count The postfix form: count++, count--
● first adds 1 to the variable and then ● first evaluates the expression

continues to any other operator in the and then adds 1 to the variable
expression
int numOrange = 5; int numOrange = 5;
int numApple = 10; int numApple = 10;
int numFruit; int numFruit;
numFruit = ++numOrange + numApple; numFruit = numOrange++ + numApple;

Now: numFruit has value 16 ●
Now: numFruit has value 15
numOrange has value 6 numOrange has value 6

51
Precedence of Operators
● Precedence specifies the order in which an
operation is performed.
● Consider the expression: a+b*c
– The multiplication is carried out first, then the value of
b*c is added to a
● Here is a table which outlines the precedence of
operators in Java and their associativity(from left to
right or from right to left)
● Note: Some of these operators will not be familiar
to you, you will learn more about them in the
coming lectures. 52
Precedence of Operators
P = Precedence A = Associativity

P A Operator P A Operator

15 L . , [ ] , (args) , ++, -- 7 L &

14 R ++ , -- , + , - , ~ , ! 6 L ^

13 R new , (type) 5 L |

12 L *,/,% 4 L &&

11 L +,- 3 L ||

10 L << , >> , >>>


2 R ?:

9 L < , <= , > , >=


= , *= , /= , %= , += , -=
1 R <<= , >>= , >>>= , &=
^= , |= 53
8 L == , !=
Pop Quiz
1) What is the value of number? int number = 5*3–3/6–9*3;
2) What is the value of state?
int x = 8;
int y = 2;
boolean state;
state = (15 == x*y);

3) What is the value of state?


boolean x = false;
boolean y = true;
boolean state;
state = (((x && y) & (!x)) || ((! y) | x))
4) What is the value of numCar and numGreeenCars?
int numBlueCars = 5;
int numGreenCars = 10;
int numCar;
54
numCar = numGreenCars++ + numBlueCars + ++numGreeenCars;
Control Structures
Control structures: are a way to alter the natural
sequence of execution in a Java program.
● In other words, they act as “direction signals” to
control the path a program takes.
● Control structures include:
● Block Statements
● Selection/Decision Statements
● Iteration/Repetition Statements
● Branching/Jumping Statements

55
Block Statements
A Block Statement groups zero or more statements
between curly brackets:
{
*/Normally, two or more statements are
used inside block statements/*
}
● From the compiler’s perspective, a block statement is
equivalent to a single statement.
● Block statements can be nested inside other block
statementsts.
56
Block Statements
A Block Statement groups zero or more statements
between curly brackets:
{
*/Normally, two or more statements are
used inside block statements/*
}
● From the compiler’s perspective, a block statement is
equivalent to a single statement.
● Block statements can be nested inside other block
statementsts.
57
Selection/Decision Statements
There are two types of decision making statements in Java. They
are:
– if statements
– switch statements
The if Statement: consists of a Boolean expression followed by
one or more statements.
Syntax: The syntax of an if statement is:
if(Boolean_expression)
{
Statements; //Will execute if the
Boolean expression is true
} 58
If Statements
● If the Boolean expression evaluates to true then the block of code
inside the if statement will be executed.
● If not the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
● Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.println("This is if statement");
}
}
}
● This would produce the following result:
This is if statement 59
The if...else Statement
● An if statement can be followed by an optional else
statement, which executes when the Boolean
expression is false.
Syntax: The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true

}else{
//Executes when the Boolean expression is false

}
60
The if...else Statement
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
This would produce the following result:
This is else statement 61
The if...else if...else Statement
● An if statement can be followed by an optional else
if...else statement, which is very useful to test
various conditions using single if...else if statement.
● When using if ... else if ... else statements there are
few points to keep in mind.
– An if can have zero or one else's and it must come after
any else if's.
– An if can have zero to many else if's and they must
come before the else.
– Once an else if succeeds, none of the remaining else if's
or else's will be tested.
62
The if...else if...else Statement
Syntax: The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.

63
The if...else if...else Statement
Example:
public class Test {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
Value of X is 30 64
Nested if...else Statement
● It is always legal to nest if-else statements which means you can
use one if or else if statement inside another if or else if
statement.
● Syntax: The syntax for a nested if...else is as follows:
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression2){
//Executes when the Boolean expression 2 is true

}
}
● You can nest else if...else in the similar way as we have nested if
statement.
65
Nested if...else Statement
Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
This would produce the following result:
66
X = 30 and Y = 10
The switch Statement
● The switch statement enables you to test several
cases generated by a given expression.
– It allows a variable to be tested for equality against a
list of values.
– Each value is called a case, and the variable being
switched on is checked for each case.
● The expression must produce a result of type
char, byte, short or int, but not long, float,
or double.

67
The switch Statement
Syntax: The syntax for switch statement is:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
} 68
The switch Statement
● Rules that apply to a switch statement:
– The variable used in a switch statement can only be a byte, short, int, or
char.
– You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
– The value for a case must be the same data type as the variable in the
switch and it must be a constant or a literal.
– When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
– When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
– Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
– A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case. 69
The switch Statement
Example:
public class Test {
public static void main(String args[]){
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
Default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
70
}
Iteration/Repetition Statements
● A loop allows you to execute a statement or block
of statements repeatedly.
● There are three types of loops in Java:
– for loops
– while loops
– do-while loops
● As of Java 5, the enhanced-for-loop was
introduced which is mainly used with Arrays.

71
The while loop
● A while loop is a control structure that allows you to
repeat a task a certain number of times while a condition
is satisfied.
Syntax: The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
● When executing, if the boolean_expression result is true,
then the actions inside the loop will be executed.
● This will continue as long as the expression result is true.
72
The while loop
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 15 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
} value of x : 10
value of x : 11
} value of x : 12
value of x : 13
● This would produce the following result: value of x : 14
73
The do – while loop
● A do...while loop is similar to a while loop, except
that a do...while loop is guaranteed to execute at
least one time.
Syntax: The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);
● Notice that the Boolean_expression appears at the
end of the loop, so the statements in the loop
execute once before the expression is tested. 74
The do – while loop
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 15 );
} value of x : 10
value of x : 11
} value of x : 12
value of x : 13
● This would produce the following result: value of x : 14
75
The for loop
● A for loop is a repetition control structure that
allows you to efficiently write a loop that needs to
execute a specific number of times.
● A for loop is useful when you know how many
times a task is to be repeated.
Syntax: The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}

76
The for loop
Here is the flow of control in a for loop:
● The initialization step is executed first, and only once.
– This step allows you to declare and initialize any loop control variables.
– You are not required to put a statement here, as long as a semicolon appears.
● Next, the Boolean_expression is evaluated.
– If it is true, the body of the loop is executed.
– If it is false, the body of the loop does not execute and flow of control jumps to the
next statement past the for loop.
● After the body of the for loop executes, the flow of control jumps back up
to the update statement.
– This statement allows you to update any loop control variables.
– This statement can be left blank, as long as a semicolon appears after the
Boolean expression.
● The Boolean expression is now evaluated again, and the loop is repeated
until the boolean expression is false. 77
The for loop
Example:
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 15; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
● This would produce the following result: value of x : 12
value of x : 13
value of x : 1478
The enhanced – for loop
● As of Java 5, the enhanced for loop was introduced. This is mainly
used for Arrays.
Syntax: The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type
compatible with the elements of the array you are accessing.
– The variable will be available within the for block and its value
would be the same as the current array element.
Expression: This evaluates to the array you need to loop through.
– The expression can be an array variable or method call that returns
an array. 79
The enhanced – for loop
Example:
public class Test {
public static void main(String args[]){
int[] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String[] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
● This would produce the following result:
10,20,30,40,50,
80
James,Larry,Tom,Lacy,
Jumping/Branching Statements
● The break Keyword: is used to stop the entire
loop.
– The break keyword must be used inside any loop or a
switch statement.
– The break keyword will stop the execution of the
innermost loop and start executing the next line of
code after the block.
Syntax: The syntax of a break is a single statement
inside any loop:
break;

81
Jumping/Branching Statements
Example:
public class Test {
public static void main(String args[]) {
int[] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
● This would produce the following result:
10
82
20
Jumping/Branching Statements
● The continue Keyword: can be used in any of
the loop control structures.
– It causes the loop to immediately jump to the next
iteration of the loop.
– In a for loop, the continue keyword causes flow of
control to immediately jump to the update statement.
– In a while loop or do/while loop, flow of control
immediately jumps to the Boolean_expression.
Syntax: The syntax of a continue is a single
statement inside any loop:
continue; 83
Jumping/Branching Statements
Example:
public class Test {
public static void main(String args[]) {
int[] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
● This would produce the following result:
10
20
40
84
50
Pop Quiz
1.In the switch statement expression must produce
a result of what type?
2.What must be used to separate each section of a for
statement.
3.Which statement causes a program to go back to the
statement that began a loop and then keep going
from there.
4.Write a for loop that outputs 100-1 in reverse
sequence.
5.Write a for loop that outputs all numbers that are
divisible by 3 between 0-50. 85

You might also like