Skip to main content

Java Variables

In programming language variables are used to deal with the memory locations. Generally programmer is define behaviour of variable. Such as what type of value are stored by variable in on memory location (data type of variable). And data type is decide the size of variables. This process are applied when compile source code by compiler. And allocation of memory is while running of program. So variable is provide a interface to get and set value of this allocated memory place.

Here include few example to declare variables in java programming.

//declaring integer variable
int age;

//declaring float variable 
float salary;

//declaring string variable
String name;

Name of identifier are should be start with on character. And that cannot contain whitespace and and special symbols. We can use underscore and numbers. As naming conversion we can define variable name in camelcase format.

Note that when define of a variable in java programming there are need to specify which type of value will be store by variable in memory place. And variable are capable to store value by it's data type. In this example defined of three different variables. So how to assign value of variable, that is are very simple.

Assign the value of variable by using = (equal to) operator.

//Assign variable value and display variable value
public class Example{
   
  public static void main(String[] args) {
    //age is an integer variable
    int age=22; //assign 22 
    //name is an String variable
    String name="Foo"; //assign Foo string
    //salary is an float variable 
    float salary=150000.90f; //assign 150000.90

    //display variable value
    System.out.println(" Name :"+name);
    System.out.println(" Age  :"+age);
    System.out.println(" Salary :"+salary);
  }
}
 Name :Foo
 Age  :22
 Salary :150000.9

We can define similar data type variable into single statement. where are separate by comma and also can assign value of variables.

//Combining declarations and initializing

//Declaration of integers variables
int x=10,y,z=100;// assign x and z variable value  

//Define float variables
float salary,amount=10000.33;

Note that we can declare two different type variable into single declaration. In this situation we can declare new statement and define. In this example int and float are two different data type.

Type of Variables

Variable are three type in Java programming. Such as Local, static and instance types.

Local Variables : This type of variables are defined by inside a function, In parameter list of function and inside a block. The scope of this variable is block level this can't use outside of this scope. Note that we can pass variable value to another function.

//Example in Local Variables
public class LocalVariables{

    public static int testSum(int x,int y){

        //local variables of x,y,z in this method
        int z=x+y;
        //Modified local variable
        x++; 
        y++;

        return z;

    }
    public static void main(String[] args){
        //Local variables of main method
        String textData="Learn programming";
        int x=2,y=5;
        System.out.println("textData : "+textData);
        
        {   
            //result variable is not accessible by outside this block
            int result=0;
            //But local variable of main are access here
            result=testSum(x,y);
            System.out.println("result : "+result);

        }
        //result variable not accessible here
    }

}
Local Variable Example In Java

Output

textData : Learn programming
result : 7

There are possible to define same local variable name in two different function and block.

Instance types : This type of variable are define outside of function that means this is data member of class (class variables). We can use this variable inside of class methods. class instance variables will directly accessible by its class methods. And possible to use public variable outside of class by using class objects. Lets view an example how to define an use instance variable in class.

//Example in instance Variables
public class Student{

    //This is an instance variables
    public String name,classSection;
    public int age;
    //Display instance values
    public void showRecords(){
        System.out.println("\nName : "+name);
        System.out.println("ClassSection : "+classSection);
        System.out.println("Age : "+age);
    }
    public static void main(String[] args){
        //Create object of class
        Student objOne=new Student();
        //Set value of instance in object
        objOne.name="Om";
        objOne.age=9;
        objOne.classSection="5'th";

        Student objTwo=new Student();
        objTwo.name="hani";
        objTwo.classSection="7'th";
        objTwo.age=11;

        objOne.showRecords(); //first student record
        objTwo.showRecords(); //second student record
    }
}
Instance Variable In Java Programming

Output

Name : Om
ClassSection : 5'th
Age : 9

Name : hani
ClassSection : 7'th
Age : 11

Observe that when creating a class object using of new operator then in this situation compiler are create class instance which are hold the information about class variable. In this example there are two objects (objOne and obi Two).

Static Variables : static is special type of variable, those variables memory are allocated at only once And objects of class will share this variable.

//Example in Static Variables
public class Student{

    //Static variable   
    public static int records; 

    //This is an class variables
    public String name,section;
    public int age;
    //Constructor of class
    Student(){
        Student.records++;
    }
    static void instance(){
        System.out.println("Number of student records : "+
          Student.records);
    }
    public static void main(String[] args){
        
        Student first=new Student();
        first.name="Megan";
        first.age=8;
        first.section="A";

        Student second=new Student();
        second.name="Hani";
        second.section="B";
        second.age=11;

        Student third=new Student();
        third.name="Smith";
        third.section="E";
        third.age=17;

        instance();
    }
}

static variable of class are accessible and used by the name of class and dot operator.

Static Variable Example in Java

Output

Number of student records : 3

Other basic example

public class Example{
    //fields member or data member of class
    String name;

    //name is parameter of constructors
  public Example(String name){
    //name is local variable of this function
    //this.name is data member of class
    this.name=name;
  }
  public String getName(){
    //return name
    return this.name;
  }
  public static void main(String[] args) {
    //make object of class
    Example obj=new Example("Foo");
    //get name 
    String userName=obj.getName();
    //display name
    System.out.println("name is :"+userName);
  }
}

Output

name is :Foo
Variables scope

In this example class are one data member. And class object are access this variable value that is protected by class. And inside a function variable are access within the function. If we are need to use this variable outside of other function, Then passing this local variable value to other function. In above program get the value of object and this is store by local variable of main function.

Variable name we are get the value. Suppose we are check the variable data type. So In java we can check variable data type in following ways..

//Display data type of variables
class Variables{

  public static void main(String args[]){

    String data="Java Program";
    //display object type
    System.out.println(data.getClass().getName());
    //Define integers variable
    int x=10;
    //Useful to primitive and other data type
    System.out.println(((Object) x).getClass().getName()); 
  }
}

Output

java.lang.String
java.lang.Integer

Pass by reference and pass by value

Java programming are not allowed to pass a local variable reference to any function. But in case modified class variable values then there are possible to send the object reference to other function. And that function can changed there class variable values.

//Example pass by object
class Execution{
    //Private data of class
    private String name;
    private int id;
    public Execution(String name,int id){
        this.id = id;
        this.name = name;
    }
    public void showData(){
        System.out.println("Name :" + name);
        System.out.println("Id :" + id);
    }
    public void changeData(Execution other,String newName){
        other.name=newName; //change values
    }
    
}
public class Test{
    public static void main(String[] args){

        Execution objectOne = new Execution("Hani",100);

        Execution objectTwo = new Execution("Smith",710);
        
        System.out.println("Before change");
        objectOne.showData();
        objectTwo.showData();
        
        objectOne.changeData(objectTwo,"Mark");

        System.out.println("\nAfter change");
        objectOne.showData();
        objectTwo.showData();
        
    }
}
Pass Instance reference to function

Clear that, When pass any object to function. inside a function this pass class object as act a local variable. but that are holding the reference of an instance. That means that is capable to change instance variable values.

Output

Before change
Name :Hani
Id :100
Name :Smith
Id :710

After change
Name :Hani
Id :100
Name :Mark
Id :710

When provide new instance reference to this local objects then passed object are never reflected. See this example.

//Example pass by object
class Execution{
    //Private data of class
    private String name;
    private int id;
    public Execution(String name,int id){
        this.id = id;
        this.name = name;
    }
    public void showData(){
        System.out.println("Name :" + name);
        System.out.println("Id :" + id);
    }
    public void changeData(Execution other,String newName){
        other=new Execution("Foo",900); //modified reference
        other.name=newName;
    }
    
}
public class Test{
    public static void main(String[] args){

        Execution objectOne = new Execution("Hani",100);

        Execution objectTwo = new Execution("Smith",710);
        
        System.out.println("Before change");
        objectOne.showData();
        objectTwo.showData();
        
        objectOne.changeData(objectTwo,"Mark");

        System.out.println("\nAfter change");
        objectOne.showData();
        objectTwo.showData();
        
    }
}
Change the local object reference

Output

Before change
Name :Hani
Id :100
Name :Smith
Id :710

After change
Name :Hani
Id :100
Name :Smith
Id :710




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment