Variable in Java

In Java, variables are used to store values that can be used later in the program. Variables in Java are classified into different types based on the kind of data they can hold. Here are the different types of variables in Java along with examples:

1. Primitive Variables:

Primitive variables are used to store simple data types such as integers, characters, booleans, and floating-point numbers. There are eight primitive data types in Java: byte, short, int, long, float, double, char, and boolean.

Here's an example of using primitive variables to store integer and floating-point values:

                
    int age = 25;
    double salary = 55000.50;
    char gender = 'M';
    boolean isMarried = true;
                
            
2. Reference Variables:

Reference variables are used to store the memory address of an object. They are used to refer to objects created using classes or interfaces. In Java, all objects are reference types.

Here's an example of using a reference variable to refer to an object of the String class:

                
    String name = "John Doe";
                
            
3. Instance Variables:

Instance variables are declared within a class, but outside any method or constructor. They are used to store data that is unique to each instance of a class.

Here's an example of using an instance variable to store the name of a person:

                
    public class Person {
       String name;
       public Person(String name) {
          this.name = name;
       }
    }
                
            
4. Class Variables:

Class variables, also known as static variables, are declared using the static keyword and are shared by all instances of a class. They are used to store data that is common to all instances of a class.

Here's an example of using a class variable to store the number of instances of a class:

                
    public class MyClass {
       static int count = 0;
       public MyClass() {
          count++;
       }
    }
                
            

In summary, Java supports different types of variables, including primitive, reference, class, and instance variables. Each variable type has its own use case, and understanding them is crucial for developing effective Java programs.