Week3 CM MDL CP1212
Week3 CM MDL CP1212
Week 3
UNIT 1: Demonstrate using Operators and Decision Construct in Accordance with Java
Framework
Most Essential Learning Competencies: At the end of the course, you must be able to:
1. Discuss the different types of operators in Java
2. Demonstrate Java conditional statements such as If, If-Else, Nested If-Else, Switch and
Break Statements and its syntax
Introduction
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Checks if the value of left operand is less than the value of (A < B) is
< (less than)
right operand, if yes then condition becomes true. true.
& (bitwise Binary AND Operator copies a bit to the (A & B) will give 12 which is
and) result if it exists in both operands. 0000 1100
^ (bitwise Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
XOR) set in one operand but not both. 0011 0001
C <<= 2 is
<<= Left shift AND assignment operator. same as C
= C << 2
C >>= 2 is
>>= Right shift AND assignment operator. same as C
= C >> 2
C &= 2 is
&= Bitwise AND assignment operator. same as C
=C&2
Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should
be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true : value if false
Example
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}
This will produce the following result −
Output
Value of b is : 30
Value of b is : 20
instanceof Operator
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type (class type or interface type). Instance of operator is written as −
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is an example −
Example
public classTest{
class Vehicle{}
Vehicle a = newCar();
boolean result = a instanceof Car;
System.out.println( result);
}
}
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Use if statement to specify a block of Java code to be executed if a condition is true.
Figure 3.1
if(condition){
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is true,
print some text:
Example
If (20>18){
Java Code
Example
int x =20;
int y =18;
if (x > y){
System.out.println("x is greater than y");
}
Example Explained
In the example above we use two variables, x and y, to test whether x is greater than y (using
the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen
that "x is greater than y".
Use the else statement to specify a block of code to be executed if the condition is false.
Figure 3.2
Syntax
if(condition){
// block of code to be executed if the condition is true
}else{
// block of code to be executed if the condition is false
}
Example
int time =20;
if (time <18){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Java Code
public class MyClass{
public static void main(String[]args){
int time =20;
if (time <18){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
Output:
Good evening.
Example Explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on
to the else condition and print to the screen "Good evening". If the time was less than 18, the program
would print "Good day".
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if(condition1){
}else if(condition2){
}else{
Example
int time =22;
if (time <10){
System.out.println("Good morning.");
} else if (time <20){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Java Code:
public class MyClass{
public static void main(String[]args){
int time =22;
if (time <10){
System.out.println("Good morning.");
} else if (time <20){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
Output:
Good evening
In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in
the else if statement, is also false, so we move on to the else condition
since condition1 and condition2 is both false - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
There is also a short-hand if else, which is known as the ternary operator because it consists of three
operands. It can be used to replace multiple lines of code with a single line. It is often used to replace
simple if else statements:
Syntax
variable=(condition)?expressionTrue:expressionFalse;
Instead of writing:
Example
int time =20;
if (time <18){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
Java Code:
public class MyClass{
public static void main(String[]args){
int time =20;
if (time <18){
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
Output:
Good evening
Example
int time =20;
String result =(time <18)?"Good day.":"Good evening.";
System.out.println(result);
Java Code:
public class MyClass{
public static void main(String[]args){
int time =20;
String result;
result =(time <18)?"Good day.":"Good evening.";
System.out.println(result);
}
}
Output:
Good evening.
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression){
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, and will be described later in this chapter
Example
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 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
Java Code:
public class MyClass{
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");
Output:
Thursday
When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.
Example
int day = 4;
switch (day){
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
Java Code:
public class MyClass{
public static void main(String[]args){
int day = 4;
switch (day){
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
}
}
Output:
Note that if the default statement is used as the last statement in a switch block, it does not need a
break.
1. If Statement
https://www.youtube.com/watch?v=7qLGhGPth3I
2. If-Else Statement
https://www.youtube.com/watch?v=cM-SuD1Hr9o
3. If…Else...If…Else Statement
https://www.youtube.com/watch?v=HlEomyY4KqI
Quiz 3.1
Instructions: Write your answer on the Answer Sheet (AS) provided in this module.
Activity 3.1
Test Data
Input number: 35
Pictorial Presentation:
Figure 3.3
Solution:
Java Code:
import java.util.Scanner;
public class Activity1{
public static void main(String[]args)
{
Scanner in = newScanner(System.in);
System.out.print("Input number: ");
int input =in.nextInt();
if (input >0)
{
System.out.println("Number is positive");
Output:
Input number: 35
Number is positive
Activity 3.2
In Java, it is also possible to if..else statements inside a if..else statement. It's called
Class Number{
public static void main(String[] args){
else {
largestNumber = n3;
}
}
else {
else {
largestNumber = n3;
}
}
Output:
Activity 3.3
Before you go through the program, make sure you know about Java Scanner to take input from the
user.
import java.util.Scanner;
class Main{
public static void main(String[] args){
char operator;
Double number1, number2, result;
switch (operator) {
break;
default:
System.out.println("Invalid operator!");
break;
}
}
}
Output:
Activity 3.4
A sequence of six tests all scored out of 100, are to be given different weightings in determining a final
mark. Write a program fragment that computes the appropriate weighted score for one test. The
fragment should first read values of Test Number and Score. Using a switch statement it should compute
and print the appropriate value of Weighted Score using the weightings given in the following table.
Table 3.7
For example, input of 3 and 27 should produce the following output: A score of 27 on test 3 gives a
weighted score of 5.4
Activity 3.5
Sample Output:
1. Put the running codes on the Activity Sheet provided in this module together with the screen
shots or pictures from your monitor of the output. Save your file with the following format:
<lastname_coursecode_section_Weekno_quarter_ActivitySheetNo.docx>
Example: delacruz_CP1212_ICT2MA_Week3_1stQuarter_ASNo3.docx
* Activity Sheet No. and Week No. refers to the week you are working on
2. Email the file to your teacher.
1. Java Operators
http://www1.fs.cvut.cz/cz/u12110/prt/java/j5.pdf
2. Logical Operator
https://www.youtube.com/watch?v=PAaqgTr7Cx4
5. Conditional Statement
https://www.inf.unibz.it/~calvanese/teaching/04-05-ip/lecture-notes/uni05.pdf
6. Java Switch
https://www.programiz.com/java-programming/switch-statement
8. If Statement
https://www.youtube.com/watch?v=7qLGhGPth3I
https://www.youtube.com/watch?v=iMeaovDbgkQ
9. If-Else Statement
https://www.youtube.com/watch?v=cM-SuD1Hr9o