You are on page 1of 104

OBJECT ORIENTED PROGRAMMING

(OOP)

15 TL-Sec I & II
Engr. Maria Shaikh
maria.sheikh@faculty.muet.edu.pk

Control Structures / Control Flow


Statements
Control
Structures /
Control Flow
Statements

Decision Making/
Conditional
Statements

Iterative Control
Structure/
Loops
Engr. Maria Shaikh

Branching
Statements

Control Structures / Control Flow


Statements (cont.)
One of the instructions, statements or groups of statements in a
programming language which determines the sequence of execution of
other instructions or statements (the control flow).
A programming language uses control statements to cause the flow of
execution to advance and branch based on changes to the state of a
program.
The statements inside your source files are generally executed from
top to bottom, in the order that they appear.
Control flow statements, however, break up the flow of execution by
employing decision making, looping, and branching, enabling your
program to conditionally execute particular blocks of code.
Engr. Maria Shaikh

Control Structures / Control Flow


Statements (cont.)
The decision-making statements (if-then, if-then else, switch),
the looping statements (for, while, do-while), and the
branching statements (break, continue, return) supported by
the Java programming language.
Statements that support repetition and conditional execution
are called control statements or control structures.

Engr. Maria Shaikh

Decision Making / Conditional Logic


Decision making structures have one or more conditions to be
evaluated or tested by the program, along with a statement or
statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.

Engr. Maria Shaikh

Conditional Logic - If Statements


Java if statement is used to execute some code, if a condition is true
otherwise if condition is false, execute nothing.
The if-then statement is the most basic of all the control flow statements.
It tells your program to execute a certain section of code only if a particular
test evaluates to true.

Syntax:
if(condition)
{
statement 1;
statement 2;
...
}

Engr. Maria Shaikh

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");
}
}
}

Engr. Maria Shaikh

Conditional Logic - If Statements (cont.)


If the user is not less than 18 then the code between the curly brackets will be
skipped, and the program continues on its way, downwards towards the last line of code.
Whatever you type between the curly brackets will only be executed IF the condition is
met, and this condition goes between the round brackets.
Exercise
Replace your "less than" symbol with the "less than or equal to" symbols. Change your
message to suit, something like "user is less than or equal to 18". Run your program
again. Do you see the message?
Exercise
Change the user value to 20. Run your program again. Do you still see the message?
Exercise:
Take the value at run time and see different effects?

Engr. Maria Shaikh

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");
}
}

Engr. Maria Shaikh

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;
}

Engr. Maria Shaikh

Operation of if-then-else Statement

Engr. Maria Shaikh

Implementation of if-then-else Statement


public class Sample {
public static void main(String args[]) {
int a = 80, b = 30;
if (b > a) {
System.out.println("b is greater");
}
else {
System.out.println("a is greater");
}
}
}

Engr. Maria Shaikh

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.

Engr. Maria Shaikh

IF ELSE IF Statement Syntax


if(condition)
{
Statements;
}
else if(condition n)
{
Statements;
}
else
{
Statements;
}

Engr. Maria Shaikh

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";
}

Engr. Maria Shaikh

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);
}
}

Engr. Maria Shaikh

The switch Case Statement


.A switch statement gives you the option to test for a range of values for
your variables. They can be used instead of long, complex if else if
statements.
A switch statement 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 body of a switch statement is known as a switch block. A statement
in
the
switch
block
can
be
labeled
with
one
or
more case or default labels. The switch statement evaluates its
expression, then executes all statements that follow the
matching case label.
Engr. Maria Shaikh

The switch Case Statement (cont.)


Deciding whether to use if-then-else statements or a switch statement
is based on readability and the expression that the statement is testing.
An if-then-else statement can test expressions based on ranges of
values or conditions, whereas a switch statement tests expressions
based only on a single integer, enumerated value, or String object.
Each break statement terminates the enclosing switch statement.
Control flow continues with the first statement following
the switchblock. The break statements are necessary because without
them, statements in switch blocks fall through: All statements after the
matching case label are executed in sequence, regardless of the
expression of subsequent case labels, until a break statement is
encountered.
Engr. Maria Shaikh

Rules apply to a Switch Case statement


The variable used in a switch statement can only be integers, convertable
integers (byte, short, char), strings and enums.
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.
Engr. Maria Shaikh

Rules apply to a Switch Case statement


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.

Engr. Maria Shaikh

Operation of Switch Case Statement

Engr. Maria Shaikh

Syntax
switch ( variable_to_test ) {
case value:
code_here;
break;
case value:
code_here;
break;
default:
values_not_caught_above;
}

Engr. Maria Shaikh

Implementation of Switch Case Statement


import java.util.Scanner;
public class SwitchDemo {
public static void main(String[] args) {
Scanner user_input = new Scanner( System.in );
int month;
System.out.print("Enter the month:");
month = user_input.nextInt();
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;

Engr. Maria Shaikh

Implementation of Switch Case Statement


case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
Engr. Maria Shaikh

Implementation of Switch Case Statement


case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
Engr. Maria Shaikh

Switch blocks fall through


Each break statement terminates the enclosing switch statement.
Control flow continues with the first statement following the switch
block.
The break statements are necessary because without them, statements
in switch blocks fall through: All statements after the matching case
label are executed in sequence, regardless of the expression of
subsequent case labels, until a break statement is encountered.
The program SwitchDemoFallThrough shows statements in a switch
block that fall through. The program displays the month corresponding
to the integer month and the months that follow in the year.
The java.util.ArrayList class provides resizable-array and implements
the List interface.
Engr. Maria Shaikh

Implementation of Switch blocks fall


through
import java.util.Scanner;
public class SwitchDemoFallThrough {
public static void main(String[] args) {
java.util.ArrayList<String> futureMonths = new java.util.ArrayList<String>();
Scanner user_input = new Scanner( System.in );
int month;
System.out.print("Enter the month:");
month = user_input.nextInt();

switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
Engr. Maria Shaikh

Implementation of Switch blocks fall


through
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;

Engr. Maria Shaikh

Implementation of Switch blocks fall


through
if (futureMonths.isEmpty()) {
System.out.println("Invalid month number");
}
else {
for (String monthName : futureMonths) {
System.out.println(monthName);
}
}
}
}
Engr. Maria Shaikh

Iterative Control Structures / Loops

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.

Engr. Maria Shaikh

Operation of Loops

Engr. Maria Shaikh

Loop Control Statements:


Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were created
in that scope are destroyed.
Control Statement

Syntax

Description

break statement

break;

Terminates the loop or switch statement and transfers


execution to the statement immediately following the
loop or switch.

continue statement

continue;

Causes the loop to skip the remainder of its body and


immediately retest its condition prior to reiterating.

goto statement

Its transfer current program execution sequence to


goto
labelName;labelName: some other part of the program.
Statement;

Engr. Maria Shaikh

Java For Loops


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.
The for statement provides a compact way to iterate over a
range of values. Programmers often refer to it as the "for
loop" because of the way in which it repeatedly loops until a
particular condition is satisfied.

Engr. Maria Shaikh

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

Flow of control in a for loop (cont.)


After the body of the for loop gets executed, the control
jumps back up to the update statement. This statement allows
you to update any loop control variables. This statement can
be left blank with a semicolon at the end.
The increment expression is invoked after each iteration
through the loop; it is perfectly acceptable for this
expression to increment or decrement a value. The Boolean
expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update
step, then Boolean expression). After the Boolean expression
is false, the for loop terminates.
Engr. Maria Shaikh

Operation of For Loop

Implementation of For Loop


import java.util.Scanner;
public class ForLoop {
public static void main(String[] args) {
int loopVal;
int end_value = 11;
int addition = 0;
int times_table = 0;
Scanner user_input = new Scanner(System.in);
System.out.println("Which times table do you want?");
times_table = user_input.nextInt();
Engr. Maria Shaikh

Implementation of For Loop


for (loopVal = 1; loopVal < end_value; loopVal++) {
addition = times_table * loopVal;
System.out.println( times_table + " * " + loopVal + " = " + addition);
}
}
}

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.

Engr. Maria Shaikh

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

Engr. Maria Shaikh

Implementation of While Loop


public class WhileLoop {
public static void main(String[] args) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
Engr. Maria Shaikh

Implementation of While Loop

Engr. Maria Shaikh

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.

Engr. Maria Shaikh

Syntax
do {
statement(s)
}
while (expression);

Engr. Maria Shaikh

Block Diagram of
Do / Do-While Loop

Engr. Maria Shaikh

Implementation of Do / Do-While Loop


public class DoWhile {
public static void main(String[] args) {
int n = 1, times = 0;
do {
System.out.println("Java do while loops:" + n);
n++;
} while (n <= times);
}
}

Engr. Maria Shaikh

Implementation of Do / Do-While Loop


public class DoWhoileLoop {
public static void main(String[] args) {
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Engr. Maria Shaikh

Enhanced for loop / for each loop in Java:


As of Java 5, the enhanced for loop was introduced. This is
mainly used to traverse collection of elements including
arrays.

Syntax:
for (declaration : expression)
{
//Statements
}

Engr. Maria Shaikh

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.

Engr. Maria Shaikh

Nested For Loop


We have all seen web page counters that resemble the one
shown below ( well, OK, maybe not quite this spastic!!). Your
car's odometer works in a similar manner.
This counter (if it worked properly) and your car's odometer
are little more than seven or eight nested for loops, each
going from 0 to 9. The far-right number iterates the fastest,
visibly moving from 0 to 9 as you drive your car or increasing
by one as people visit a web site.
Engr. Maria Shaikh

Syntax

Engr. Maria Shaikh

Implementation of Nested For Loop


public class NestedFor {
public static void main(String[] args) {
for (int i=1; i<=9; i++) {
System.out.println();
for (int j=9; j>=i; j--) {
System.out.print(" "); }
for (int k=1; k<=i; k++) {
System.out.print("*"); }
}
System.out.println();
}
Engr. Maria Shaikh
}

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

Implementation of Unlabelled Break


Statement
This program searches for the number 12 in an array. The break
statement, shown in boldface, terminates the for loop when that
value is found. Control flow then transfers to the statement after
the for loop.
public class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
Engr. Maria Shaikh

Implementation of Unlabelled Break


Statement
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;}
} if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
Engr. Maria Shaikh

Implementation of labelled Break


Statement
public class BreakWithLabel {
public static void main(String[] args) {
int[ ] [ ] arrayOfInts = {
{ 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;

Engr. Maria Shaikh

Implementation of labelled Break


Statement (cont.)
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
Engr. Maria Shaikh

Implementation of labelled Break


Statement (cont.)
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}

Engr. Maria Shaikh

The continue Statement


The continue statement skips the current iteration of a for,
while , or do-while loop.
The unlabelled form skips to the end of the innermost loop's
body and evaluates the boolean expression that controls the
loop.
The following program, ContinueDemo , steps through a String,
counting the occurences of the letter "p". If the current
character is not a p, the continue statement skips the rest of
the loop and proceeds to the next character. If it is a "p", the
program increments the letter count.
Engr. Maria Shaikh

Implementation of Unlabelled continue


Statement
public class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
// process p's
numPs++;
Engr. Maria Shaikh

Implementation of Unlabelled continue


Statement (cont.)
}
System.out.println("Found " + numPs + " p's in the string.");
}
}

Engr. Maria Shaikh

Implementation of labelled continue


Statement
public class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
Engr. Maria Shaikh

Implementation of labelled continue


Statement (cont.)
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
Engr. Maria Shaikh
}

goto Statement in Java


Java doesn't support goto (it's reserved as a keyword, but it
doesn't do anything, so you can't use it).
break can only be used inside loops and it's used to break out
of the loop marked by the given label - not to jump to the
label.
There's no way in Java to jump to a given label like you would
with goto in a language that supported it. You should
restructure your code to use loops.
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

Engr. Maria Shaikh

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.

Disadvantage of Java Array:


Size Limit: We can store only fixed size of elements in the
array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in java.
Engr. Maria Shaikh

Declaring a Variable to Refer to an Array


The preceding program declares an array (named anArray) with the following line of
code:
// declares an array of integers

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

Declaring a Variable to Refer to an Array

Similarly, you can declare arrays of other types:


byte [ ] anArrayOfBytes;
short [ ] anArrayOfShorts;
long [ ] anArrayOfLongs;
float [ ] anArrayOfFloats;
double [ ] anArrayOfDoubles;
boolean [ ] anArrayOfBooleans;
char [ ] anArrayOfChars;
String [ ] anArrayOfStrings;
Engr. Maria Shaikh

Declaring a Variable to Refer to an Array


You can also place the brackets after the array's name:
// this form is discouraged

float anArrayOfFloats [ ];
However, convention discourages this form; the brackets identify
the array type and should appear with the type designation.

Engr. Maria Shaikh

Creating, Initializing, and Accessing an


Array
One way to create an array is with the new operator. The next
statement in the ArrayDemo program allocates an array with
enough memory for 10 integer elements and assigns the array
to the anArray variable.
// create an array of integers
anArray = new int [10];
If this statement is missing, then the compiler prints an error like
the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been
initialized.
Engr. Maria Shaikh

Creating, Initializing, and Accessing an


Array

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.

Engr. Maria Shaikh

Types of Array in java


There are two types of array.
Single Dimensional Array
Multidimensional Array

Engr. Maria Shaikh

Single Dimensional Array in java


A one-dimensional array (or single dimension array) is a type of linear
array. Accessing its elements involves a single subscript which can either
represent a row or column index. As an example consider the C
declaration int anArrayName[10];

Syntax to Declare an Array in java


dataType[ ] arr; (or)
dataType [ ]arr; (or)
dataType arr[ ];

Instantiation of an Array in java


arrayRefVar=new datatype[size];
Engr. Maria Shaikh

Implementation of Single Dimensional


Array using println
public class Array {
public static void main(String[] args) {
int[ ] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
Engr. Maria Shaikh

Implementation of Single Dimensional


Array using println
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index 0: + anArray[0]);
System.out.println("Element at index 1: + anArray[1]);
System.out.println("Element at index 2: + anArray[2]);
System.out.println("Element at index 3: + anArray[3]);
Engr. Maria Shaikh

Implementation of Single Dimensional


Array using println
System.out.println("Element at index 4: + anArray[4]);
System.out.println("Element at index 5: " + anArray[5]);
System.out.println("Element at index 6: + anArray[6]);
System.out.println("Element at index 7: "+ anArray[7]);
System.out.println("Element at index 8: + anArray[8]);
System.out.println("Element at index 9: + anArray[9]);
}
}

Engr. Maria Shaikh

Implementation of Single Dimensional


Array using println

Engr. Maria Shaikh

Implementation of Single Dimensional


Array using for loop
public class Array {
public static void main(String[] args) {
int[ ] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
Engr. Maria Shaikh

Implementation of Single Dimensional


Array using for loop
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
for (int i=0;i<anArray.length;i++)
System.out.println("Element at index:"+anArray[i]);
}
}
Engr. Maria Shaikh

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.

Engr. Maria Shaikh

Multidimensional Array
Syntax to Declare Multidimensional Array in java

dataType[ ][ ] arrayRefVar; (or)


dataType [ ][ ]arrayRefVar; (or)
dataType arrayRefVar[ ][ ]; (or)
dataType [ ]arrayRefVar[ ];

Example to instantiate Multidimensional Array in java


int[ ][ ] arr=new int[3][3];

//3 row and 3 column

Engr. Maria Shaikh

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

Implementation of Multi Dimensional


Array using for each loop
public class MultidimensionalArray {
public static void main(String[] args) {
int arr[ ][ ]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int[ ] list : arr) {
for (int list2 : list) {
System.out.print(list2 + ");
}
System.out.println(); }
}
}
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.

Engr. Maria Shaikh

Copy of Range Method:


Declaration:
Following is the declaration for java.util.Arrays.copyOfRange() method

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

Copy of Range Method:


Exception:
ArrayIndexOutOfBoundsException -- If from < 0 or from >
original.length()
IllegalArgumentException -- If from > to.
NullPointerException -- If original is null.

Engr. Maria Shaikh

Implementation of Copy of Range Method:


import java.util.Arrays;
public class CopyArray {
public static void main(String[] args) {
int[ ] arr1 = new int[ ] {15, 10, 45,60, 34, 80, 21};
// printing the array
System.out.println("Printing 1st array:");
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}
// copying array arr1 to arr2 with range of index from 1 to 3
int[ ] arr2 = Arrays.copyOfRange(arr1, 1, 5);
Engr. Maria Shaikh

Implementation of Copy of Range Method:


// printing the array arr2
System.out.println("Printing new array:");
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]);
}
}
}

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

public static void sort(int[ ] a)


Parameters:
a -- This is the array to be sorted.
Return Value:
This method does not return any value.
Engr. Maria Shaikh

Implementation of Sorting an Arrays


import java.util.Arrays;
public class SortingArrays {
public static void main(String[] args) {
// initializing unsorted int array
int iArr[] = {2, 1, 9, 6, 4};
// let us print all the elements available in list
for (int number : iArr) {
System.out.println("Number = " + number);
}
// sorting array
Arrays.sort(iArr);
Engr. Maria Shaikh

Implementation of Sorting an Arrays


// let us print all the elements available in list
System.out.println("The sorted int array is:");
for (int number : iArr) {
System.out.println("Number = " + number);
}
}
}

Engr. Maria Shaikh

Array Lists in Java


If you don't know how many items are going to be held in your array, you
may be better off using something called an ArrayList. An ArrayList is a
dynamic data structure, meaning items can be added and removed from
the list. A normal array in java is a static data structure, because you
stuck with the initial size of your array.
To set up an ArrayList, you first have to import the package from
the java.util library:
import java.util.ArrayList;
You can then create a new ArrayList object:
ArrayList listTest = new ArrayList( );

Engr. Maria Shaikh

Array Lists in Java


Once you have a new ArrayList objects, you can add elements to it with the
add method:
listTest.add( "first item" );
listTest.add( "second item" );
listTest.add( "third item" );
listTest.add( 7 );
Items in the list can be referenced by an Index number, and by using the
get method:
listTest.get( 3 )
Or you can use the value on the list:
listTest.remove( "second item" );
Engr. Maria Shaikh

Array Lists in Java


You can also remove items from an ArrayList. You can either use the Index
number:
listTest.remove(2);
Removing an item will resize the ArrayList, so you have to be careful when
trying to get an item on the list when using its Index number. If we've
removed item number 2, then our list above will contain only 3 items. Trying
to get the item with the Index number 3 would then result in an error.
To go through each item in your ArrayList you can set up something called
an Iterator. This class can also be found in the java.util library:
import java.util.Iterator;
You can then attach your ArrayList to a new Iterator object:
Iterator it = listTest.iterator( );
Engr. Maria Shaikh

Array Lists in Java


This sets up a new Iterator object called it that can be used to go
through the items in the ArrayList called listTest. The reason for using
an Iterator object is because it has methods called next and hasNext.
It can be used in a loop:
while ( it.hasNext( ) ) {
System.out.println( it.next( ) );
}
The method hasNext returns a Boolean value. The value will be false if
there are no more items in the ArrayList. The next method can be used
to go through all the items in the list.

Engr. Maria Shaikh

Implementation of Array Lists in Java


import java.util.ArrayList;
import java.util.Iterator;
public class ArrayLists {
public static void main(String[] args) {
ArrayList listTest = new ArrayList( );
listTest.add( "first item" );
listTest.add( "second item" );
listTest.add( "third item" );
listTest.add( 7 );
Iterator it = listTest.iterator( );
Engr. Maria Shaikh

Implementation of Array Lists in Java


while ( it.hasNext( ) ) {
System.out.println( it.next( ) );
}
listTest.remove(1);
System.out.println( "Whole list=" + listTest );
System.out.println("Position 1="+listTest.get( 1));
}
}

Engr. Maria Shaikh

END OF SLIDE
Engr. Maria Shaikh

You might also like