Java Tutorial/Statement Control/Statement
Содержание
- 1 An Overview of Java Statements
- 2 Combining both statements into one
- 3 Declaring and defining multiple variables in a single statement
- 4 Expressions
- 5 How to write multiple assignments in a single statement
- 6 Label a statement block
- 7 Spreading a single declaration over several lines
- 8 Statement Blocks
An Overview of Java Statements
- In programming, a statement is an instruction to do something.
- It controls the sequence of execution of a program.
- In Java, a statement is terminated with a semicolon and multiple statements can be written on a single line.
x = y + 1; z = y + 2;
Combining both statements into one
class Animal {
public Animal(String aType) {
type = aType;
}
public String toString() {
return "This is a " + type;
}
private String type;
}
public class MainClass {
public static void main(String[] a) {
System.out.println(new Animal("a").getClass().getName()); // Output the
// class name
}
}
Animal
Declaring and defining multiple variables in a single statement
A comma separates each variable.
public class MainClass{
public static void main(String[] arg){
long a = 999999999L, b = 100000000L;
int c = 0, d = 0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
999999999 100000000 0 0
Expressions
Some expressions can be made statements by terminating them with a semicolon. For example, x++ is an expression. However, this is a statement:
x++;
Statements can be grouped in a block. A block is a sequence of the following programming elements within braces:
- statements
- local class declarations
- local variable declaration statements
How to write multiple assignments in a single statement
public class MainClass{
public static void main(String[] argv){
int a, b, c;
a = b = c = 777;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
777 777 777
Label a statement block
- A statement and a statement block can be labeled.
- Label names follow the same rule as Java identifiers and are terminated with a colon.
public class MainClass {
public static void main(String[] args) {
int x = 0, y = 0;
sectionA: x = y + 1;
}
}
Label statement can be referenced by the break and continue statements.
Spreading a single declaration over several lines
public class MainClass {
public static void main(String[] arg) {
int a = 0, // comment for a
b = 0, // comment for b
c = 0, // comment for c
d = 0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
Statement Blocks
- You can have a block of statements enclosed between braces.
- If the value of expression is true, all the statements enclosed in the block will be executed.
- Without the braces, the code no longer has a statement block.
public class MainClass {
public static void main(String[] arg) {
int a = 0;
if (a == 0) {
System.out.println("in the block");
System.out.println("in the block");
}
}
}
in the block in the block