OOP Lecture 03
OOP Lecture 03
Programming-Java
Control structure,
Arrays and Strings
1
Control Structure:
Sequence
Program executes sequentially line by line without
skipping starting from the top.
e.g
public class A{
public static void main(String[] args){
int x;
x = 5;
int y;
y=12;
int z;
z = x + y;
System.out.println(x);
System.out.println(y);
System.out.println(z);
2
}
}
Control Structure:
Single Selection(if statement)
syntax
If (conditional expression)
{
Statement;
}
e.g
import java.util. Scanner;
public class A{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
System.out.println(“Enter marks”);
int n = x.nextInt();
if(n>= 40){
System.out.print(“PASS”);
}
3
}
}
Control Structure:
double Selection (if-else
statement)
To selectively execute statements depending
on some criteria
if(conditional expression) {
statement(s)
} else {
statement(s)
}
4
Control Structure:
double Selection (if-else statem)
e.g.
import java.util. Scanner;
public class A{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
System.out.println(“Enter marks”);
int n = x.nextInt();
if(n>= 40){
System.out.println(“PASS”);
}
else
System.out.print(“FAIL”);
}
}
5
Control Structure:
double Selection(if-else stat)
Exercise
Write a program to calculate the grade of a
student given the average
Marks < 0 or Marks > 100 give Error Message
0 <= Marks < 40 – Grade = C
40 <= Marks < 70 – Grade = B
70 <= Marks <= 100 – Grade = A
6
Control Structure:
double selection(if-else stat)
Class Grade {
public static void main (String[] args){
int mark = 75;
if ( (mark<0) or (mark>100) ) {
System.out.println(‘Error’);
} else if (mark<40) {
System.out.println(‘C’);
} else if (mark<70) {
System.out.println(‘B’);
} else {
System.out.println(‘A’);
}
}
} 7
Control Structure:
multiple selection(switch stat)
Evaluatesa variable and executes
statements according to it’s value
switch (variable) {
case value1: statement(s);
break;
case valueN: statement(s);
break;
case default: statement(s);
break;
8
}
Control Structure:
multiple selection(switch stat)
Eg.
switch (day) {
case 1: System.out.println(“Sunday”); break;
case 2: System.out.println(“Monday”); break;
case 3: System.out.println(“Tuesday”); break;
case 4: System.out.println(“Wednesday”);
break;
case 5: System.out.println(“Thursday”); break;
case 6: System.out.println(“Friday”); break;
case 7: System.out.println(“Saturday”); break;
9
}
Control Structure:
multiple selection(switch stat)
e.g.
public class MyClass {
}
Control Structure:
multiple selection(switch stat)
Write a method to output the following
Grade = A – ‘Very Good’
Grade = B – ‘Good’
Grade = C – ‘Bad’
for(initialization; termination;
increment) { statement(s)
}
Eg
for (int i=0; i<5; i++) {
System.out.println(“Iteration “ + i);
} 12
Control Structure:
repetition (For Statement)
Write a method to calculate the factorial of a given
integer
14
Control Structure:
repetition (While Statement)
Eg.
int x=0;
while (x<5) {
System.out.println(“Iteration ” + x);
x++;
}
15
Control Structure:
repetition (While Statement)
Eg.
publicclassMyClass {
while(x<= 10)
{
System.out.println(x);
x++;
}
}
16
}
Control Structure:
repetition (do-While Statement)
do{
statement(s)
} while (conditional expression);
17
Control Structure:
repetition (do-While Statement)
int x=0;
do {
System.out.println(“Iteration ” + x);
x++;
} while (x<5);
18
Control Structure:
Iterations
It will be covered in Methods
19
Exercise
20
Branching Statements
break
Used to terminate a switch statement or a loop
Eg.
public class A{
public static void main(String[] args){
int x=0;
while (true) {
System.out.println(“Iteration” + x);
x++;
if (x==5) {
break;
} //end if
} //end while
} //end main
} //end class 21
Branching Statements
continue
Used to skip a part of an iteration in a loop
Eg.
public class A{
public static void main(String[] args){
int x=0;
while (x<5) {
x++;
if (x==2) {
continue;
} //end if
System.out.println(“Iteration ” + x);
} //end while
} //end main 22
} //end class
Branching Statements
return
Used to come out of a method
Eg.
public void method1() {
System.out.println(“Method 1”);
return;
}
public int method2() {
System.out.println(“Method 2”);
return 1;
}
23
Nesting
Task
Find out about nested Selection Statements and
nested loops
24
Arrays-Single Dimensional
A structure that holds multiple values of the
same type
Single dimensional array has one row and n-
number of columns
The length of an array is established when
25
Arrays-Single Dimensional
Array is declared and created
Array is a no-primitive or reference data type
The following declaration and array-creation expression
create an array object containing 12 int elements and store
the array’s reference in variable c, that reference point to 0
index of that array.
int c[] = new int[ 12 ];
Other ways of declaring and creating an array
double[] array1, array2;// declaration
int[] arr = {13,10,11,21,16};
int[] arr = new int[5];
int[] arr = new int[]{13,10,11,21,16};
int arr[] = {13,10,11,21,16};
After creation receives a default value depending on 26
//you can also use enhanced for loop i.e for(int elem:anArray)
Arrays-Single Dimentional
public class MyClass{
public static void main(String args[]){
int[] arr = {13,10,11,21,16};
int index = 0;
//System.out.println(arr[index]);
while(index< 5) {
System.out.println(arr[index]);
index++;
}
}
} 29
Arrays-Single Dimentional
Array Initializing
boolean[] answers = { true, false, true, true, false };
Arrays of Objects
String[] anArray = { "One", "Two", "Three" };
MyClass[] mcArray = new MyClass[5]; // No
Items
30
Arrays-Two Dimensional
Arraysof Arrays, an array with multiple rows
and columns
or 2D Arrays can be defined
String[][] 2DArray = new String[3][4];
31
Arrays-Two Dimensional
int b[][]= { { 1, 2 }, { 3, 4 } };
nested arrays form rows
Number of elements in nested arrays form columns
So 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ],
respectively, and 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ]
[ 1 ], respectively.
int b[][] = new int[ 3 ][ 4 ];
3 specifies number of rows
4 specifies number of columns
32
Arrays-Two Dimensional
e.g
Import java.util.Scanner;
public class Array{
public static void main( String args[] ){
int arr[][] = new int[3][4];
Scanner input = new Scanner(System.in);
for(int row=0; row <arr.length; row++){
for(int col=0; col <arr[row].length; col++){
System.out.print("Enter an interger");
arr[row][col] = input.nextInt();
}
}
for(int row=0; row <arr.length; row++){
for(int col=0; col <arr[row].length; col++){
System.out.print(arr[row][col] );
} 33
System.out.print("\n");}}}
Exercise
Using
single dimensional array and two
dimensional do the following tasks:
Create and array of 100 integer elements
Perform summation of all elements
Perform average
Perform sorting of elements in ascending order
Perform sorting of elements in discending order
34
Strings
Next to numbers, strings are the most important
data type that most programs use
A string is a sequence of characters, e.g., “Hello”
In Java strings are enclosed in quotation marks,
which are not themselves part of the string
You can declare variables that hold strings
String name = “John”
Use assignment to place a different string into the
variable
name = “Godfrey”
35
String variables
Next to numbers, strings are the most important
data type that most programs use
A string is a sequence of characters, e.g., “Hello”
In Java strings are enclosed in quotation marks,
which are not themselves part of the string
You can declare variables that hold strings
String name = “John”
Use assignment to place a different string into the
variable
name = “Godfrey”
36
String Data Type
The number of characters in a string is called the length of
the string
E.g., the length of “Hello, World” is 13.
Compute the length of the string with the length method
int n = name.length();
Unlike numbers, strings are objects.
See that String is a class because it starts with an
uppercase letter
The basic data types int and double start with a
lowercase letter
Thus, can call methods on strings, e.g., name.length()
37
Substrings
Can extract substrings, and can glue smaller strings together to
forma larger ones
To extract substring, use the substring method:
s.substring(start, pastEnd)
Returns a string that is made up from the characters in the string s,
starting at character start, and containing all characters up to, but
not including, the character pastEnd.
E.g.,
String greeting = “Hello, World!”;
String sub = greetings.substring(0,4); //sub is “Hell”
H e l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
38
Substrings
The position number of the last character (12 for the
string “Hello, World!”) is 1 less than the length of the
string
E.g., to extract the substring “World”, count characters
starting at 0, not 1.
Find that W, the 8th character, has position number 7.
character at position 12
The appropriate substring command is:
String w = greeting.substring(7,12);
He l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12 39
Substrings
Must specify the position of the first character that you do want
and then the first character that you don’t want
One advantage to this setup is, can easily compute the length of
the substring: pastEnd - start
If you omit the second parameter of the substring method, then all
characters from the starting position to the end of the string are
copied
E.g.,
String tail = greeting.substring(7); //tail is “World!”
Equivalent to
String tail = greeting.substring(7, greeting.length());
40
Concatenation
Given two strings, such as “Snuffer” and “Dog-Dog”, you
can concatenate them to one long string:
String fname = “Snuffer”;
String lname = “Dog-Dog”;
String name = fname + lname;
The + operator concatenates two strings
The resulting string is “SnufferDog-Dog”
We would-like the first and last name separated by a
space.
String name = fname + “ “ + lname;
Now we’ve concatenated three strings: “Snuffer”, “ “, and
“Dog-Dog”.
The result is “Snuffer Dog-Dog” 41
Concatenation
If one of the expressions, either to the left or the right of a +
operator, is a string, then the other one is automatically
forced to become a string as well, and both strings are
concatenated
E.g.,
String a = “Agent”;
int n = 7;
String bond = a + n;
Since a is a string, n is converted from the integer 7 to the
string “7”.
The two strings “Agent” and “7” are concatenated to form
the string “Agent7”
42
Concatenation
Can reduce the number of System.out.print
instructions
E.g.
System.out.print(“The total is”);
System.out.println(total);
To the single call
System.out.println(“The total is “ + total);
The concatenation “The total is “ + total computes a
single string that consists of the string “The total is “,
followed by the string equivalent of the number total.
43
toUpperCase, toLowerCase
The toUpperCase and toLowerCase methods make strings
with only upper- or lowercase characters.
String greeting = “Hello”;
System.out.println(greetings.toUpperCase() + “ “ +
greetings.toLowerCase());
Display HELLO hello
The toUpperCase and toLowerCase do not change the original
String object greeting.
They return new String objects that contain the uppercased and
lowercased versions of the original string
No String methods modify the string object on which they
operate – called mutable objects.
44
Converting between Numbers
and Strings
In general to convert a numbe to a string, yo can
conactenate with the empty string:
int age = 19;
String ageString = “” + age;
Some programmers prefer to use the toString
methods of the Integer and Double classes,
because it is more explicit:
String ageString = Integer.toString(age);
45
Converting between Numbers
and Strings
To convert a string containing just digits to its integer value
use the static parseInt method of the Integer class.
String password = “hjh19”
String ageString = password.substring(3);
int age = ageString; // ERROR
int age = Integer.parseInt(ageString); // age is the
number 19
To convert a string containing floating-point digits to its
floating-point value, use the static parseDouble method of
the Double class.
46
Converting between Numbers
and Strings
String priceString = “$3.95”;
double price =
Double.parseDouble(priceString.substring(1));
// sip “$” and convert to a number
The parseInteger and parseDouble methods are
useful for processing input
47
publicclassMyClass{
publicstaticvoid main(String args[]){
String myString = "Hallow Java";
//Concatenation
String s = “s”;
String t = “top”;
String p = “s + t”;
int n = 1;
String x = “1”;
Int m = n+ n; ->2
String g = x+x; ->”11”
String f = n+s; ->”11”
String s = “”;//empty string,leght 0
String s = “ ”;//space character, legth 1
String j = “halloo”;
String r = j.substring(2,4);->”ll”
String r = j.substring(0,2);->”He”
String r = j.substring(2);->”llo!”
System.out.println(myString);
intmyStringLength = myString.length();
System.out.println(myStringLength);
String myStringLowCase = myString.toLowerCase();
System.out.println(myStringLowCase);
String myStringUpCase = myString.toUpperCase();
System.out.println(myStringUpCase);
String myStringReplacedA = myString.replace('a','e');
System.out.println(myStringReplacedA); 48
intmyStringIndices = myString.indexOf('J');