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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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...

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.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles