Course Instructor: Nazish Basir Page: 1/13 Institute of Information and Communication Technology, University of Sindh
Course Instructor: Nazish Basir Page: 1/13 Institute of Information and Communication Technology, University of Sindh
IF STATEMENT
Following is the syntax of an if statement:
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not,
the first set of code after the end of the if statement (after the closing curly brace) will be executed.
IF-ELSE STATEMENT
Following is the syntax of an if...else statement:
if(Boolean_expression) {
// Executes when the Boolean expression is true
}
else {
// 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.
import java.util.Scanner;
class PassingGrade
{
public static void main( String [ ] args )
{
Scanner scan = new Scanner( System.in );
System.out.print( "Enter a grade > " );
int grade = scan.nextInt( );
String message;
if ( grade >= 60 )
message = "You passed";
else
message = "You failed ";
System.out.println( message ) ;
}
}
You can nest else if...else in the similar way as we have nested if statement:
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
}
//else Executes when the Boolean expression 1 is false
else if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
else
{
// Executes when the Boolean expression 2 is false
}
import java.util.Scanner;
class LetterGrade
{
public static void main( String [] args )
{
Scanner scan = new Scanner( System.in );
char grade;
System.out.print( "Enter your test grade: " );
int score = scan.nextInt( );
if ( score >= 90 )
grade = 'A';
else if ( score >= 80 )
grade = 'B';
else if ( score >= 70 )
grade = 'C';
else if ( score >= 60 )
grade = 'D';
else // grade fits none of the conditions
grade = 'F';
System.out.println("Your test score "+score+" has "+grade+" Grade" );
}
}
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
import java.util.Random;
import java.util.Scanner;
class GuessANumber
{
public static void main( String [ ] args )
{
Random random = new Random( );
int secretNumber = random.nextInt( 10 ) + 1;
Scanner scan = new Scanner( System.in );
System.out.print( "I'm thinking of a number" + " between 1 and 10. What
is your guess? " );
int guess = scan.nextInt( );
if ( guess < 1 || guess > 10 )
{
System.out.println( "Well, if you're not going to try," + " I'm not
playing." );
}
else
{
if ( guess == secretNumber )
System.out.println( "Hoorah. You win!" );
else
{
System.out.println( "The number was " + secretNumber );
if ( Math.abs( guess - secretNumber ) > 3 )
System.out.println( "You missed it by a mile!" );
else
System.out.println( "You were close." );
System.out.println( "Better luck next time." );
}
}
}
}
SWITCH STATEMENT
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.
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
FOR LOOP
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a
specific number of times. A for loop is useful when you know how many times a task is to be repeated.
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 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.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
class ForTick {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}
class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime = true;
num = 14;
for(int i=2; i <= num/i; i++) {
if((num % i) == 0) {
isPrime = false;
break;
}
}
if(isPrime) System.out.println("Prime");
else System.out.println("Not Prime");
}
}
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
}
WHILE LOOP
A while loop statement in Java programming language repeatedly executes a target statement as long as a given
condition is true.
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
char ch = 'y';
double number, answer;
Scanner myObj = new Scanner(System.in);
number = myObj.nextInt();
answer = Math.sqrt(number);
System.out.println("Square root is " + answer);
System.out.println("Do you want the square root of another number?" );
System.out.println( "Press y for yes... ");
ch = myObj.next().charAt(0);
}
}
}
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.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to
the next iteration of the loop.
In a for loop, the continue keyword causes control to immediately jump to the update statement.
In a while loop or do/while loop, control immediately jumps to the Boolean expression.
The continue may specify a label to describe which enclosing loop to continue.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
class BreakLoop2 {
public static void main(String args[]) {
int i = 0;
while(i < 100) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}
class BreakLoop3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
class TestArray{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int a[] : arr){
for(int b: a ){
System.out.print(b);
}
System.out.println();
}
}
}
EXERSICE 1 :
Write a Java program to display the following character rhombus structure.
Input the number: 7
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
ABCDEFEDCBA
ABCDEFGFEDCBA
ABCDEFEDCBA
ABCDEDCBA
ABCDCBA
ABCBA
ABA
A
EXERSICE 2:
Create a program for Mark sheet with following requirements:
Take input for data of 5 students in 7 different arrays like: (Roll Number, Name, Marks of 5 different subjects)
Calculate and store the Total, Percentage and Grade of them in other 3 arrays.
Use loops, and decision statements for the repetition and decision making.
Then display the results as shown below
Roll No.: 2k19/SW/130
Name of Student: XYZ
English: 40
Calculus: 50
Electronics: 60
Programming: 70
Intro. To IT: 80
Total: 300
Percentage: 60%
Grade: B
EXERCISE 3:
Write a program to input a character from user and check whether given character alphabet, digit or special
character is using if else. If user presses ENTER the program should exit.
Input character: a
'a' is alphabet
Input character: A
'A' is alphabet
Input character: #
'#' is special character
Input character: 1
'1' is a number
Input character:
Exit