Variables and types of variables in java with examples

In this article, we will cover what are java variables and the types of variables in java with examples.

A variable is a name for a specific memory location.

Declaration of variables in java

We can declare a variable like below :

datatype + variable_name = variable_value

The process of assigning a value to a variable is known as the Initialization of variable.

int result = 100 ;

int is a datatype
result is a variable_name
100 is a variable_value

Note* 100 is stored in memory and the result variable points to that memory location.

We can print the value of a variable using the variable name.

System.out.println(“printing the value of a variable : “+result);

We can change the value of an existing variable as well.

int result = 100 ;
result = result + 100 ;
System.out.println(“adding up the result : “+result);

We can use the variables to perform operations as well.

int first = 10 , int second = 20 ;
int result = first + second ;
System.out.println(“adding two numbers : “+result);

package demo;

public class Demo {

  public static void main(String[] args) {

    int result = 100;
    System.out.println("printing the value of a variable : " + result);

    result = result + 100;
    System.out.println("adding up the result : " + result);

    int first = 10;
    int second = 20;
    int sum = first + second;
    System.out.println("adding two numbers : " + sum);
  }
}

Output : printing the value of a variable : 100
         adding up the result : 200
         adding two numbers : 30

String name = “Suraj” ;

String is a datatype
name is a variable_name
Suraj is a variable_value

Note* We cannot assign a String value to an int variable or vice versa. We will get a Compile time exception.

package demo;

public class Demo {
  public static void main(String[] args) {

    int name = "Suraj";
    String result = 100;
  }
}

Output : Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	Type mismatch: cannot convert from String to int
	Type mismatch: cannot convert from int to String

Types of variables in java

1 ) Local variables
2 ) Instance variables
3 ) Class variables

Local variables

Local variables are local to a specific method, constructor or block. It means the variables which are created and used within the scope of a method, constructor or block are known as local variables.

We can use only the final access modifier with the local variable.

Why we can use only the final access modifier with the local variable?

The local variable is created and used within the method and gets destroyed once the method is completed. Hence we can say the scope of a local variable is limited to the method. So no point in declaring the local variable with a public or protected access modifier.

What do you mean by a variable is created?

It means the memory is assigned to that particular variable.

Local variables should be assigned some default value at the time of declaration before using it else java will throw a compile-time exception.

Why is it so?

Because once a method is called the steps in the method are executed sequentially and as the scope of the local variable is limited to that method hence the variable should be declared within that method itself. The local variable cannot be assigned value from a constructor or some setter method hence its value has to get assigned within that method. Hence java compiler throws a message saying you have to initialize the variable before use.

Local variables in java example

package demo;

public class Demo {
  public static void main(String[] args) {

    String name;
    System.out.println("name of the person is : " + name);
  }
}

Output : Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The local variable name may not have been initialized

Note* In the above example main is a method and name is a local variable hence it must be initialized before use.

If we are not using a local variable then we do not have to assign default values at the time of declaration. Java compiler is smart enough to not throw the compilation exception.

package demo;

public class Demo {
  public static void main(String[] args) {

    String name;
    System.out.println("name variable is not used hence no compilation issue");
  }
}

Output : name variable is not used hence no compilation issue

Instance variables

Non-static variables or Instance variables are declared in the class outside of a method, constructor or block. The instance variable’s scope is throughout the Objects’ lifetime. It means the instance variables get initialized when the Object of a class is created and gets destroyed when the Object is destroyed.

private, protected, public, and default are the access modifiers that we can use with instance variables.

We do not have to explicitly initialize the instance variables they will implicitly have default values.

The default values

int variable is 0.
The string variable is null.
The boolean variable is false.

Every Object will have a separate copy of instance variables. Say we have created 3 objects of Student class then there will be a separate copy of instance variables for each Student object and they will not depend on each other. Change in one copy will not affect another copy.

We can access instance variables in instance methods directly. But to access instance variables in static methods, we have to create an object of that class.

Instance variables in java example

package demo;

class Student {
  int rollNo;
  String name;

  Student(int rollNo, String name) {
    this.rollNo = rollNo;
    this.name = name;
  }

  @Override
  public String toString() {
    return "Student [rollNo=" + rollNo + ", name=" + name + "]";
  }
}

public class Demo {
  public static void main(String[] args) {

    Student student1 = new Student(101, "Suraj");
    System.out.println(student1);

    Student student2 = new Student(102, "Iqbal");
    System.out.println(student2);

    student1.name = "Surya";  // Since main is a static method hence we can access instance variable using student1 reference

    System.out.println(student1);
    System.out.println(student2);
  }
}
Output : Student [rollNo=101, name=Suraj]
         Student [rollNo=102, name=Iqbal]
         Student [rollNo=101, name=Surya]
         Student [rollNo=102, name=Iqbal]

Note* student1 and student2 maintain a separate copy of Student instance variables. Hence we can see there are 2 different values for each object.

Static variables

Class variables or Static variables are declared in the class outside of a method, constructor or block. Static variables belong to the class and not to the object. It means a single copy of static variables will be shared by all the instances.

Say we have created 3 objects of Student class then there will be a single copy of static variables which will be shared by all the 3 Student objects. So if a change is made on a static variable by one student object, it gets reflected for the other 2 objects as well.

We can access static variables in a class using object reference or class name.

Static variables get loaded into the memory at the time of class loading. It means the static variables get initialized even before the instance of the class is created ( even before the class object is created )

The default values of static variables will be the same as instance variables.

private, protected, public, and default are the access modifiers that we can use with static variables the same as instance variables.

static variables can be used directly in static methods as well as for instance methods.

Static variables in java example

package demo;

class Student {
  static String subject;

  int rollNo;
  String name;

  Student(int rollNo, String name) {
    this.rollNo = rollNo;
    this.name = name;
  }

  @Override
  public String toString() {
    return "Student [rollNo=" + rollNo + ", name=" + name + " , subject=" + subject + "]";
  }
}

public class Demo {
  public static void main(String[] args) {

    Student student1 = new Student(101, "Suraj");
    student1.subject = "Maths";
    System.out.println(student1);

    Student student2 = new Student(102, "Iqbal");
    System.out.println(student2);
  }
}

Output : Student [rollNo=101, name=Suraj , subject=Maths]
         Student [rollNo=102, name=Iqbal , subject=Maths]

Note* Since the same copy of the static variable is shared by all the instances of a class. Now since the student1 object has made a change to the subject it gets reflected for the student2 object as well.

student1.subject = “Maths”; OR Student.subject = “Maths”;

[ We can use both the syntax because the subject is a class variable hence it can be accessed using a reference variable or class name ]

Naming conventions for variables

1 ) If the variable_name is of a single word then we should use lowercase characters.

String name = “Suraj”;

2 ) If the variable_name is of multiple words then we should use the camel case. Every first character of the word should be Caps except the first word.

String myFirstName = “Suraj”;

3 ) If the variable_value will be a constant, then the variable_name should be in Caps. If the variable_name is of multiple words then the words should be split out using an underscore.

String NAME = “Suraj”;

String MY_FIRST_NAME = “Suraj”;

FAQ’s

what are instance variables in java?

The variables that are declared in the Class outside of a method, constructor or block. The instance variable’s scope is throughout the Objects’ lifetime. It means the instance variables get initialized when the Object of a class is created and gets destroyed when the Object is destroyed.

what are local variables in java?

The variables that are local to a specific method, constructor or block. It means the variables which are created and used within the scope of a method, constructor or block are known as local variables.

what are class variables in java?

The variables that are declared in the Class outside of a method, constructor or block. The static variable belongs to the class and not to the object. It means a single copy of static variables will be shared by all the instances.

In this article, we have covered java variables and types of variables in java with examples. I hope you found this article interesting and valuable. Please share this article with your friends and help me grow. If you are having any concerns or questions about this article please comment below. If you want to get in touch with me please visit the Contact Me page and send me an email.

Leave a Comment