Showing posts with label Java control statement. Show all posts
Showing posts with label Java control statement. Show all posts

Monday, April 8, 2024

Switch Expressions in Java 12

In Java 12 Switch statement has been extended to be used either as a statement or an expression. In this article we’ll see with some examples how to use this new feature switch expressions in Java.


Java Switch expressions

A new form of switch label, written "case L ->" has been added in Java 12 that allows the code to the right of the label to execute only if the label is matched.

We’ll try to understand this switch expression with an example, initially let’s use traditional switch statement to write a conditional switch-case branch and then use switch expression to see how it simplifies it.

For example if you want to display the quarter, passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1:    
   case 2:    
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4:   
   case 5:     
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:   
   case 8:  
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:     
   case 11:   
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }
 }
}

Consider some of the pain areas here-

  1. Even if multiple cases have the same end value still you need to write them in the separate lines.
  2. Use of many break statements make it unnecessarily verbose.
  3. Missing a break statement results in an accidental fall-through.

Now let’s write the same example using Java switch expressions.

public class SwitchCaseDemo {

  public static void main(String[] args) {
    int month = 4;        
    switch(month){
      case 1, 2, 3 -> System.out.println("Quarter 1");         

      case 4, 5, 6 -> System.out.println("Quarter 2");     
  
      case 7, 8, 9 -> System.out.println("Quarter 3");             
       
      case 10, 11, 12 -> System.out.println("Quarter 4");              
      
      default -> System.out.println("Invalid month value passed");
    }
  }
}

Note the changes here-

  1. Multiple case labels can be grouped together now.
  2. Break statement is not required any more. If a label is matched, then only the expression or statement to the right of an arrow label is executed; there is no fall through.
  3. This new switch form uses the lambda-style syntax introduced in Java 8 consisting of the arrow between the label and the code that returns a value.

The new kind of case label has the following form

case label_1, label_2, ..., label_n -> expression;|throw-statement;|block

Java 12 onward you can use colon syntax (:) too with multiple case labels but in that case break statement has to be used to avoid fall-through.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1, 2, 3: System.out.println("Quarter 1"); 
         break;

   case 4, 5, 6: System.out.println("Quarter 2");  
       break;
   case 7, 8, 9: System.out.println("Quarter 3");    
       break;
   case 10, 11, 12: System.out.println("Quarter 4");     
       break;
   default : System.out.println("Invalid month value passed");
  }
 }
}

Why is it called Switch expression

Now the more pertinent question is why this new feature is called switch expression in Java. As you must be knowing; Statements are essentially "actions" that have to be executed. Expressions, however, are "requests" that produce a value. Same difference applies to switch statement and switch expressions too.

Here is an example showing returning a value from a traditional switch statement.

public class SwitchCaseDemo {
 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  String message = "No event to log";
  switch (event) {
    case "Start":
      message = "User started the event";
      break;
    case "Stop":
      message = "User stopped the event";
      break;
  }
  return message;
 }
}

Output

User started the event

Same thing with Java Switch expressions. Since expression itself produces a value so it can be assigned to a variable directly.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  var msg = switch (event) {
    case "Start" ->  "User started the event";
    case "Stop" -> "User stopped the event";
    default -> "No event to log";
  };
  return msg;
 }
}

Output

User started the event

Using yield statement with Switch expression

If you want to use colon syntax then you can assign the value directly using yield statement. The yield statement takes one argument, which is the value that the case label produces in a switch expression.

public class SwitchCaseDemo {

  public static void main(String[] args) {
    System.out.println(getMessage("Stop"));
  }
	 
  private static String getMessage(String event) {
    var msg = switch (event) {
      case "Start": 
        yield "User started the event";
      case "Stop": 
        yield "User stopped the event";
      default: 
        yield "No event to log";
    };
    return msg;
  }
}

Writing statement blocks

If you need to have multiple statements with in a case you can use a statement block enclosed in curly braces. Specify the value that the case label produces with the yield statement.

public class SwitchCaseDemo {

  public static void main(String[] args) {
    int month = 4;        
    var value = switch(month){
      case 1, 2, 3 ->{
        System.out.println("Quarter 1");     
        yield "Quarter 1";
      }
      case 4, 5, 6 -> {
        System.out.println("Quarter 2"); 
        yield "Quarter 2";
      }
          
      case 7, 8, 9 ->{
        System.out.println("Quarter 3");     
        yield "Quarter 3";
      }
               
      case 10, 11, 12 -> {
        System.out.println("Quarter 4");  
        yield "Quarter 4";            
      }
              
      default -> {
        System.out.println("Invalid month value passed");
        yield "Invalid month value";
      }
    };
    System.out.println("Value- " + value);
  }
}

That's all for this topic Switch Expressions in Java 12. If you have any doubt or any suggestions to make please drop a comment.Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java Sealed Classes and Interfaces
  2. break Statement in Java With Examples
  3. Java Record Class With Examples
  4. Ternary Operator in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Private Methods in Java Interface
  2. Multi-Catch Statement in Java Exception Handling
  3. Creating a Thread in Java
  4. How HashMap Works Internally in Java
  5. Byte Streams in Java IO
  6. Check if Given String or Number is a Palindrome Java Program
  7. Spring Boot Hello World Web Application Example
  8. Connection Pooling With Apache DBCP Spring Example

Monday, July 4, 2022

continue Statement in Java With Examples

When you are working with loops where loop body is repeatedly executed, you may have a scenario where you want to skip the execution of statements inside the loop or you may want to terminate the loop altogether. To handle these two scenarios there are two control statements in Java- continue statement and break statement. In this tutorial you’ll learn about Java continue statement along with usage examples.

When to use continue statement in Java

During the repeated execution of the loop if you don’t want to execute statements with in the loop body for some particular condition you can force the next iteration of the loop using continue statement.

If there is a continue statement in a loop statements after the continue are not executed and control jumps to the beginning of the loop.

If continue statement is there in while loop or do-while loop control transfers to the condition of the loop.

In case of for loop, continue statement causes the control to transfer to the iteration part first and then to condition part.

Continue statement Java examples

1- Using continue statement with while loop. In the example you want the user to enter an even number when such a number is entered then only control comes out of the loop otherwise loop continues.

public class ContinueJava {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int number;
    while(true){
      System.out.print("Enter a number: ");
      number = scanner.nextInt();
      // checking entered number even or not
      if(number%2 != 0) {
        System.out.println("Please enter even number...");
        continue;
      }else {
        break;
      }
    }
    scanner.close();
    System.out.print("Entered number is- " + number);
  }
}

Output

Enter a number: 5
Please enter even number...
Enter a number: 7
Please enter even number...
Enter a number: 8
Entered number is- 8

2- Using continue statement in for loop.

public class ContinueJava {
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++) {
      if (i == 1)
        continue;
      System.out.println(i);
    }
  }
}

Output

0
2
3
4

As you can see when value of i is 1 continue statement is encountered so the statement after the continue statement is not executed and the control transfers to the beginning of the loop for next iteration.

3- Using continue statement in do-while loop. In the example odd numbers between 1..10 are displayed using do-while loop.

public class ContinueJava {
  public static void main(String[] args) {
    int i = 1;
    do {
      // check if even number
      if(i%2 == 0)
        continue;
      System.out.println(i);
    }while(++i < 10);
  }
}

Output

1
3
5
7
9

Labelled continue statement in Java

Just like labeled break statement there is also a labeled continue statement to let you decide which loop to continue.

Labelled continue statement Java example

In the example a pattern (triangle) is displayed using labeled continue statement.

public class ContinueJava {
  public static void main(String[] args) {
    outer:
    for (int i = 0; i < 6; i++) {
      for(int j = 0; j < 6; j++) {
        if(j > i) {
          System.out.println();
          continue outer;
        }
        System.out.print("*");
      }
    }
  }
}

Output

*
**
***
****
*****
******

In the example whenever value of j is greater than i control is transferred to the outer for loop for next iteration.

That's all for this topic continue Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch-Case Statement in Java With Examples
  2. Java Variable Types With Examples
  3. super Keyword in Java With Examples
  4. Access Modifiers in Java - Public, Private, Protected and Default
  5. Java Abstract Class and Abstract Method

You may also like-

  1. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  2. Method Overloading in Java
  3. Linear Search (Sequential Search) Java Program
  4. Bubble Sort Program in Java
  5. HashMap in Java With Examples
  6. Difference Between Thread And Process in Java
  7. pass Statement in Python
  8. Spring Component Scan Example

Saturday, July 2, 2022

return Statement in Java With Examples

In previous tutorials we have already seen continue statement which is used to continue the iteration of a loop and break statement which is used to break out of a loop, in this post we’ll learn about return statement in Java which is used to explicitly return from a method.

Java return statement

When a return statement is encountered in a method that method’s execution is terminated and control transfers to the calling method. A return statement may or may not return a value to the calling method.

Rules for using Java return statement

  1. If no value is returned from the method then the method signature should signify it by having void in method signature. For example- void methodA()
  2. If a method is not returning any value i.e. its a void method then having return statement in that method is not mandatory. Though an empty return can still be there which can be used as a control statement to terminate execution of the method for given condition.
  3. If a method is returning a value then return type should be signified in the method signature. For example a method that returns int should have it in its method signature- int methodA()
  4. The return type of the method and actual value returned should be compatible.

Java return keyword example

1- A method returning int value.

public class ReturnExample {

 public static void main(String[] args) {
  ReturnExample obj = new ReturnExample();
  int sum = obj.add(6,  7);
  System.out.println("Sum is- " + sum);
 }
 
 int add(int a, int b) {
  int sum = a + b;
  return sum;
 }
}

Output

Sum is- 13

2- A void method with return statement as a control statement to terminate method execution when the condition is satisfied.

public class ReturnExample {
  public static void main(String[] args) {
    ReturnExample obj = new ReturnExample();
    obj.display();
    System.out.println("After method call...");
  }
    
  void display() {
    for(int i = 1; i <= 10; i++) {
      // method execution terminates when this 
      //condition is true
      if (i > 5)
        return;
      System.out.println(i);
    }
  }
}

Output

1
2
3
4
5
After method call...

In the example, there is a for loop in method with a condition to return from the method. When the condition is true, method execution is terminated and the control returns to the calling method.

One point to note here is that in a method return statement should be the last statement or it should be with in a condition. Since method execution terminates as soon as return statement is encountered so having any statements after return results in “Unreachable code” error.

public class ReturnExample {

 public static void main(String[] args) {
  ReturnExample obj = new ReturnExample();
  obj.display();
  System.out.println("After method call...");
 }
 
 void display() {
  int i;
  return;
  i++; // error
 }
}

In the example there is code after the return statement which is never going to be executed thus the “Unreachable code” compile time error.

That's all for this topic return Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java do-while Loop With Examples
  2. Conditional Operators in Java
  3. Why Class Name And File Name Should be Same in Java
  4. Object Creation Using new Operator in Java
  5. Literals in Java

You may also like-

  1. Method Overriding in Java
  2. Interface in Java With Examples
  3. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  4. try-catch Block in Java Exception Handling
  5. Split a String in Java Example Programs
  6. Java Program to Reverse a Number
  7. Serialization and Deserialization in Java
  8. Nested Class And Inner Class in Java

Friday, June 24, 2022

break Statement in Java With Examples

When you are working with loops where loop body is repeatedly executed, you may have a scenario where you want to skip the execution of statements inside the loop or you may want to terminate the loop altogether. To handle these two scenarios there are two control statements in Java- continue statement and break statement. In this tutorial you’ll learn about Java break statement along with usage examples.

Where do you use break statement in Java

break statement in Java can be used in following scenarios-

  1. For terminating a loop– If there is a break statement with in a for loop, while loop or do-while loop the loop is terminated and the control moves to the statement immediately following the loop.
  2. For terminating switch statement– In Java switch statement if a case is followed by a break statement then the switch statement is terminated. For usage of break statement with switch statement in Java refer this post- Switch-Case Statement in Java
  3. Using labeled break statement– You can use labeled break statement to exit out of a labelled block.

break statement Java examples

1- Using break statement to break out of a for loop. In the example a list of cities is iterated and searched for a specific city. If the city is found loop is terminated using a break statement.

public class BreakJava {
  public static void main(String[] args) {
    List<String> cities = Arrays.asList("Beijing", "London", "Santiago", "St. Petersburg", "Helsinki");
    for(String city : cities) {
      if(city.equals("Santiago")) {
        System.out.println("Found city - " + city);
        // terminate loop
        break;
      }                
    }
    System.out.println("Out of for loop");
  }
}

Output

Found city - Santiago
Out of for loop

2- Using break statement to terminate an infinite while loop.

public class BreakJava {
  public static void main(String[] args) {
    int i = 1;
    while(true){
      // terminate loop when i is greater than 5
      //display i's value otherwise
      if(i > 5)
        break;
      System.out.println("i- " + i);
      i++;
    }
  }
}

Output

i- 1
i- 2
i- 3
i- 4
i- 5

3- When break statement is used with nested loops, break statement terminates the innermost loop in whose scope break is used.

public class BreakJava {
  public static void main(String[] args) {
    for(int i = 1; i <= 3; i++){
      System.out.print(i + "- ");
      for(int j = 0; j < 10; j++){
        System.out.print("*");
        // terminate inner loop
        if(j == 6)
          break;
      }
      System.out.println();                   
    }        
    System.out.println("Out of loop");
  }
}

Output

1- *******
2- *******
3- *******
Out of loop

Here break statement is used in the scope of outer loop so outer for loop is terminated.

public class BreakJava {
  public static void main(String[] args) {
    for(int i = 1; i <= 6; i++){
      if(i == 4)
        break;
      System.out.print(i + "- ");
      for(int j = 0; j < 10; j++){
        System.out.print("*");
      }
      System.out.println();                   
    }        
    System.out.println("Out of loop");
  }
}

Output

1- **********
2- **********
3- **********
Out of loop

4- With unlabeled break statement you can come out of the innermost loop. If you want to come out of a deeply nested loop you can use labeled break statement which helps in coming out of more than one blocks of statements.

For example in the following code two for loops are there and labeled break statement helps in coming out of both the loops.

public class BreakJava {

  public static void main(String[] args) {
    int[][] array = { 
      {1, 2, 3 },
      {4, 5, 6 },
      {7, 8, 9 }
    };
    int searchedNum = 5;
    boolean flag = false;
    int i = 0, j = 0;
    // label
    outer:
    for (i = 0; i < array.length; i++) {
      for (j = 0; j < array[i].length; j++) {
        if (array[i][j] == searchedNum) {
          flag = true;
          // lebeled break
          break outer;
        }
      }
    }
    if(flag) {
      System.out.println("Found element " + searchedNum + " at index " + i + " and " + j );
    }else {
      System.out.println("Element " + searchedNum + " not found in the array" );
    }
  }
}

Output

Found element 5 at index 1 and 1

That's all for this topic break Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. if else Statement in Java With Examples
  2. Arithmetic And Unary Operators in Java
  3. this Keyword in Java With Examples
  4. Constructor in Java
  5. Java Abstract Class and Abstract Method

You may also like-

  1. BigInteger in Java
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. Map.Entry Interface in Java
  4. Deadlock in Java Multi-Threading
  5. Selection Sort Program in Java
  6. How to Display Pyramid Patterns in Java - Part1
  7. Python First Program - Hello World
  8. How MapReduce Works in Hadoop

Saturday, June 18, 2022

if else Statement in Java With Examples

To control the execution flow Java programming language provides two types of conditional statements if-else and switch-case statement. In this post we'll talk about Java if and if-else statements in detail along with usage examples.

if-else statement in Java

The Java if statement is used to test a condition and take the execution path based on whether the condition is true or false. There are many combinations in which if statement can be used in Java.

  • if statement
  • if-else statement
  • if-else-if ladder
  • nested if statement

if statement in Java

Syntax of the Java if statement is as follows-

if(condition){
  //statement(s)
}

Here condition is a boolean expression that evaluates to either true or false. If the condition evaluates to true then the block of code enclosed in curly braces is executed. If the condition evaluates to false then the if block is skipped.

If there is only a single statement with in the if condition then the curly braces are optional.

Java if statement flow

if condition java

Java if statement examples

1- Testing a condition to check if passed number is greater than 5 or not.

public class IfDemo {
  public static void main(String[] args) {
    int i = 10;
    if(i > 5) {
      System.out.println("Value of i is greater than 5");
    }
    System.out.println("After if statement");
  }
}

Output

Value of i is greater than 5
After if statement

2- You can also use conditional operators like Conditional-AND (&&) and Conditional-OR (||) to create a condition.

public class IfDemo {
  public static void main(String[] args) {
    int i = 10;
    String test = "Hello";
    if(i > 5 && test.equals("Hello"))
      System.out.println("Inside if");
    System.out.println("After if statement");
  }
}

Output

Inside if
After if statement

Java if-else statement

Syntax of the Java if-else statement is as follows-

if(condition){
  // if block
}else{
  // else block
}

Here condition is a boolean expression that evaluates to either true or false. If the condition evaluates to true then if block is executed. If the condition evaluates to false then the else block is executed.

Java if-else statement flow

if else Java

Java if-else statement examples

public class IfDemo {

  public static void main(String[] args) {
    int i = 10;
    String test = "Hello";
    if(i > 20 && test.equals("Hello")) {
      System.out.println("Inside if");
    }else {
      System.out.println("Inside else");
    }
    System.out.println("After if-else statement");
  }
}

Output

Inside else
After if-else statement

In the example condition fails therefore else block is executed.

Java if-else-if ladder

You can also have an if statement followed by one or more else-if statements and an optional else statement at the end. Each if and else-if statement has a condition and a particular block is executed if the condition associated with that block evaluates to true. If none of the conditions evaluate to true then the else block (if present) is executed.

Syntax of Java if-else-if syntax is as follows-

if(condition1){
  statement(s);
}else if(condition2){
  statement(s);
}else if(condition3){
  statement(s);
}
.
.
.
else{
  statement(s);
}

Java if-else-if examples

Suppose you have requirement to add 10% to amount if amount is greater than 5000.
Add 15% if amount is more than 3000 but less than or equal to 5000.
Add 20% if amount is more than 1000 but less than or equal to 3000.
Otherwise add 25% to the amount.

public class IfDemo {
  public static void main(String[] args) {
    int amount = 5000;
    if(amount > 5000) {
      // add 10%
      amount = amount + (amount*10/100);
    }else if (amount > 3000 && amount <= 5000) {
      // add 15%
      amount = amount + (amount*15/100);
    }else if (amount > 1000 && amount <= 3000) {
      // add 20%
      amount = amount + (amount*20/100);
    }else {
      //add 25%
      amount = amount + (amount*25/100);
    }
    System.out.println("Amount is- " + amount);
  }
}

Output

Amount is- 5750

Java nested if-else statements

It is possible to have an if-else statement inside a if-else statement in Java. It is known as a nested if-else statement.

public class IfDemo {

  public static void main(String[] args) {
    int amount = 8000;
    if(amount > 5000) {
      if(amount > 7000 && amount <=10000) {
        amount = amount + (amount*10/100);
      }else {
        amount = amount + (amount*5/100);
      }    
    }else {
      if (amount > 3000 && amount <= 5000) {
        amount = amount + (amount*15/100);
      }else {
        amount = amount + (amount*20/100);
      }
    }
    System.out.println("Amount is- " + amount);
  }
}

Output

Amount is- 8800

That's all for this topic if-else Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java for Loop With Examples
  2. Equality And Relational Operators in Java
  3. String in Java Tutorial
  4. static Block in Java
  5. Marker Interface in Java

You may also like-

  1. finally Block in Java Exception Handling
  2. BigDecimal in Java With Examples
  3. How to Loop or Iterate an Arraylist in Java
  4. Java Collections Interview Questions And Answers
  5. Producer-Consumer Java Program Using ArrayBlockingQueue
  6. How to Convert String to Date in Java
  7. Operator Overloading in Python
  8. Data Access in Spring Framework

Tuesday, June 14, 2022

Java do-while Loop With Examples

In Java programming language there are three types of loops- do-while loop, while loop, and for loop. In this post we’ll learn about do-while loop in Java along with usage examples.

do-while loop in Java

A do-while loop in Java repeatedly executes a statement or a block of statements while the given condition is true. Java do-while loop is similar to while loop except that the condition in do-while loop is evaluated after the loop body is executed.

Syntax of the do-while loop in Java is as follows-

 
do {
  // loop body
} while (condition);

In do-while loop condition that controls the loop is at the bottom of the loop so the loop always executes at least once where as in while loop if condition evaluates to false at the first time itself then the loop body is not executed at all.

Java do while loop execution flow

Java do while loop examples

1- Using do-while loop to print numbers 1..5.

 
public class DoWhileDemo {
  public static void main(String[] args) {
    int i = 1;
    do {
      System.out.println(i);
    } while (++i <= 5);
  }
}

Output

 
1
2
3
4
5

2- Since do-while loop is executed at least once so this loop is a good choice if you want to present a simple menu to the user, because you will definitely want menu to be displayed at least once.

public class DoWhileDemo {
  public static void main(String[] args) throws IOException {
    Scanner sc = new Scanner(System.in);
    int choice;
    do {
      System.out.println("----Language Menu----: ");
      System.out.println(" 1. Java");
      System.out.println(" 2. Python");
      System.out.println(" 3. C#");
      System.out.print("Enter your preferred language (1-3): ");
      choice = sc.nextInt();
      //while choice is not between 1..3 be in the loop
    } while( choice < 1 || choice > 3);
    sc.close();
    switch(choice) {
      case 1:
        System.out.println("Preferred Language- Java");            
        break;
      case 2:
        System.out.println("Preferred Language- Python");
        break;
      case 3:
        System.out.println("Preferred Language- C#");
        break;
    }
  }
}

Output

 
----Language Menu----: 
 1. Java
 2. Python
 3. C#
Enter your preferred language (1-3): 5
----Language Menu----: 
 1. Java
 2. Python
 3. C#
Enter your preferred language (1-3): 1
Preferred Language- Java

As you can see when 5 is entered, loop is repeated only when the choice is between 1..3 loop is terminated.

That's all for this topic Java do-while Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Arithmetic And Unary Operators in Java
  2. if else Statement in Java With Examples
  3. Type Wrapper Classes in Java
  4. static Keyword in Java With Examples
  5. Array in Java With Examples

You may also like-

  1. try-catch Block in Java Exception Handling
  2. Type Casting in Java With Conversion Examples
  3. ArrayList in Java With Examples
  4. How HashSet Works Internally in Java
  5. AtomicLong in Java With Examples
  6. Python First Program - Hello World
  7. Spring Bean Life Cycle
  8. What is Big Data

Monday, May 16, 2022

Switch Case Statement in Java With Examples

Switch case statement is Java's decision statement which can have a number of possible execution paths. It provides an easy and more readable way to execute a set of code based on the value of the expression. For another decision statement if-else in Java you can refer this post- if else Statement in Java With Examples


General form of switch statement in Java

switch (expression) {
 case value1:
  // statement
  break;
 case value2:
  // statement
  break;
 .
 .
 .
 case valueN :
  // statement
  break;
 default:
  // default statement
}

In Java 12 Switch statement has been extended to be used as either a statement or an expression. Read more about switch expressions here- Switch Expressions in Java 12

Execution path of Java switch statement

When a value is passed in the switch expression it is compared with the value of each case statement, if match is found the code following that case statement is executed. Code execution, with in the case statement, is terminated when the break statement is encountered. As soon as the break statement is encountered no other case statement is executed and control comes out of the switch case statement.

If none of the values in the case statement matches the value of the expression then the default statement is executed. Note that default statement is not mandatory though. If none of the values in the case statement matches the value of the expression and default statement is also not there then control will come out of the switch-case statement executing nothing.

It is not mandatory to have break statement in every case statement, in case break statement is omitted in any case statement, next case statement will also be executed even though it doesn't match the value of the expression. That can be used to group a set of case statements but omission due to negligence will result in execution of several case statements in place of a single matching one. See example for more clarity.

Rules for using Java switch statement

  1. Switch statement works with byte,short, char, and int primitive data types and their wrapper classes Character, Byte, Short, and Integer. It works with Java enum too. Starting Java 7 it also works with String in Java.
  2. Switch case statement can only be used for equality test. No other boolean expression like greater than, not equal to etc. can be used with switch statement.
  3. Value of the case statement can only be a constant expression. Variable is not allowed.
  4. Duplicate case values are not allowed, each case statement should have a unique value.
  5. Type of each case value must be compatible with the type of expression.
  6. default statement is not mandatory in Java switch statement.
  7. break statement is also not mandatory. Leaving break statement with in a case statement will result in the execution of the next case statement.
  8. From Java 7 string class can also be used with Switch-Case statement in Java.

Java Switch-case statement example

public class SwitchCaseDemo {
 public static void main(String[] args) {
  int month = 7;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is December"); 
   break;
  }
 }
}

Output

Month is July

Here month expression has the value 7 so it will go to the case statement which has value 7 and execute the statements with in that case statement and then break out.

Note that default statement is not used in this code.

Java Switch-case statement example with default

Let us change this example to pass month as 13 and have a default statement to encounter such cases.

public class SwitchCaseDemo {
 public static void main(String[] args) {
  int month = 13;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is December"); 
   break;
   default: System.out.println("Invalid month value passed");
  }
 }
}

Output

Invalid month value passed

Java Switch statement example omitting break statement

As stated above break statement is not mandatory but it will result in fall-through i.e. execution of the following case statements until the break statement is encountered or the statement ends.

public class SwitchCaseDemo {
 public static void main(String[] args) {
  int month = 7;
  
  switch(month){
   case 1: System.out.println("Month is January");
   
   case 2: System.out.println("Month is February"); 
   
   case 3: System.out.println("Month is March"); 
   
   case 4: System.out.println("Month is April"); 
   
   case 5: System.out.println("Month is May"); 
   
   case 6: System.out.println("Month is June"); 
   
   case 7: System.out.println("Month is July"); 
   
   case 8: System.out.println("Month is August"); 
   
   case 9: System.out.println("Month is September"); 
   
   case 10: System.out.println("Month is October"); 
   
   case 11: System.out.println("Month is November"); 
   
   case 12: System.out.println("Month is December"); 
   
   default: System.out.println("Invalid month value passed");
  }
 }
}

Output

Month is July
Month is August
Month is September
Month is October
Month is November
Month is December
Invalid month value passed

In the above switch case statement break is not used with any case statement. Since month passed is 7 so control will go to the case statement having value 7 and start executing the code with in that case statement but it won't know when to break so all the following case statements (even default) are executed.

Java Switch statement example grouping cases

Case statements can be grouped by omitting the break statement. For example, if you want to display the quarter passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

public class SwitchCaseDemo {
 public static void main(String[] args) {
  int month = 5;
  
  switch(month){
   case 1:   
   case 2:   
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4:   
   case 5:    
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:   
   case 8:   
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:     
   case 11:    
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }
 }
}

Output

Quarter 2

Using Strings in Java switch Statements

In Java SE 7 and later, you can use a String object in the switch statement's expression.

 
public class StringSwitchDemo {

 public static void main(String[] args) {
  String dept = "Human Resources";
  String deptCd = null;
  switch(dept.toLowerCase()){
   case "account": 
    deptCd = "acct";
    break;
   case "human resources": 
    deptCd = "hr";
    break;
   case "administration":
    deptCd = "admin";
    break;
   default: System.out.println("Invalid deprtment");
  }
  System.out.println("Department - " + deptCd);
 }
}

Output

Department – hr

Nested switch statements in Java

You can have nested switch-case statement in Java with in the outer switch statement.

switch(month){
 case 1:
 switch(week){
  case 1: .....
         break;
  case 2 : ....

  ...
  ...
 }
 break;
}

Java Switch-case statement efficiency

If you have to make a choice between sequence of if-else statement and switch-case statement opt for switch case as it will run faster.

Reason being when the Java compiler compiles a switch-case statement it will go through all the case statement values (which are constants) and make a jump table. The value on which the switch is being performed is used as an index into the jump table to directly go to that case statement. In the case of switch-case statement it can be done as compiler knows that case values are all of same type and switch expression can only be used for equality test with case values.

That's all for this topic Switch Case Statement in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Ternary Operator in Java With Examples
  2. instanceof Operator in Java With Examples
  3. BigDecimal in Java With Examples
  4. String in Java Tutorial
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Java Pass by Value or Pass by Reference
  2. Constructor Overloading in Java
  3. Abstraction in Java
  4. Multi-Catch Statement in Java Exception Handling
  5. How HashMap Works Internally in Java
  6. Fail-Fast Vs Fail-Safe Iterator in Java
  7. Java Semaphore With Examples
  8. AtomicInteger in Java With Examples

Tuesday, May 3, 2022

Java for Loop With Examples

In Java programming language there are three types of loops- for loop, while loop and do while loop. In this post we’ll learn about for loop in Java along with usage examples.

for loop in Java

In Java there are two forms of for loop.

  1. Traditional for loop– Available from the beginning.
  2. Enhanced for loop (for-each loop)- Added in Java 5.

Syntax for traditional for loop in Java

Syntax of the traditional for loop is as follows-

 
for(initialization; condition; increment\decrement) {
  // loop body
}

Statements that are part of loop body are enclosed with in curly braces. If there is only one statement with in a for loop then curly braces are optional.

It is not mandatory to do initialization and increment\decrement with in the for loop statement.

There are three parts in a for loop-

  1. Initialization– Initialization step is used to set the initial value of the variable which controls the for loop. Initialization is the first step in for loop execution and it is executed only once. The initilized variable is later incremented or decremented in the increment\decrement step of the loop.
  2. Condition– Condition is a boolean expression that is evaluated in each iteration. If condition is true then the loop body is executed, if condition is false then the loop terminates.
  3. Increment\decrement– The variable that controls the loop is incremented or decremented in this step.

Java for loop execution flow

Flow of the for loop can be explained using the following flow chart.

Java for loop

Java for loop examples

1- Using for loop to print numbers 1..5.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    for(int i = 1; i <=5; i++){
      System.out.println(i);
    }
  }
}

Output

 
1
2
3
4
5
  1. In the initialization part of for loop statement, variable i is declared and initialized to 1.
  2. Condition part (i <= 5) is evaluated in each iteration, returning true if value of i is less than or equal to 5 and returning false when value of i becomes greater than 5 and the condition evaluates to false which terminates the for loop.
  3. Third part of the for loop increments the variable i.

2- Using for loop in Java to print table of 7.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int number = 7;
    for(int i = 1; i <=10; i++){
      System.out.println(number + " X " +i + " = " + (i*7));
    }
  }
}

Output

 
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

3- Using for loop to print numbers in reverse order 5..1

 
public class ForLoopDemo {
  public static void main(String[] args) {
    for(int i = 5; i > 0; i--){
      System.out.println(i);
    }
  }
}

Output

 
5
4
3
2
1

In this example value of i is decremented in the increment\decrement part.

4- As already stated it is not mandatory to do initialization and increment\decrement as part of for loop statement. Previous example of printing number in reverse order can also be written as follows.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int i = 5;
    for(; i > 0;){
      System.out.println(i);
       i--;
    }
  }
}

Output

 
5
4
3
2
1

As you can see in this example initialization and increment/decrement part is done outside the for loop statement but you still need semicolons with in the for loop statement.

Java for-each loop (Enhanced for loop)

for-each loop or enhanced for loop is available Java 5 onward. This version of for loop is used to iterate a collection of objects like an array, list or set sequentially.

Java for-each loop syntax

 
for(type var : collection){
  //loop body
}
  • type specifies the type of the elements in the collection.
  • var is assigned the next element from the collection in each iteration.
  • collection is the Collection that is iterated.

Java for-each loop examples

1- Using for-each loop to iterate an ArrayList and displaying its elements.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    List<String> avengers = new ArrayList<String>();
    avengers.add("Iron Man");
    avengers.add("Captain America");
    avengers.add("Hulk");
    avengers.add("Thor");
    avengers.add("Black Widow");
    avengers.add("Hawkeye");        
    for(String avenger : avengers){
      System.out.println(avenger);
    }
  }
}

Output

 
Iron Man
Captain America
Hulk
Thor
Black Widow
Hawkeye

2- Iterating an array using for-each loop and finding the max element in the array.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int arr[] = {6, 7, 34, -23, 45, 48, 9, 4, 10, 21};
    int max = 0;
    for(int number: arr) {
      if(number > max)
        max = number;
    }
    System.out.println("Max elements in the array- " + max);        
  }
}

Output

 
Max elements in the array- 48

Nested for loop in Java

You can have a for loop (or any other loop) inside another for loop, such loops are known as nested loops.

In a nested for loop, for each iteration of the outer for loop, inner for loop is iterated until the condition in the inner for loop evaluates to false.

Java Nested for loop example

If you want to display the following pyramid pattern in Java.

 
     1
    1 2
   1 2 3
  1 2 3 4
 1 2 3 4 5
1 2 3 4 5 6
 
import java.util.Scanner;
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - "); 
    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    // Outer for loop
    for(int i = 1; i <= num; i++){
      // this nested loop prints the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop prints the number
      for(int k = 1; k < i; k++){
        System.out.print(k + " ");
      }
      System.out.println();
    }            
  }
}

That's all for this topic Java for Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch Case Statement in Java With Examples
  2. Conditional Operators in Java
  3. Object Creation Using new Operator in Java
  4. Java Pass by Value or Pass by Reference
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Ternary Operator in Java With Examples
  2. Constructor in Java
  3. How to Format Date in Java Using SimpleDateFormat
  4. Linked List Implementation Java Program
  5. How to Loop Through HashSet in Java
  6. Creating a Thread in Java
  7. Python Conditional Statement - if, elif, else Statements
  8. Dependency Injection in Spring Framework

Friday, March 4, 2022

Java while Loop With Examples

In Java programming language there are three types of loops- while loop, do while loop and for loop. In this post we’ll learn about while loop in Java along with usage examples.

while loop in Java

While loop repeatedly executes a statement or a block of statements while its condition is true.

Syntax of the while loop in Java is as follows-

 
while (condition) {
  // loop body
}

Here condition is a boolean expression that evaluates to either true or false.

while loop body is repeatedly executed as long as the conditional expression is true. When condition evaluates to false, control comes out of the loop. The curly braces are not necessary if loop body consists of a single statement.

Java while loop execution flow

while loop in Java

Java while loop examples

1- Using while loop to print numbers 1..5.

 
public class WhileLoopDemo {
  public static void main(String[] args) {
    int i = 1;
    while(i <= 5){
      System.out.println(i);
      i++;
    }
  }
}

Output

 
1
2
3
4
5

The condition (i <= 5) is evaluated first in the while loop if it’s true loop body is executed and in each iteration condition is evaluated to verify whether it is true or false.

In the loop body value of i is incremented by 1 in each iteration so that the condition eventually evaluates to false when i is greater than 5.

2- Using while loop in Java to print table of 7.

 
public class WhileLoopDemo {
  public static void main(String[] args) {
    int number = 7;
    int i = 1;
    while(i <= 10){
      System.out.println(number + " X " +i + " = " + (i*7));
      i++;
    }
  }
}

Output

 
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

Java while loop with no loop body

You can have a while loop with no loop body. Consider the following example where while loop is repeated as long as i is not greater than 10.

 
public class WhileLoopDemo {
  public static void main(String[] args) {
    int i = 1;
    while(!(++i > 10));
    System.out.println("Value of i- " + i);
  }
}

Output

 
Value of i- 11

Infinite while loop

Since while loop is evaluated as long as the condition remains true so you can have an infinite while loop by using condition as true. Consider the following example which has to be terminated manually to come out of an infinite while loop.

 
public class WhileLoopDemo {
  public static void main(String[] args) {
    while(true){
      System.out.println("This is an infinite while loop");
    }
  }
}

Usually you use such an infinite while loop with a break statement along with a condition to break out of loop.

 
public class WhileLoopDemo {
  public static void main(String[] args) {
    int i = 1;
    while(true){
      i++;
      // condition to break out of loop
      if(i > 20)
        break;
    }
    System.out.println("Value of i- " + i);
  }
}

Output

 
Value of i- 21

Same program can also be written using a boolean flag to control the while loop.

 
public class WhileLoopDemo {
  public static void main(String[] args) {
    boolean flag = true;
    int i = 1;
    while(flag){
      i++;
      // condition to turn flag to false
      if(i > 20)
        flag = false;
    }
    System.out.println("Value of i- " + i);
  }
}

Output

 
Value of i- 21

That's all for this topic Java while Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Ternary Operator in Java With Examples
  2. Difference Between equals() Method And equality Operator == in Java
  3. Why no Multiple Inheritance in Java
  4. Package in Java
  5. Class in Java

You may also like-

  1. this Keyword in Java With Examples
  2. Java Exception Handling Tutorial
  3. StringBuffer Class in Java With Examples
  4. How HashMap Internally Works in Java
  5. Race Condition in Java Multi-Threading
  6. Factorial Program in Java
  7. Magic Methods in Python With Examples
  8. Spring JavaConfig Example Program