8.CONDITIONALS
In our day-to-day life, we often almost every day. (Think of) some examples:
- I am going to visit office by a local train, thus I reach at 10 AM, so the train is cancelled by 9 AM, I will catch a bus. So I reach here 5 p.m. & could take 10 AM train. Draw it diagrammatically as a flowchart.


Note that we are now a step ahead to decide what to do next.
Similarly, when we are writing a program in Java to get our problem solved by computer, I we need to instruct the computer what to do in a certain case. That one to do in another case. One-generally decision involves so in order to execute the program. One see if different one set of statements if that condition is met. One. Thus condition can be like checking the value of a variable
Let’s take an example program. Suppose we want the computer to tell me, that the no. entered is odd or even. How will computer determine if the no. is odd or even? One algorithm could show the algorithm is as follow –

As you can see a simple (clearsion statement) how we implement. This is true program
class OddorEvenTeller
PSVM(String args)
int remainder;
int numberToBeChecked = 25;
if (numberToBeChecked % 2
int remainder = numberToBeChecked % 2;
& if (remainder == 0)
SOP.ln(“Entered no. is even”);
else
SOP.ln(“Entered no. is odd”);
Read the above program carefully. User defined variable number. Used a variable for the value which we want to check whether it odd or even. remainder, is a variable it that stores the remainder after the no. to be divided is displayed.
Please note that we already have the operator (%) used for us the remainder. So just the operator (%) apply number/subscriber. The result is stored a variable. Here comes the new statement for you which does the collection the statement which checks the condition.Recall the time we said if the beginning. If runs or (or a variable) is Instance then if a condition is true & the condition cadillan is not the if that that condition is If (remainder == 0). Please note in Java if we use double equals (==) to check if RHS operand is equal to LHS operand. If it is on the expression returns a boolean variable value ‘true’. & if it is not so the expression returns a boolean value ‘false’.
One set d) instruction is
SOP.ln(“Entered no. is even”)
when will execute only when condition is true
Another set d instruction is
SOP.ln(“Entered no. is odd”);
when will execute only when condition is false &
So neither of the above set of instruction will be executed & Obviously, we also want that the no. will be either odd or even
So the format if conditional statement, if (conducted)
one set d instruction to execute when condition return the }else{
another set instruction to execute when condition return false
Please note that ‘else’ block is completely optional. There can be situation when if we over a set of instruction the certain condition is fine but in another case the is no set of instruction to execute that condition is false else block is not needed.
There is an efficient way to write the above code if using class OddorEvenTeller
& PSVM(String args)
SOP.ln(“Enter the no. you want to know if odd or even”);
Scanner number Scanner = new Scanner(System.in);
int String number = numberScanner.next();
if (numberToBeChecked/2 == 0)
SOP.ln(“Entered no. is even”);
else
SOP.ln(“Entered no. is odd”);
}}
numberScanner.close()
We got a big advantage here with the OScanner class available from Java library, we can easily input the value to be checked for odd or even when the program is executing. In the earlier program we were providing the value while writing the program.
At this point of time, you should be clear with compile & run, this flowchart explains it.

Please read the earlier chapter to recall more detail on this.
So basically, in the first pvg we are providing value at compile time to be checked for even or odd at compile time while in the second pvg we are providing value at run time.
Why the second pvg is better than first pvg? Suppose you are writing this program to your friend who lives in another city. He does not know the program so would you give him first program & ask him to change the value() numberToBeChecked with the no. to for which the user inputs to know the if the number is odd or even.? Or share him the .class file (compiled program) so that computer ask him the no. at runtime & tell whether it is odd or even? I believe most of you will say secondly:
Now apply the concept of we studied so far the program are for a no. to check if there is add or even.class OddorEvenTeller
{
PSVM(String[] args)
{
Scanner numberScanner = new Scanner(System.in);
for (int i = 0; i < 20; i++)
{
SOP.ln(“Enter the no. which you want to check for odd or even”);
int String numberToBeChecked = numberScanner.next();
if (numberToBeChecked / 2 == 0)
SOP.ln(“entered number” + numberToBeChecked + “is even”);
else
SOP.ln(“entered no. ” + numberToBeChecked + “is odd”);
}
}
}
If – else if – else & timed
In the above program above we saw that we are using if statement & one else statement. If the condition in your if statement is true then whatever inside if block is executed by the compiler. If for any other case like when the if-condition is not true, the statement following else & is executed.Let’s continue with the previous example about the computer if you don’t want he is odd or even. If it is the positive integer, instead is 0 or the computer intends. If it is the computer intends to you want that if you use a no. –
2, 4, 0, 6, 0 → computer prints even
1, 3, 5, 7, 9 → computer prints odd
0 → computer prints odd
-1, -2, -3 → computer prints is even
To solve this problem the if-else-if statement isn’t helpful you. These look class OddorEvenTeller
PSVM(String[] args)
{
(1) Scanner userInputScanner = new Scanner(System.in);
for (int i = 0; i < 20; i++)
{
SOP.ln(“Enter the no. which you can to check for odd or even”);
(2) int noToBeChecked = userInputScanner.next();
if (noToBeChecked == 0)
{
SOP.ln(“Entered no. is zero”);
} else if (noToBeChecked < 0)
{
SOP.ln(“Entered no. is negative”);
}
}
}
else if (noToBeChecked / 2 == 0)
{
SOP.ln(“Entered no. is even”);
} else {
SOP.ln(“Entered no. is odd”);
}
}
}
Please note to be kept in mind here & clear
(1) For now just know that this is a facility provided by Java library to take input/value/data when the program is running/executing (i.e plan (for ). You will understand it in better later on.
(2) Remember we have int “int” data type to our new variables (noToBeChecked). Plan variable is expected to take (Note the residue no. as well as a positive +). Practically from previous chapter that int (can store/submit residue even to (a data at 2/1).
(3) If we will do checking condition for Step within I see matching condition If found, then if the if-yes-I block is not checked.
Switch – case statement
This is another way it provided in Java to provide decide if provided in this is more simple than if-else statement we take needed. Here in value variable is checked for different variables, where value variable If matched the & statement in that block is executed by Java.
Suppose we want to do addition when user enter 1, subtraction when use enter 2, multiplication when use enter 3, division when use enter 4, & Computer & should display error message if any other no. is entered look at the program carefully
class SimpleCalculator
{
PSVM(String[] args) throws Exception
{
Scanner poCalculator = new Scanner(System.in);
int S OP.ln(“1. Addition”);
SOP.ln(“2. Subtraction”);
SOP.ln(“3. Multiplication”);
SOP.ln(“4. Division”);
SOP.ln(“5 enter your choice”);
about int userChoice = userChoice.nextInt();
System.out.print(“Enter userdarrNo'”);
switch (userChoice)
{
Case 1 :
& SOP.ln(“save yes no to do addition”); int firstNo = Integer.parseInt(userChoice…)(instance now()); SOP.ln(“2 a note be added”); int secondNo = Integer.parseInt(userChoice…)(instance next()); int sum = firstNo + secondNo; SOP.ln(“sum is” + sum); break;
Case 2: // can you write for loop Case 3: y each : Case 4: // break default: SOP.ln(“You entered wrong choice”)
Point to be considered is: The value we prondi as &endsin” for the variable usedha it matched against the constant we needed in each case statement when matched the statement inside that statement is executed break (optional but heavy at each one if matched code block not be checked the rest us in better efficiency
Ternary Operator: We also if-else statement in the beginning of the chapter. The statement are getting B spannning across multiple lines. What if, I see that w can be shortened to one line? Isn’t it comfortable for you? So here it is.
Read the old-one program we read earlier if it how we use ternary operator class OddOrEvenTeller
PSVM(String[] args) { int notToBeChecked = ? ( int remainder = notToBeChecked / 2; String result = (remainder == 0) ? “even” : “odd”; SOP.ln(“± result”); }
be || else – We see two special character && (condition) initially +), if they the statement belong), ?, if true the statement before), ?, if else the statement off is executed
=> nested statement: Have you seen a nest? If not try to see one (hol didn’t): It has multiple layers & things one outer thing followed o by a third thing 2 so on
(1) For (int whoretable = 2; whoretable <= 10; whoretable++) (2) (3) for (int counter = 1; counter <= 10; counter++) (4) int product = whoretable * counter; (5) SOP.ln(whoretable + “X” + counter + “=” + product); (6) ? ? ? ?
Can you guess what the program does? You pushed it right? This will give you multiplication table of a number 2 to 10. One good thing about Java is presence of curly braces which clearly defines the scope or jurisdiction of a conduct. We can think it like bordering. When we go to hell station like “Great section begin” or
“Great section ends” (There) define( at (1) start 1 scope) and at (1) starts one CPU execute in often b inside…. & the variable & stored inside the value at one iteration. The next size and at (2) iteration… store size ends at (2)… that for (of statement separated inside that three store. Start (2) stmt (2) is executed by sensilla there three store that may solve will work If first understande that for loop more at is…
Statements following (2) will run more times) how many times? you’ll Start! is int whoretable = 0 2 It means initial value of whoretable is 2. The is of type int whoretable_F = 10 means the stmt (2) is (2 will be created if the value of whoretable is less than or equal to 10
whoretable++ This is the increment condition. after each iteration, the value of whoretable is incremented by how much? whoretable + 1; it’s a shorthand notation is whoretable = whoretable + 1. So it means for each iteration, the value of whoretable is increased by 1.
What if you want to increment by 2,3 or any other digit? It can be within the whoretable += 2.
Now here you need to understand two important core form of increment because at whoretable++ for ++ whoretable
- This is called post-increment. In this case, the value of the variable is first used inside the for loop’s & after that incremented.
- This is called pre-increment. In this case the value of the variable is first incremented & and then used for However, point to note is that we don’t see any difference in observation when we use either of these in the for loop the for loop (int i = 0; i < 10; i++) and for (int i = 0; i < 5; i++) SOP.ln(2);
Both will return a same result
0 → the product wise 0 which was printed before i was merged 2, 3, 4
Please note the scope if the for loop n empty means at all not doing anything whatever is completely pin for computers
Similarly, for (int i = 0; 2 < 5; SOP.ln(++i)) } Here, ++i will cause the value to increase by 2′ before used in SOP.ln. Here the printed values will be 2, 3, 4, 5
It is because incomeant happen before to create the for loop n empty means at end not doing anything whatever is completely pin for computers
Similarly, for (int i = 0; 2 < 5; SOP.ln(++i)) } Here, ++i will cause the value to increase by 2′ before used in SOP.ln. Here the printed values will be 2, 3, 4
Please note the scope if the for loop n empty means at all not doing anything whatever is completely pin for computers
Similarly, for (int i = 0; 2 < 5; SOP.ln(++i)) } Here the ++i will cause the value to increase by 2′ before used in SOP.ln. Here the printed values will be 2, 3, 4, 5
KK did
Just like the loop is meant conditional case needed…case, for a loop can also be nested. The format of nested if-else is— if (condition) { if-condition } else { y else if { if-condition } else { y if-condition }
We want to print the identified of a no. value if we able to use like if you enter a do greater than 0 the program should print “Nested if” if you enter a do greater than 0 and also enter a do greater than a no. move the class NestdDemo
PSVM(String[] args) { SOP.ln(“please enter a no.”); Scanner s = new Scanner(System.in); int num = s.nextInt(); if (num == 0) { SOP.ln(“Neither positive or negative”);
else if (num < 0) { SOP.ln(“Negative”); } else if (num if (num / 2 == 0) { SOP.ln(“Even”); } else { SOP.ln(“Odd”); } } }
MAKE YOURSELF CONFIDENT! Similarly, can you try writing a similar program showing nested switch-case and nested loops (operate)
Planning:
NULL: We have used previous chapters different data type (whether primitive or non-primitive) and assign a value to it. For a pair of memory (the boxes—containing 0 and is) reserved for the variable name. If ‘int a = 5’;
a → | | 0 | | d ° | | 1 | 1 d |
Part g (the memory)
But what if we with just want assign the variable to NULL. NULL simply means the variable is not allocated any of memory. During our programming journey it will come across the NULL often.
APPLY YOUR KNOWLEDGE
By now, we have learnt few important concepts in Java – Conditional loops, variables. Let’s apply our learning as well for to solve some problems – Apply our learning to write programs in Java so that we can solve it problem through computer…
- Write a program to print the following pattern :
Worksheet: Before going to compile to start typing program. Think 1apply you read to understand the problem & then think of the solution.
TIP! If your program-blc, say to yourself – by can aside the problem I can work the program. I am born to write the program if play (replace with you fixed she used programming) can program I can also code it.
You can frame your students. To do any more times a day this will make pure “that you begin will stand thinking positively to find out the answer”
Ingredient: To fit complete this program we will need the concept of loops.
One the requirement is that on the first line we have to print 4 stars followed by stays in second line followed by 2 stars in third line followed by 1 star in fourth line
So you keyboard’s and character. You will find it on one of your keyboard buttons.
Well need to print this character only first line – 4 times need to be printed second line – 3 times need to be printed third line – 2 times need to be printed fourth line – 1 time need to be printed
Can you think LOOP if required there? Why? Well because we need to print a pattern for doing – doing line second line if for loop will be sufficient. Do you think one loop will be sufficient?
Third? The answer is “No. Because for each iteration of the size loop are needed to print it one on more times in level line. Hence, we need two loops. Note that we mentioned “for each iteration of the above loop” – where you a nested loop that is needed there outside loop would be called loop-1 & the nested loop will be called loop-2. This is called two loops.
Loops (outer loop) will take care of no of lines – it has to be printed in this problem, this loop is hard sum 4 times because we want to print * pattern on 4 lines.
Loop-2 (Nested loop) will take care of no of times – it has to be printed in one line. This loop is pretty this loop should run 4 times for first iteration of loop-1 so that 4 stars could be printed the loop should run 3 times for second iteration of loop-1 so that 3 stars could be printed.
This loop should run 1 time for fourth iteration of loop-1 so that 1 star could be printed.
What do you notice here? The no of times loop-2 will run is dependent on the #for that under which iteration of time(1) loop-1 is executing.
So from here we get the time for initialize value & variable or present value will have some correlation with the loop-1. Let’s write how some into code. What we have thought—
public class StarPrinter { PSVM(String[] args) { int tc = 5; for (int lineNo = 1; lineNo <= 4; lineNo++) { for (int starCounter = 1; starCounter <= (tc – lineNo); starCounter++) { System.out.print (“* “); } SOP.ln ( ); } } }
Try running this program on computer hopefully you will be able to see the expected output.
One point to note over here – Usage of SOP () yada the SOP.ln() SOP() always print the character in the same line where it printed last time compile & give us more to work line SOP.ln() do-print the character (using on the same line.
So if you need print with we used SOP() & SOP.ln() is.
for (int lineNo = 1; lineNo <= 4; lineNo++) { for (int starCounter = 1; starCounter <= (tc – lineNo); starCounter++) { System.out.print (“* “); } SOP.ln ( ); }
and for (int i = 0; 2 < 5; i++) { SOP.ln ( 2) ; }
Both will return a same result
0 → the product wise 0 which was printed before i was merged 2, 3, 4
Please note the scope if the for loop n empty means at all not doing anything whatever is completely pin for computers
Similarly, for (int i = 0; 2 < 5; SOP.ln(++i)) { }
Here, ++i will cause the value to increase by 2′ before used in SOP.ln. Here the printed values will be 2, 3, 4, 5
for (int lineNo = 1; lineNo <= 4; lineNo++) { // First loop will serve us here with lineNo = 1 in first iteration. That will correspond to first line of the output (on having 4 stars) thereafter conclusion is lineNo = 2 meaning that the second loop will not send us here when lineNo’s value becomes 5 or more. lineNo++ means ‘in the 2nd iteration, that loop will send us here with value of lineNo = 2. (then lineNo = ? and so on then the No = 4 loop execution will end when lineNo’s value becomes 5 or more
// For lineNo = 1, the inner loop should run 4 times // For lineNo = 2, the inner loop should be 3 times // For lineNo = 3, the inner loop should be 2 times // For lineNo = 4, the inner loop should be 1 time
How can we make sure that at each iteration the no of times inner loop executes is dependent by 5?
got an edge. ADD about be creating a variable with befor the outer loop used with a value = 5. And then the #formula in inner loop is the the inner – lineNo. So that when lineNo = 1, the condition will be, 5 – 1 = 4 when lineNo = 2, the condition will be, 5 – 2 = 3 when lineNo = 3, the condition will be 2 times when the No = 4, the inner loop will execute 1 time.
Let’s do it!
NOTE: Add more problems in this chapter
class StarPrinter { PSVM(String[] args) { int tc = 5; for (int lineNo = 1; lineNo <= 4; lineNo++) { for (int starCounter = 1; starCounter <= (tc – lineNo); starCounter++) { System.out.print (“* “); } SOP.ln ( ); } } }
Try running this program on computer hopefully you will be able to see the expected output.
One point to note over here – Usage of SOP () yada the SOP.ln() SOP() always print the character in the same line where it printed last time compile & give us more to work line SOP.ln() do-print the character (using on the same line.
So if you need print with we used SOP() & SOP.ln()