Table of Contents
Block Scope
Conditional statements
Format 2
Format 3 (commonly used)
switch statement
Home Java javaTutorial How to use Java block scope, conditional statements and switch statements

How to use Java block scope, conditional statements and switch statements

May 15, 2023 pm 02:58 PM
java switch

Block Scope

Before learning the control structure in depth, you must first understand the role of blocks.

Definition: A statement composed of multiple Java statements, enclosed by a pair of curly brackets.

Function: The block determines the scope of the variable, and one block can be nested on another block.

Example:

package decom1;
public class cuowu {
	public static void main(String[] args) {  //第二个块嵌套在第一个块里面。
		byte i = 12;                 //变量i只在第二个块区域内有作用包括嵌套里面的块。
		{                            //第三个块嵌套在第二个块里面同时也在第一个块里面。
			int a = 3;               //变量a只在所在的块起到作用。
			System.out.println(a);
		}                            //写在main(程序执行的入口)里面的代码块,就称为局部代码块。
		                             //局部代码的作用:能够让变量更早的在内存中消失,节省内存空间。
		System.out.println(i);
	}
}
Copy after login

Variables with the same name cannot be declared in two nested blocks.

Example:

package decom1;
public class cuowu {
	public static void main(String[] args) {
		byte i = 12;
		{
			int i = 3;      //报错:Duplicate local variable i	
		}
		System.out.println(i);
	}
}
Copy after login

Conditional statements

Conditional statements have three formats. Let me decipher which three formats are below.

Format 1

if (conditional expression) { statement body; }

The expression form of conditional statements in Java:

if(condition) statement

The conditions here must be enclosed in parentheses.

The final result of the conditional expression can only be of boolean type, either true or false.

Process:

1. If the program executes the if statement, it will see whether the result of the conditional expression is true or false.

2. If it is true, it will enter the if and execute the statement body content inside.

3. If it is false, it will not enter the if and the content of the statement body inside will not be executed.

package com;
public class liu {
	public static void main(String[] args) {
		int i = 1;
		int j = 2;
		if(i > j) {
			System.out.println(i);
		} 
			System.out.println(j);  //由于i>j不成立,所以不执行if里面的语句,直接跳过执行外面的语句。
	}
}
Copy after login

Format 2

if (conditional expression){ statement body; }else{ statement body; }

Statement expression form:

if(condition) statement1 else statement2

Execution process:

1. If the program executes the if statement, it will look at the conditional expression The result is true or false.

2. If it is true, it will enter the if and execute the statement body content inside.

3. If it is false, it will not enter if, but will enter else and execute the statement body inside.

Example:

package com;
public class liu {
	public static void main(String[] args) {
		//获取两个数的较大值
		int i = 1;
		int j = 2;
		int max = 0;
		if(i > j) {
			max = i;  //把i赋值给max
		} else {
			max = j;  //把j赋值给max
		}
		System.out.println(max);  //因为i>j条件为假,所以执行else里面的语句,所以max得到的数值为2。
	}
}
Copy after login

Format 3 (commonly used)

if (conditional expression){ statement body; }else if{ statement body; }…else {Statement body;}

Statement expression form:

if…else if…

Execution process:

1. If the program executes the if statement, it will check whether the result of the conditional expression is true or false.

2. If it is true, the statement body content in if will be executed, and other statement bodies will not be executed.

3. If it is false, it will continue to go down to see whether the result of the conditional expression of else if is true or false.

4. If it is true, enter elseif and execute the statement body content inside.

5. If it is false, continue going down...

6. If the conditional expressions in if and all elseif are false, the statement body in else will be executed. content.

Example:

package com;
public class liu {
	public static void main(String[] args) 
		int a = 0;
		int i = 7;
		if(i > 8) {
			a = 1;
		} else if(i > 7) {
			a = 2;
		} else if(i > 6) {
			a = 3;
		} else {
			a = 4;
		}
		System.out.println(a); 
	}
}
Copy after login

switch statement

The if conditional statement is obviously a bit clumsy when dealing with multiple options. At this time, there are new ways to play, why not? ? Next I will introduce the switch statement.

Let’s talk about the structure in an example. Let’s talk about the execution process:

1. When the program executes the switch, it will enter the switch and find the first case for matching. If it matches If successful, enter the case for execution.

2. The content of the statement body and break inside. If there is no successful match, it will continue to go down and find the second case to continue matching...

3. If all cases do not match, the statement body content in default will be executed finally.

Instance:

package com;
public class liu {
	public static void main(String[] args) {
		int i = 3;
		switch(i) {   
			case 1:
				System.out.println("1");
				break;
			case 2:
				System.out.println("2");
				break;
			case 3:
				System.out.println("3");  //i=3符合case 3所以就执行case里面的命令,其余语句则不管。
				break;
			default:
				System.out.println("3");
				break;
		}
	}
}
Copy after login

case tag:

  • Constant expression of type char, byte, short or int.

  • Enumeration constant.

  • Starting from Java 7, case tags can be string literals.

Character constant example:

String input....
switch (input.tolowerCase())
{
	case "yes":
		...
		break;
		...
}
Copy after login

Warning: If there is no break statement at the end of the case branch statement, the next case branch statement will be executed.

If you tend to forget this, you can add this statement in front. In this way, if there is a break missing after the case, an error will be prompted during compilation.

javac -Xlint:fallthrough Test.java

switch end flag:

1.break

2.Encounter the end }

The above is the detailed content of How to use Java block scope, conditional statements and switch statements. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

Avoid errors caused by default in C switch statements Avoid errors caused by default in C switch statements Apr 03, 2025 pm 03:45 PM

A strategy to avoid errors caused by default in C switch statements: use enums instead of constants, limiting the value of the case statement to a valid member of the enum. Use fallthrough in the last case statement to let the program continue to execute the following code. For switch statements without fallthrough, always add a default statement for error handling or provide default behavior.

Best practices for C language default Best practices for C language default Apr 03, 2025 pm 03:48 PM

The best practices of default in C language: place it at the end of the switch statement as the default processing for unmatched values; it is used to handle unknown or invalid values ​​to improve program robustness; avoid duplication with case branches to maintain conciseness; comment clearly on the purpose of the default branch to improve readability; avoid using multiple defaults in one case to maintain clarity; keep the default branch concise and avoid complex operations; consider using enumeration values ​​as case conditions to improve maintainability; in large switch statements, use multiple default branches to handle different situations.

See all articles