- Variables are locations where the data is stored when program execute.
- It refers to memory location.
- You should follow the variable naming rules before type a name, Go to Java naming standards post.
- There are two major types of variables in java.
Primitive
- Numeric (integer and floating point)
- Single character
- Boolean (true/false)
- Strings
- Dates
- Everything else
Another types of declaration of variables
1. Instance variables (Non-static variable)2. Class variables (Static variables)
3. Local variables
public class Apple{
int x = 10; // Instance variable
static int y = 20; // static variables
public static void main(String args[]){
byte z=5; // local variables
}
}
Instance variable
- This variables are declared in a class, but outside of any block.
- These are visible for all method, constructor and any block in the class.
- If you are using instance variable in non-static field, you have to call it through object.
- We will learn how to create objects in next posts. Here is a example.
- Value is depend on the object which is created.
class Apple{
int x = 10; // Instance variable
public static void main(String args[]){
Apple obj = new Apple(); // create obj object
System.out.println(obj.x);
/*System.out.println(x); this will give a compile time error */
}
}
Class variables (Static variables)
- This variable declared with a ‘static’ keyword.
- This variables are start with program start and destroy when program stops.
- Can be accessed with class name.
- Values depend on the class.
class Apple{
static float x = 10.5f;
static String s = "ryjskyline";
public static void main(String args[]){
System.out.println(Apple.x);
System.out.println("-------------------");
System.out.println(x);
System.out.println("-------------------");
System.out.println(s); // Apple.s is also correct
}
}
Local variable
- Local variable are declared in method, constructors of any other block.
- This type of variable destroy once it exits the method, constructor or block.
- Access modifiers can’t be used for local variables.
- This variable does not initialize to default values.
- Local variables should be explicitly assigning value.
public class Apple{
public static void main(String args[]){
int x =10;
System.out.println(x);
}
}
Java variables
Reviewed by Ravi Yasas
on
2:41 AM
Rating:
Reviewed by Ravi Yasas
on
2:41 AM
Rating:

No comments: