0% found this document useful (0 votes)
1 views

Section 02 Conditionals

Uploaded by

krish89.ece
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Section 02 Conditionals

Uploaded by

krish89.ece
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Conditionals: if/else

© luv2code LLC
Conditionals: if/else
• Conditional statements can make decisions based on conditions

• Will execute certain code if conditions are true or false

if (<some boolean condition is true>)

// execute this block of code

} else
{

// if condition false, execute this block of cod

www.luv2code.com © luv2code LLC


Example: Check voting age

int minVotingAge = 18

int age = 15; Entered by user

System.out.println("Minimum voting age: " + minVotingAge)

if (age >= minVotingAge) Executes if boolean condition

System.out.println("You are eligible to vote.") is true

} else
{

System.out.println("Sorry, you are not eligible to vote.")

Executes if boolean condition Minimum voting age: 1

is false Sorry, you are not eligible to vote.

www.luv2code.com © luv2code LLC


Example: Check voting age - Prompt User
Enter your age: 1
Scanner scanner = new Scanner(System.in)

Minimum voting age: 1

Sorry, you are not eligible to vote.


int minVotingAge = 18

System.out.print("Enter your age: ") Enter your age: 2

int age = scanner.nextInt() Minimum voting age: 1

You are eligible to vote.


System.out.println("Minimum voting age: " + minVotingAge)

if (age >= minVotingAge)


{

System.out.println("You are eligible to vote.")

} else
{

System.out.println("Sorry, you are not eligible to vote.")

scanner.close();

www.luv2code.com © luv2code LLC


boolean variable
Scanner scanner = new Scanner(System.in)

int minVotingAge = 18

Enter your age: 1

System.out.print("Enter your age: ") Minimum voting age: 1

Sorry, you are not eligible to vote.


int age = scanner.nextInt()

System.out.println("Minimum voting age: " + minVotingAge)

boolean eligible = (age >= minVotingAge)

if (eligible)
{

System.out.println("You are eligible to vote.")

} else
{

System.out.println("Sorry, you are not eligible to vote.")

scanner.close();

www.luv2code.com © luv2code LLC


Conditional Operators:
Name Description
==, != equal, not equal

<, > less than, greater than

>=, <= greater than or equal to, less than or equal to

&& logical AND

|| logical OR

! logical NOT

www.luv2code.com © luv2code LLC


Example: Checking enrollment class count
• When enrolling in classes, there is a minimum and maximum limit
int minClassCount = 2

int maxClassCount = 5

userCount=

int userCount = 3 Entered by user minClassCount=

maxClassCount=

System.out.println("userCount=" + userCount) Your class count is in the recommended range

System.out.println("minClassCount=" + minClassCount)

System.out.println("maxClassCount=" + maxClassCount)

System.out.println() and
;

if ((userCount >= minClassCount) && (userCount <= maxClassCount))

System.out.println("Your class count is in the recommended range")

} else
{

System.out.println("Your class count is outside of the recommended range")

www.luv2code.com © luv2code LLC


Nested if/else: userCount=

minClassCount=

maxClassCount=

int minClassCount = 2 Check if userCount is an Your class count is in the recommended rang

int maxClassCount = 5

even number or odd number You have selected an odd number of classes.

int userCount = 3
;

if ((userCount >= minClassCount) && (userCount <= maxClassCount))


% - Modulus operator

System.out.println("Your class count is in the recommended range") Returns the remainder of division

if ((userCount % 2) == 0) If number divided by 2

System.out.println("You have selected an even number of classes.") has 0 remainder


then it is an even number

} else
{

System.out.println("You have selected an odd number of classes.")

Nested if/else statement


} else
{

System.out.println("Your class count is outside of the recommended range")

www.luv2code.com © luv2code LLC


If/else if
• For an exam score, determine scoring tier

double scoreOnExam = 81.0

You scored in the second tier.


double firstTierScoreMin = 90.0

double secondTierScoreMin = 80.0

if (scoreOnExam >= firstTierScoreMin)

System.out.println("You scored in the first tier.")

} else if (scoreOnExam >= secondTierScoreMin)

System.out.println("You scored in the second tier.")

} else
{

System.out.println("Low grade. You did not score in the top two tiers.")

www.luv2code.com © luv2code LLC


Ternary operator
Advanced

• Short-hand notation for if/els

• Reduces amount of code … but can be dif cult to read

fi
Ternary operator

String message = (<some boolean condition>) ? <true value> : <false value>

String message = (age >= minVotingAge) ? "You are eligible to vote" : "You are NOT eligible to vote";

www.luv2code.com © luv2code LLC


Ternary operator: Example
Advanced

Traditional

String message = null

if (age >= minVotingAge)

message = "You are eligible to vote"

} else
Reduces amount of code …
{

message = "You are NOT eligible to vote"

System.out.println(message); but can be difficult to read

Ternary

String message = (age >= minVotingAge) ? "You are eligible to vote" : "You are NOT eligible to vote"

System.out.println(message)
;

www.luv2code.com © luv2code LLC


Comparing Strings

© luv2code LLC
Comparing Strings
• Comparing Strings in Java can be very trick

• This is often the source of bugs in programs by new Java developers

Hello World Hello World

Are these Strings the same???

www.luv2code.com © luv2code LLC


Comparing Strings
• There are two ways of comparing String

• == operator: compares the memory addres

• .equals(…) method: compares the string content

• For comparing String contents, use .equals(…) method

Best Practice

www.luv2code.com © luv2code LLC


It’s Tricky ….
String s1 = "Hello"

String s2 = "Hello"

boolean result1 = (s1 == s2)

s1: Hell

System.out.println("s1: " + s1) s2: Hell

System.out.println("s2: " + s2) s1 == s2: true

System.out.println("s1 == s2: " + result1);

What???
String s3 = new String("Hello")
;

boolean result3 = (s1 == s3)


;

== operator:
s1: Hell
System.out.println("s1: " + s1) compares the

s3: Hell memory address


;

System.out.println("s3: " + s3)

s1 == s3: false
;

Not the contents of the String


System.out.println("s1 == s3: " + result3);

www.luv2code.com © luv2code LLC


String Interning
• When Java creates String using String literals (without the new keyword

• Leverages a technique known as String internin


s1 Hello

• If the String literal already exists in the String pool, it will reuse the String referenc

• In our example, when s2 was assigned, it reused same reference as s


s2

• Hence, they have the same memory address … point to same location

String s1 = "Hello"
;

String s2 = "Hello"
;

boolean result1 = (s1 == s2)


;

s1: Hell == operator:


System.out.println("s1: " + s1)

compares the
s2: Hell
;

System.out.println("s2: " + s2) memory address

s1 == s2: true
;

System.out.println("s1 == s2: " + result1); Not the contents of the String

www.luv2code.com © luv2code LLC


Creating a ‘new’ String
• When Java creates a String using the new keywor

• Allocates new space in memory with a new memory addres s1 Hello

• In our example, when s3 was assigned, it is pointing to a new memory address

• Hence, they do NOT have the same memory address … point to different locations s2

s3 Hello

String s1 = "Hello"
;

String s3 = new String("Hello")


;

boolean result3 = (s1 == s3)


;

s1: Hell == operator:

compares the
System.out.println("s1: " + s1) s3: Hell memory address

System.out.println("s3: " + s3) s1 == s3: false


Not the contents of the String
;

System.out.println("s1 == s3: " + result3);

www.luv2code.com © luv2code LLC


Comparing Strings: .equals(…)
s1 Hello
• When comparing the contents of a Strin

• Best practice is to use .equals(…) method


s3 Hello

String s1 = "Hello";
String s3 = new String("Hello")

boolean result3 = s1.equals(s3)

System.out.println("s1.equals(s3): " + result3);

s1: Hell

s3: Hell Compares contents

s1.equals(s3): true of the String

www.luv2code.com © luv2code LLC


Case-Sensitive
• Strings in Java are case-sensitive

• Hello is not the same as hell

• To ignore case-sensitivity, use: .equalsIgnoreCase(…)

String s3 = new String("Hello")


;

System.out.println("s3: " + s3)


;

String s4 = new String("hello")


;

System.out.println("s4: " + s4) s3: Hell

s4: hell

boolean result4 = s4.equalsIgnoreCase(s3) s4.equalsIgnoreCase(s3): true


;

System.out.println("s4.equalsIgnoreCase(s3): " + result4);

www.luv2code.com © luv2code LLC


Recap Best Practice

• The best practice for String comparisons, use: .equals(…

• To ignore case, use: .equalsIgnoreCase(…)

• Do NOT use == to compare Strings

www.luv2code.com © luv2code LLC


Switch Statement

© luv2code LLC
switch Statement
• switch statement can make decisions based on a value(s

• Will execute certain code based on the value of a variable

• Can be used to replace multiple if-else statements for single variable

switch (variable)

case value1:
// execute this block of code
break;
case value2:
// execute this block of code
break;
default:
// default block of code
}

www.luv2code.com © luv2code LLC


switch Statement switch (variable)

case value1:
// execute this block of code
break;
• The switch statement has a variable case value2:
// execute this block of code
break;
default:

• The type of the variable can only b }


// default block of code

• primitive type: byte, short, char and int

• Wrapper classes: Byte, Short, Char and Integer

• String and Enum

Discussed later in
the course

www.luv2code.com © luv2code LLC


Basic Example
• case: The value to evaluat

• break: exits the case block to prevent executing subsequent case blocks

String computerType = "tablet"

switch (computerType)
{

case "smartphone"
:

System.out.println("Smartphones offer computing power in your hand.")

break
;

case "tablet"
:

System.out.println("Tablets are lightweight for browsing and light tasks.")

break
;

}
Tablets are lightweight for browsing and light tasks.

www.luv2code.com © luv2code LLC


Full Example
public class SwitchComputerType

public static void main(String[] args)

String computerType = "tablet"

switch (computerType)

case "smartphone"

System.out.println("Smartphones offer computing power in your hand.")


The break statement is VERY important

break
to avoid inadvertently falling through
;

case "tablet"
:

System.out.println("Tablets are lightweight for browsing and light tasks.")

break
;

case "laptop"
:

System.out.println("Laptops are portable for work on the go.")

break
;

case "desktop"
:

System.out.println("Desktops excel in gaming and work related tasks.")

break
;

default
:

System.out.println("Unknown computer type.") The default case is executed

if none of the other cases match


}

Tablets are lightweight for browsing and light tasks.


}

www.luv2code.com © luv2code LLC


Fall-Through (by design)
• There are scenarios when you want to leverage fall-throug

• Grouping cases with shared logi

• Supporting a range of value

• Replacing complicated if-else chain

• …

www.luv2code.com © luv2code LLC


Example: Fall-Through (by design)
// Months are 1-based: January = 1, February = 2, etc ..

int theMonth = 9; // Septembe Based on the month number,

System.out.println(“Month: " + theMonth)

Determine if it is:
switch (theMonth)
Quarter 1 - Q1

case 1
Quarter 2 - Q2
:

case 2
:

case 3 Quarter 3 - Q3
:

System.out.println("Q1") Quarter 4 - Q4

break
;

case 4
:

case 5
:

case 6
:

System.out.println("Q2")

break
;

case 7 Use case: Grouping cases with shared logic


:

case 8
:

case 9
:

System.out.println("Q3")
;

break
;

case 10
:

case 11
:

case 12 Month:
:

System.out.println("Q4")
Q3
;

break
;

default
:

System.out.println("Invalid month")
;

www.luv2code.com © luv2code LLC


Recap Best Practice

• Leverage supported data types on switch variabl

• Provide break statements to avoid inadvertently falling through

• Include a default case to handle for unknown values

www.luv2code.com © luv2code LLC


Modern switch Statement

© luv2code LLC
Regular switch Statement
• While regular switch statement meets basic requirement

• There are a number of limitation

• Repeated use of break statements (boilerplate code, verbose

• Limited types supported: byte, short, char, int, etc …


switch (variable)

case value1:
// execute this block of code
break;
case value2:
// execute this block of code
break;
default:
// default block of code
}

www.luv2code.com © luv2code LLC


Modern switch Statement
• Java 14 introduced a Modern switch statemen

• Advantage s

• Reduces boilerplate code (eliminates repeated break statements and verbosity

• Improves readability and maintenance of cod

• Expands additional types supporte

• Can return value


s

• Better handling of default case

www.luv2code.com © luv2code LLC


Modern switch Statement Syntax
• Replace case blocks and break statement with arrow operato

switch (variable)

case value1 -> expression1;


case value2 -> expression2;
default -> defaultExpression;
}

• The Modern switch can also return values (expression)

www.luv2code.com © luv2code LLC


Compare Regular vs Modern
String computerType = "tablet"

switch (computerType) Regular Switch

case "smartphone" (verbose)

System.out.println("Smartphones offer blah blah …")

break
;

case "tablet"
:

System.out.println("Tablets are blah blah …")

break
Modern Switch
;

(condensed)

String computerType = "tablet"


;

switch (computerType)
{

case "smartphone" -> System.out.println("Smartphones offer blah blah …")

case "tablet" -> System.out.println("Tablets are blah blah …")

www.luv2code.com © luv2code LLC


Modern switch Statement
• The switch statement has a variable

• The type of the variable can b

• primitive type: byte, short, char and int and associated Wrapper classe

• String and Enu m

switch (variable)

case value1 -> expression1;


case value2 —> expression2
• Modern switch adds support fo

case null —> nullExpression;

default -> defaultExpression;


}
• null handling and Sealed classe

• Sealed classes provided more controlled inheritance support

www.luv2code.com © luv2code LLC


Full Example
public class ModernSwitchComputerType
Modern Switch

can return a value


public static void main(String[] args)

String computerType = "tablet"

String description = switch (computerType)

case "smartphone" -> "Smartphones offer computing power in your hand."

case "tablet" -> "Tablets are lightweight for browsing and light tasks."

case "laptop" -> "Laptops are portable for work on the go."

case "desktop" -> "Desktops excel in gaming and work related tasks."

default -> "Unknown computer type."

}
;

System.out.println(description)

}
Tablets are lightweight for browsing and light tasks.

www.luv2code.com © luv2code LLC


Recap - Modern switch statement
• Reduces boilerplate code (eliminates repeated break statements and verbosity

• Improves readability and maintenance of cod

• Expands additional types supporte

• Can return value


s

• Better handling of default case

www.luv2code.com © luv2code LLC


Enums

© luv2code LLC
Enums
• Enum is short for enumeration

• Used for de ning a set of related constant value


fi
s

• Enums are type-saf

• Improves readability and maintenance of code

public enum ComputerType

SMARTPHONE, TABLET, LAPTOP, DESKTOP

www.luv2code.com © luv2code LLC


Full Example public enum ComputerType

SMARTPHONE, TABLET, LAPTOP, DESKTOP

public class EnumDemo }

public static void main(String[] args)

ComputerType myComputerType = ComputerType.TABLET

String description = switch (myComputerType)

case ComputerType.SMARTPHONE -> "Smartphones offer computing power in your hand."

case ComputerType.TABLET -> "Tablets are lightweight for browsing and light tasks."

case ComputerType.LAPTOP -> "Laptops are portable for work on the go."

case ComputerType.DESKTOP -> "Desktops excel in gaming and work related tasks."

default -> "Unknown computer type."

}
;

System.out.println(description)
;

Tablets are lightweight for browsing and light tasks.

www.luv2code.com © luv2code LLC

You might also like