Java Tutorial/Language/Variables
Содержание
Demonstrate lifetime of a variable
<source lang="java">
public class MainClass {
public static void main(String args[]) { int x; for (x = 0; x < 3; x++) { int y = -1; // y is initialized each time block is entered System.out.println("y is: " + y); // this always prints -1 y = 100; System.out.println("y is now: " + y); } }
}</source>
y is: -1 y is now: 100 y is: -1 y is now: 100 y is: -1 y is now: 100
helloMessage variable is declared as a local variable:
<source lang="java">
public class MainClass {
public static void main(String[] args) { String helloMessage; helloMessage = "Hello, World!"; System.out.println(helloMessage); }
}</source>
shows the proper way to declare a class variable named helloMessage
<source lang="java">
public class MainClass {
static String helloMessage; public static void main(String[] args) { helloMessage = "Hello, World!"; System.out.println(helloMessage); }
}</source>
Variable Dynamic Initialization
<source lang="java">
public class MainClass {
public static void main(String args[]) { double a = 3.0, b = 4.0; // c is dynamically initialized double c = Math.sqrt(a * a + b * b); System.out.println("Hypotenuse is " + c); }
}</source>
Hypotenuse is 5.0
Variables
Variables are data placeholders. There are two data types in Java:
- Reference types provides a reference to an object.
- Primitive types hold a primitive.
You don"t have to place class variable declarations at the beginning of a class.
<source lang="java">
public class MainClass {
public static void main(String[] args) { helloMessage = "Hello, World!"; System.out.println(helloMessage); } static String helloMessage;
}</source>