0% found this document useful (0 votes)
2 views22 pages

Java Decision Control Statements Guide

This document discusses various decision control statements in Java like if, if-else, nested if, switch, and ternary operator. It provides examples and exercises to demonstrate how to use each statement. Key topics covered include using if-else to check multiple conditions more efficiently than nested if statements, accepting user input via command line arguments, and evaluating conditional expressions in a single line using the ternary operator. The next lecture will cover using the Scanner class for user input.

Uploaded by

GauRav PaNdey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Java Decision Control Statements Guide

This document discusses various decision control statements in Java like if, if-else, nested if, switch, and ternary operator. It provides examples and exercises to demonstrate how to use each statement. Key topics covered include using if-else to check multiple conditions more efficiently than nested if statements, accepting user input via command line arguments, and evaluating conditional expressions in a single line using the ternary operator. The next lecture will cover using the Scanner class for user input.

Uploaded by

GauRav PaNdey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

JAVA SE

(CORE JAVA)
LECTURE-8
Today’s Agenda

 Decision Control Statements

 If , if-else , nested if

 switch

 Ternary Operator
Decision Control Statement

 Decision making is the most crucial part of any program.

 For example :- Deciding whether a given a number is even or


odd.

 In such cases java supports various decision control statements like


other programming languages, they are

 if, if else, nested if


 switch
 Ternary Operator
if Statement

 Syntax :-
false
if(test_Condition)
{ true
-----
-----
}

* In case there is only a single statement in the body


of if- statement then curly braces can be dropped.
if else

false
if(test_Condition)
{
true
-----
-----
}
else
{
----
----
}
 Every else statement should have one if
statement.
if else if

 In case of checking multiple conditions there are two


options,
1. Use only if statement to check every condition.
2. Use else if statement after the first if statement to check
all the other remaining conditions.
 The first method holds a drawback. Can you tell what???
 The drawback in using only if statement to check all the conditions if
that, even after getting the right statement and executing it the
compiler still continues checking all the remaining statements, which
increases run time of the program.
 So it is convenient and suggested to use if else if statement
to check multiple conditions.
if else if

false
if(test_Condition)
{
true
-----
-----
}
else if( test_Condition)
{
----
true
----
}
else
{
----
}
Nested if

 Any conditional statement within the other conditional statement makes it nested
in nature.

if(test condition)
{
if(test condition)
{
----------
----------
}
else
{
---------
---------
}
}
Try this…

 Accept an integer from user via command line argument and


check whether it is odd or even in nature.
 Solution
class EvenOdd
{
public static void main(String [ ] args)
{
int a=[Link](args[0]);
if(a%2==0)
[Link](“Number is even”);
else
[Link](“Number is odd”);
}
}
Output
The switch Statement

 The switch statement is similar to if statement, as it is also a


decision control statement.
 It allows a variable to be tested against a list of values where
each value is called a case.
 Syntax :-
switch(variable_name or expression)
{ case value : //Statements
break;
case value : //Statements
break;
.
.
default : //Statements
}
The switch Statement

 The switch statement can use different variables to check the


conditions, which are byte, short, char, int.
 Java 7 onwards use of Strings and enumerated types are
also supported.
 Example :-
int month = 8;
switch (month)
{ case 1: [Link]("January“);
break;
case 2: [Link]("February“);
break;
// and so on…
default: [Link](“Invalid Month”);
}
The switch Statement

 Case II – Clubbing cases :-


switch(variable name)
{
case value 1: case value 2: case value3:
--------
break;
case value 4: case value 5: case value 6:
-------
break;
default:
-------
}
* Any number of cases can be clubbed together as per
condition.
Exercise
 WAP to accept a month number from the user via
command line argument and display the name of
the season in which the month falls according to the
table given below.
Month Number Season Name

11,12,1,2 Winter

3,4,5,6 Summer

7,8,9,10 Rainy

Any other value Wrong Input


Sample output
Solution

class SwitchEx1 Can we improve this???


{
public static void main(String [ ] args)
{
int month=[Link](args[0]);
switch(month)
{
case 11: case 12: case 1: case 2: [Link]("Winter season");
break;
case 3: case 4: case 5: case 6: [Link]("Summer Season");
break;
case 7: case 8: case 9: case 10: [Link]("Rainy Season");
break;
default: [Link]("Wrong input");
}
}
}
Improved Solution

class SwitchEx1
{
public static void main(String [ ] args)
{
switch(args[0])
{
case "11": case "12": case "1": case "2": [Link]("Winter season");
break;
case "3": case "4": case "5": case "6": [Link]("Summer Season");
break;
case "7": case "8": case "9": case "10": [Link]("Rainy Season");
break;
default: [Link]("Wrong input");
}
}
}
Exercise
 WAP which should accept 3 arguments via
command line of type operand, operator and
operand and should display the result by
performing appropriate calculation. Assume
operator would be either + or - ?

Sample Run:
Ternary Operator

• The ternary operator can be used as an alternative to the


Java’s if-else and switch statements.
• But it goes beyond that, and can even be used on the right
hand side of java statements.
• Syntax :-
• <variable>=(test condition)?<true case>:<false case>;
• Example :-
int a=4;
String str;
str=(a%2==0)? “Even” : “Odd”;
[Link](str);
Try this…
• WAP to accept an integer via command line
argument and print its absolute value. (If user
enters -1 then result should be 1)
• Solution :-
class PrintAbsolute
{
public static void main(String args[])
{
int a,b;
a=[Link](args[0]);
b=(a>=0) ? a : -a;
[Link](“Absolute value is”+b);
}
}
Try this…

• WAP to accept an integer via command line


argument and check whether it is a leap year or not
• Note: Not every year divisible by 4 is a leap year. For example
1700 was not a leap year. But 1600 was a leap year. Similarly year
2000 is a leap year but 2100 will not be a leap year

• So the condition for leap year is that:

• 1. year must be divisible by 4 and not divisible by 100


OR
• 2. year must be divisible by 400
Ref: [Link]
End Of Lecture 8

For any queries mail us @: scalive4u@[Link]


Call us @ : 0755-4271659, 7879165533

Agenda for Next Lecture:


1. Introduction To Scanner class

2. How to use Scanner class for input

Common questions

Powered by AI

The primary advantage of using the if-else-if ladder over multiple standalone if statements is efficiency. Using only if statements causes the program to check all conditions even after a correct condition is found, which can increase the runtime of the program. The if-else-if ladder allows the program to stop checking further conditions once the correct condition is found, improving performance .

Yes, the switch statement in Java can handle different data types. It can use byte, short, char, and int. From Java 7 onwards, it can also handle Strings and enumerated types .

A nested if statement is used when conditions depend on other conditions. It allows for more complex decision-making. An example is checking if an integer is odd or even and also checking if it's positive or negative. This requires two levels of conditions: first, checking for odd/even, then a nested check for positive/negative .

A developer might prefer using a ternary operator over if-else statements when the decision logic is simple, such as conditionally assigning a single value, and the focus is on concise code. The ternary operator can make the code more compact and reduce the number of lines, which might enhance readability in small and straightforward logic scenarios. However, for more complex logic, if-else statements might be more readable .

A year is a leap year if it is divisible by 4 and not divisible by 100, unless it is also divisible by 400. This involves a complex decision-making process in programming where multiple logical conditions must be evaluated together. This relates to decision control in programming, highlighting the need to efficiently handle multiple conditions using constructs like if-else or switch statements .

The ternary operator in Java differs from the if-else statement by being more compact and often used on the right-hand side of assignments. It condenses an if-else block into a single line, allowing for more concise code. The syntax is <variable> = (condition) ? <value if true> : <value if false>; whereas the if-else statement requires more lines and verbosity .

Clubbing cases in a switch statement allows grouping multiple potential values under one case block to execute the same code, simplifying the structure and improving readability. For instance, in a seasonal month checker program, multiple months corresponding to a season can be clubbed: cases 11, 12, 1, and 2 are clubbed to print "Winter season"; by handling multiple inputs with the same output, the code becomes both cleaner and more efficient .

The document suggests improving a simple switch statement by using Strings for the case labels of month numbers instead of integers. This improvement allows input to be matched directly as a string, simplifying the parsing of command line inputs. It enhances readability and maintainability as the code better represents the logic of checking conditions based on actual inputs without additional conversion .

The default case in a switch statement acts as a catch-all for any unmatched input, ensuring the program handles unexpected values gracefully. It can be strategically implemented to provide warnings or default behaviors, enhancing program robustness. For instance, in a month-based season checker, providing a 'Wrong input' message in default ensures users are informed of input errors .

Switch statements allow checking a variable against multiple cases, efficiently handling fixed values like enums or strings, and offer clear, concise syntax when compared to multiple stand-alone if statements. Nested if statements, however, can evaluate complex conditional logic where decisions depend on the result of a previous condition, but can become cumbersome and less readable for simple value checks. Each serves different purposes: switches for straightforward, constant-bound decisions, and nested ifs for intricate, condition-dependent logic .

You might also like