Java Tutorial/Language/Variables — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:06, 1 июня 2010
Содержание
Demonstrate lifetime of a variable
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);
}
}
}
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:
public class MainClass
{
public static void main(String[] args)
{
String helloMessage;
helloMessage = "Hello, World!";
System.out.println(helloMessage);
}
}
shows the proper way to declare a class variable named helloMessage
public class MainClass
{
static String helloMessage;
public static void main(String[] args)
{
helloMessage = "Hello, World!";
System.out.println(helloMessage);
}
}
Variable Dynamic Initialization
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);
}
}
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.
public class MainClass
{
public static void main(String[] args)
{
helloMessage = "Hello, World!";
System.out.println(helloMessage);
}
static String helloMessage;
}