Skip to content

Instantly share code, notes, and snippets.

@rajeevprasanna
Created January 18, 2014 18:10
Show Gist options
  • Save rajeevprasanna/8494041 to your computer and use it in GitHub Desktop.
Save rajeevprasanna/8494041 to your computer and use it in GitHub Desktop.
Examples of different variable types in java
package variableTypes;
public class InstanceVariables {
public int mCost;//manage outside class access using access modifiers.
//Default public constructor
public InstanceVariables(){}
public InstanceVariables(int profit){
int cost = profit + 30;//cost is a local variable which is initialized during declaration only.
mCost = cost;
System.out.println("local variable cost => "+ cost);
}
public void getDogDetails() {
int age = 0;//Local variable must be initialized before use
age = age + 7;
System.out.println("Dog age is : " + age);
//Local variable
for(int i=0;i<3;i++){ //i is a local variable
System.out.println("printing local variable. i => "+i);
}
}
public static void main(String args[]) {
InstanceVariables test = new InstanceVariables();
test.getDogDetails();
//instance variables are accessed using InstanceName.variableName.
System.out.println("Accessing instance variable without setting its value. So it prints default value. mcost => " + test.mCost);
InstanceVariables test2 = new InstanceVariables(100);
System.out.println("Accessing instance variable after setting its value through construcot initialization. mcost => " + test2.mCost);
//Here test and test2 are local variables.
}
}
package variableTypes;
public class LocalVariables {
//Default public constructor
public LocalVariables(){}
public LocalVariables(int profit){
int cost = profit + 30;//cost is a local variable which is initialized during declaration only.
System.out.println("local variable cost => "+ cost);
}
public void getDogDetails() {
int age = 0;//Local variable must be initialized before use
age = age + 7;
System.out.println("Dog age is : " + age);
//Local variable
for(int i=0;i<3;i++){ //i is a local variable
System.out.println("printing local variable. i => "+i);
}
}
public static void main(String args[]) {
LocalVariables test = new LocalVariables();
test.getDogDetails();
LocalVariables test2 = new LocalVariables(100);
//Here test and test2 are local variables.
}
}
package variableTypes;
public class StaticVariables {
//fixing cost of the dog as 30$ irrespective of dog type.
public static final int mCost = 30;
public static void main(String args[]) {
//static variables are accessed using className.staticVariableName.
System.out.println("Accessing static variable directly with class name. mcost => " + StaticVariables.mCost);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment