Home > Java > javaTutorial > body text

In Java, initialize local variables in conditional block

WBOY
Release: 2023-08-22 13:53:07
forward
1391 people have browsed it

In Java, initialize local variables in conditional block

The Java compiler does not allow uninitialized local variables to be discarded. When a local variable is initialized inside a conditional block, the following three situations may happen:

  • If a value is provided in the conditional block and the given condition is true, the code compiles successfully.

  • If a variable (instead of a value) is provided in a conditional block and the condition is true, the code will give a compilation error.

  • If the condition that needs to be checked is false, the code will have a compilation error.

If local variables are initialized to default values ​​outside the code's conditional block, no errors will occur and the code will compile successfully.

Example

Demonstration

public class Demo{
   public static void main(String args[]){
      int i = 35;
      int j = 0;
      if (i > 32){
         j = i + 11;
      }
      System.out.println("The value is: " + j);
   }
}
Copy after login

Output

The value is: 46
Copy after login

A class named Demo contains the main function. Here, two variables are defined, if one variable is greater than a specific number, the other value is added to it, and the ‘if’ block is closed. Then, print the results on the console.

The above is the detailed content of In Java, initialize local variables in conditional block. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template