How 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!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
