Professional Documents
Culture Documents
(OOP)
15 TL-Sec I & II
Engr. Maria Shaikh
maria.sheikh@faculty.muet.edu.pk
Decision Making/
Conditional
Statements
Iterative Control
Structure/
Loops
Engr. Maria Shaikh
Branching
Statements
Syntax:
if(condition)
{
statement 1;
statement 2;
...
}
Operation of If Statements
Implementation of If Statement
public class IfStatement {
public static void main(String[] args) {
int user=17;
if ( user < 18 ) {
System.out.println("user is less than 18");
}
}
}
Implementation of If Statement
public class Sample{
public static void main(String args[]) {
int a=20, b=30;
if(b>a)
System.out.println("b is greater");
}
}
if-then-else Statement
The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false.
An if statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Syntax:
if ( condition_to_test ) {
statements;
}
else {
statements;
}
IF ELSE IF 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.
Implementation of IF ELSE IF
Statement
import java.util.Scanner;
public class IfElseDemo {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int testscore ;
System.out.print("Enter your TEST SCORE: ");
testscore = user_input.nextInt();
String grade;
if (testscore >= 80) {
grade = "A1";
}
else if (testscore >= 70) {
grade = "A";
}
Implementation of IF ELSE IF
Statement (cont.)
else if (testscore >= 60) {
grade = "B";
}
else if (testscore >= 50) {
grade = "C";
}
else {
grade = "F";
}
System.out.println("Grade = " + grade);
}
}
Syntax
switch ( variable_to_test ) {
case value:
code_here;
break;
case value:
code_here;
break;
default:
values_not_caught_above;
}
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
Engr. Maria Shaikh
Loops
For Loop
While
Loop
Engr. Maria Shaikh
Do / DoWhile Loop
Loops
Sometimes we want a java program to repeat something over
and over again, a loop is used to make a program do something
more than one time.
A loop statement allows us to execute a statement or group of
statements multiple times, until a condition is met.
A programming loop is one that forces the program to go back
up again. If it is forced back up again you can execute lines of
code repeatedly.
Operation of Loops
Syntax
Description
break statement
break;
continue statement
continue;
goto statement
Syntax
for ( start_value; end_value; increment_number )
{
//YOUR_CODE_HERE
}
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. and this step ends with a semi
colon (;).
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 will not be executed and control
jumps
to
the
next
statement
past
the
for
loop.
Engr. Maria Shaikh
While Loop
The while statement continually executes a block of statements
while a particular condition is true.
The while statement evaluates expression, which must return
a boolean value. If the expression evaluates to true,
the while statement executes the statement(s) in the while block.
The while statement continues testing the expression and
executing its block until the expression evaluates to false.
A while loop statement in java programming language repeatedly
executes a target statement as long as a given condition is true.
Syntax
while (expression) {
statement(s)
}
You can implement an infinite loop using the while statement
as follows:
while (true){
// your code goes here
}
Engr. Maria Shaikh
Block Diagram of
While Loop
Do / 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.
the Boolean expression appears at the end of the loop, so the statements in
the loop execute once before the Boolean is tested.
If the Boolean expression is true, the control jumps back up to do
statement, and the statements in the loop execute again. This process
repeats until the Boolean expression is false.
The difference between do-while and while is that do-while evaluates
its expression at the bottom of the loop instead of the top. Therefore,
the statements within the do block are always executed at least once.
Syntax
do {
statement(s)
}
while (expression);
Block Diagram of
Do / Do-While Loop
Syntax:
for (declaration : expression)
{
//Statements
}
Syntax (cont.)
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.
Engr. Maria Shaikh
Nested Loop
The placing of one loop inside the body of another
loop is called nesting.
When you "nest" two loops, the outer loop takes
control of the number of complete repetitions of the
inner loop.
While all types of loops may be nested, the most
commonly nested loops are for loops.
Syntax
Branching Statements
The break Statement:
The break statement has two forms labeled and unlabeled.
An
unlabelled
break
statement
terminates
the
innermost switch, for, while, or do-while statement, but a
labelled break terminates an outer statement.
An Labeled break statement uses nested for loops to search
for a value in a two-dimensional array. When the value is
found, a labeled break terminates the outer for loop (labeled
"search"):
Engr. Maria Shaikh
Arrays
Java provides a data structure, the array, which stores a fixed-size
sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type.
Java array is an object the contains elements of similar data type. It is a
data structure where we store similar elements. We can store only fixed
set of elements in a java array.
An array is a container object that holds a fixed number of values of a
single type. The length of an array is established when the array is
created. After creation, its length is fixed.
Each item in an array is called an element, and each element is accessed
by its numerical index.
Engr. Maria Shaikh
Arrays
Horizontal Array
Vertical Array
Arrays
Advantage of Java Array:
Code Optimization: It makes the code optimized, we can
retrieve or sort the data easily.
Random access: We can get any data located at any index
position.
int [ ] anArray;
Like declarations for variables of other types, an array declaration has two
components: the array's type and the array's name. An array's type is written
as type[], where type is the data type of the contained elements; the brackets
are special symbols indicating that this variable holds an awhere type is the
data type of the contained elements; the brackets are special symbols
indicating that this variable holds an array.
As with variables of other types, the declaration does not actually create an
array; it simply tells the compiler that this variable will hold an array of the
specified type.
Engr. Maria Shaikh
float anArrayOfFloats [ ];
However, convention discourages this form; the brackets identify
the array type and should appear with the type designation.
The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:
int [ ] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
Engr. Maria Shaikh
Processing Arrays:
When processing array elements, we often use either
for loop or foreach loop because all of the elements in
an array are of the same type and the size of the array
is known.
Multidimensional Array
Arrays can have more than one dimension, these arrays-ofarrays are called multidimensional arrays. They are very
similar to standard arrays with the exception that they have
multiple sets of square brackets after the array identifier. A
two dimensional array can be though of as a grid of rows and
columns.
Multidimensional Array
Syntax to Declare Multidimensional Array in java
Multidimensional Array
Example to initialize Multidimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Engr. Maria Shaikh
Copying Arrays
Copy of Range Method:
The java.util.Arrays.copyOfRange(short[] original, int from, int
to) method copies the specified range of the specified array into a new
array.
The final index of the range (to), which must be greater than or equal to
from, may be greater than original.length, in which case (short)0 is
placed in all elements of the copy whose index is greater than or equal to
original.length - from.
The length of the returned array will be to - from.
public static short[ ] copyOfRange (short[ ] original, int from, int to)
Parameters:
original -- This is the array from which a range is to to be copied.
from -- This is the initial index of the range to be copied, inclusive.
to -- This is the final index of the range to be copied, exclusive.
Return Value
This method returns a new array containing the specified range from the
original array, truncated or padded with zeros to obtain the required length.
Engr. Maria Shaikh
Sorting Arrays
Java.util.Arrays.sort(int[ ]) Method:
The java.util.Arrays.sort(int[]) method sorts the specified
array of ints into ascending numerical order.
Declaration:
Following is the declaration for java.util.Arrays.sort() method
END OF SLIDE
Engr. Maria Shaikh