search
HomeJavajavaTutorialHow to use Java block scope, conditional statements and switch statements

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);
	}
}

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);
	}
}

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里面的语句,直接跳过执行外面的语句。
	}
}

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。
	}
}

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); 
	}
}

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;
		}
	}
}

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

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function