Lec 2 Fundamentals Feb 23
Lec 2 Fundamentals Feb 23
CS212-Object Oriented
Programming
Lecture 2
Java Language Fundamentals
(Feb 2023)
Instructor: Lt Col Muhammad Imran Javaid
Email: [email protected]
• The if statement with a companion else statement executes the first block if
the boolean expression is true; otherwise, it executes the second block:
if(boolean expression) {
statement(s)
} else {
statement(s)
}
3
If-else Statement
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int time;
System.out.print("Enter present hour (0-23): ");
time = input.nextInt();
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
4 }
If-else Statement
• We can use else if to construct compound if statements:
if (boolean expression) {
statement(s)
} else if (boolean expression) {
statement(s)
} else if (boolean expression) {
statement(s)
} else {
statement(s)
}
5
If-else Statement
import java.util.Scanner;
public class CompoundIfElseDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double percent;
char grade;
System.out.print("Enter Percentage: ");
percent = input.nextDouble();
if (percent < 0.0 || percent > 100.0) {
System.out.println("Incorrect Percentage!");
return;
} else if (percent >= 90.0) { grade = 'A';
} else if (percent >= 80.0) { grade = 'B';
} else if (percent >= 70.0) { grade = 'C';
} else if (percent >= 60.0) { grade = 'D';
} else if (percent >= 50.0) { grade = 'E';
} else { grade = 'F'; }
System.out.printf("Grade: %c\n", grade);
}
6 }
Conditional Operator
Operator Symbol Form Operation
If c is true then evaluate x,
Conditional ?: c ? x : y
otherwise evaluate y
import java.util.Scanner;
public class ConditionalOperatorDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x, y, max;
System.out.print("Enter X: ");
x = input.nextInt();
System.out.print("Enter Y: ");
y = input.nextInt();
max = (x > y) ? x : y;
System.out.printf("Max: %d\n", max);
}
7 }
Switch Statement
• Nesting many if-then-else can be complicated
• For cases where we make decisions based on the values of char , integer type,
or String , we can use the switch-case statement
• The switch statement can have a number of possible execution paths.
• A switch works with the byte, short, char, and int primitive data types. It
also works with enumerated types, the String class, and a few special classes
that wrap certain primitive types: Character, Byte, Short, and Integer.
• 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 once, value of the expression
is compared with the values of each case.
– If there is a match, the associated block of code is executed. then executes all
8
statements that follow the matching case label.
Switch Statement
• Break basically means “we are finished with this switch , jump to the end of
it (and then execute the next instruction, if any)”
• 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 default section handles all values that are not explicitly handled by one
of the case sections. switch (expression) {
case label:
statement(s)
break;
...
default:
statement(s)
break;
9 }
Switch Statement
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break; case 7:
case 4: System.out.println("Sunday");
System.out.println("Thursday"); break;
break; default:
case 5: System.out.println("Invalid Day");
System.out.println("Friday"); break;
break;
case 6:
System.out.println("Saturday"); }
break; }
}
10
Switch Statement
import java.util.Scanner;
public class SwitchIntDemo {
static final Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int choice; String selection;
System.out.println("1. Black");
System.out.println("2. White");
System.out.println("3. Red");
System.out.println("4. Green");
System.out.println("5. Blue");
System.out.print("Select a Color (1-5): ");
choice = input.nextInt();
switch(choice) {
case 1: selection = "Black"; break;
case 2: selection = "White"; break;
case 3: selection = "Red"; break;
case 4: selection = "Green"; break;
case 5: selection = "Blue"; break;
default: selection = "Invalid";
}
System.out.printf("Your selection is %s.\n", selection);
}
11 }
Switch Statement
import java.util.Scanner;
import java.io.PrintStream;
public class SwitchCharDemo {
static final PrintStream out = System.out;
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
out.println("Which is the capital city of Pakistan?");
out.println("A. Islamabad\nB. Karachi");
out.println("C. Lahore\nD. Peshawar");
out.print("E. Quetta\nYour choice (Select from A to E): ");
char choice = in.next().charAt(0);
switch(choice) {
case 'A': case 'a':
out.println("Correct Answer!"); break;
case 'B': case 'C': case 'D': case 'E':
case 'b': case 'c': case 'd': case 'e':
out.println("Incorrect Answer!"); break;
default: out.println("Invalid Answer!");
}
}
12 }
Loops
While Statement
• Sometimes, we need to carry out the same command again and again in a program.
• Instead of copying the same code multiple times, we may wrap it into a loop.
• Use the while statement to loop over a block of statements while a boolean
expression remains true.
• The expression is evaluated at the top of the loop:
while (boolean expression) {
statement(s)
}
• Example: public class WhileDemo {
public static void main(String[] args) {
int count = 1;
while (count <= 10) {
System.out.printf("%d ", count++);
}
System.out.println("done!");
}
13 }
Example: Compute GCD
import java.util.Scanner;
public class WhileGcdDemo {
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter A: ");
int a = Math.abs(in.nextInt());
System.out.print("Enter B: ");
int b = Math.abs(in.nextInt());
while (b != 0) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
System.out.printf("GCD: %d\n", a);
}
14 }
Nested While Loops
public class NestedWhileDemo {
public static void main(String[] args) {
int outer = 1;
while (outer <= 5) { // 1...5
int inner = 1;
while (inner <= outer) { // 1...outer
System.out.printf("%d ", inner++);
}
// print newline after each row
System.out.println();
++outer;
}
}
15 }
do-While Statement
• Use the do-while statement to loop over a block of
statements while a boolean expression remains true.
• The expression is evaluated at the bottom of the loop,
so the statements within the do-while block execute at
least once:
do {
statement(s)
} while (expression);
16
do-While Statement
import java.util.Scanner;
import java.io.PrintStream;
public class DoWhileDemo {
static final PrintStream out = System.out;
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int answer;
out.println("Capital city of Pakistan?");
out.println("1. Islamabad\n2. Karachi");
out.println("3. Lahore\n4. Peshawar");
out.println("5. Quetta");
do {
out.print("Your choice: ");
answer = in.nextInt();
} while (answer < 1 || answer > 5);
out.printf("%s Answer!\n",
answer == 1 ? "Correct" : "Incorrect");
}
17 }
for Statement
• The for statement loops over a block of statements and includes an initialization
expression, a termination condition expression, and an increment expression:
for (initialization ; termination ; increment)
{
statement(s)
}
• The initialization expression initializes the loop; it is executed once, as the loop
begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
18
for Statement
import java.util.Scanner;
import java.io.PrintStream;
public class FactorialDemo {
static final PrintStream out = System.out;
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
long factorial = 1;
out.print("Enter the number: ");
int number = in.nextInt();
for (int i = 2; i <= number; i++) {
factorial *= i;
}
out.printf("Factorial: %,d\n", factorial);
}
}
19
Prime Factors
import java.util.Scanner;
import java.io.PrintStream;
public class PrimeFactorsDemo {
static final PrintStream out = System.out;
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
out.print("Enter the number: ");
int n = in.nextInt();
out.printf("Prime Factors: %,d = ", n);
while (n > 2 && (n % 2) == 0) {
out.printf("%d x ", 2);
n /= 2;
}
for (int i = 3; i < (Math.sqrt(n) + 1); i += 2) {
while (n > i && (n % i) == 0) {
out.printf("%,d x ", i);
n /= i;
}
}
out.printf("%,d\n", n);
}
20 }
for Statement
• The for statement also has another form designed for iteration
through Collections and arrays.
• This form is sometimes referred to as the enhanced for statement, and can be used
to make your loops more compact and easy to read. For example:
21
break Statement
• The break statement has two forms: unlabeled and labeled.
• We used the unlabeled break in the previous slides of the switch statement. We can also
use an unlabeled break to terminate a for, while, or do-while loop. For example:-
public class DoWhileBreakDemo {
static final PrintStream out = System.out;
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int value, count = 0, sum = 0;
do {
out.print("Enter value to add 0 to exit: ");
value = in.nextInt();
if (value == 0) { break; }
count++;
sum += value;
} while (true);
out.printf("Sum of %d values: %,d\n", count,
sum);
22
}
}
break Statement
import java.util.Scanner;
import java.io.PrintStream;
public class ForBreakDemo {
static final PrintStream out = System.out;
static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int value, count, sum = 0;
for (count = 0; count < 10; count++) {
out.print("Enter value to add 0 to exit: ");
value = in.nextInt();
if (value == 0) { break; }
sum += value;
}
out.printf("Sum of %d values: %,d\n", count, sum);
}
23 }
break Statement
• An unlabeled break statement terminates the innermost switch,
for, while, or do-while statement, but a labeled break terminates
an outer statement.
• The break statement terminates the labeled statement; it does not
transfer the flow of control to the label.
• Control flow is transferred to the statement immediately following the
labeled (terminated) statement.
24
break Statement
public class FindDuplicateDemo {
public static void main(String[] args) {
int[] values = { 10, 12, 9, 28, 5, 14, 5, 11, 9, 17 };
int i, j = -1;
boolean found = false;
outter:
for (i = 0; i < (values.length - 1); i++) {
for (j = i + 1; j < values.length; j++) {
if (values[i] == values[j]) {
found = true;
break outter;
}
}
}
if (found) {
System.out.print("Duplicate found at Indices: ");
System.out.printf("%d and %d\n", i, j);
} else {
System.out.println("No Duplicate Found!");
}
}
25 }
continue Statement
• The continue statement skips the current iteration of a for, while , or do-while loop.
• The unlabeled form skips to the end of the innermost loop's body and evaluates
the boolean expression that controls the loop.
• A labeled continue statement skips the current iteration of an outer loop marked with the
given label.
26
continue Statement
public class PrimeNumbersDemo {
public static void main(String[] args) {
skip:
for (int i = 0; i < 100; i++) {
if (i < 2 || (i > 2 && (i % 2) == 0)) {
continue;
}
for(int j = 3; j < (Math.sqrt(i) + 1); j += 2) {
if ((i % j) == 0) {
continue skip;
}
}
System.out.printf("%d, ", i);
}
System.out.println("\b\b ");
}
27 }
Copyright Notice
28