Java variable
From low to high:
Byte, short, char-> int -> long -> float -> double
Cast: from high level to low one, e.g.,
int i = 128
byte b = (byte)i
//output b = -128 memory overflow
Notes:
boolean value is unconversionable
cast may lead to memory overflow, e.g.,
int money = 10_0000_0000; // JDK new feature: numbers can be separted by "_"
int year = 20;
int total = money*year; // memory overflow
//solution:
long total = money*((long)year);
Java variable
While define a vairable:
type
name
value
String temp = "Java"
Local variable
Declaring and initializing values
Instance variable
Declaring in the class
If there is no initilizing values, it will return defualt value (boolean:false, basic types: 0, other type: null)
Example for using instance variable
public class Demo05 {
String i1;
int i2;
public static void main(String[] args) {
Demo05 instanceVariable = new Demo05();
System.out.println(instanceVariable.i1);//out null
}
}
Class variable (e.g., static)
Can be used in another function
Constant
pulic class Demo{
static final pi = 3.14
final static pi = 3.14
public static void main(String[] args){
System.output.println(pi)
}
}
// No order requirement
// They are identical
Variable specification
Class variable: monthSalary (hump principle)
Local variable: start with lower case and hump principle
Constant: upper case and underscore e.g., MAX_VALUE
Class name: start with upper case e.g., Demo01
public class Demo01{
}
Comments
Post a Comment