Week3 L2 Conditionals
Week3 L2 Conditionals
Example:
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if (x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Syntax: We use this form when we
want to execute a code
if ( <condition> ) {
block when a condition is
<statement1>;
true, and execute another
}
code block if it is false.
else {
<statement2>;
}
Example:
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Syntax:
if( <condition1> ) {
<statement1>; We use this form when we
} have multiple conditions and
else if( <condition2> ) { multiple code blocks to
<statement2>;
} execute when each of these
else { conditions is true.
<statement3>;
}
Example:
public class Student {
public static void main(String[] args) {
String city = “Unknown";
if(city == “Cairo") {
System.out.println("city is Cairo");
}else if (city == “Aswan") {
System.out.println("city is Aswan");
}else if(city == “Alexandria") {
System.out.println("city is Alexandria");
}else {
System.out.println(city);
}
}
}
Syntax:
if(<condition1>) { Nested conditions implement
<statement1>; logical AND of multiple
if(<condition 2>) { conditions
<statement 2>;
}
else {
statement 2;
}
}
public class Student {
public static void main(String[] args) {
String address = “12";
if(address.endsWith(“2")) {
if(address.contains(“1")) {
System.out.println(“String is 12");
}else {
System.out.println(“String ends with 2");
}
}
}
}
Switch statement is an easy way to
implement multiple if statements.
The case variables can be int, short, byte,
char, or enumeration. String type is also
supported since version 7 of Java
Cases cannot be duplicate.
Break statement terminates the switch
block when the condition is satisfied.
It is optional, if not used, next case is
executed.
Syntax:
switch (<expression>){
case <value 1>:
<statement1>;
break;
.
.
.
case <value N>:
<statement>;
break;
default:
<default statement>;
}
public class Student {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Translate each of the examples mentioned
in this lecture into flowcharts.
Translate all examples and exercises that
you have taken in sections into Java code.