DEV Community

Subash
Subash

Posted on

Variable and Data Types in Java

In Java, there are two types of data types: Primitive and Non-Primitive (Reference) Data Types.

1. Primitive Data Types

In Java, we have 8 primitive data types:

  • byte
  • short
  • int
  • long
  • float
  • double
  • boolean
  • char

These are the basic data types available in Java.

2. Non-Primitive Data Types

In non-primitive data types, we have String, arrays, and classes that we create.

For example, if we create a class called Home, it is a user-defined class and its type is a reference type.

String name = "Stark";
Home home = new Home();
Enter fullscreen mode Exit fullscreen mode

Here, String and Home are reference types.

We also use System.out.println() to print something in Java. Here, System is a predefined class in Java, and println() is a method used to print output.

3. What is a Variable?

A variable is a name given to a storage location that holds a value.

For example:

String name = "Stark";
Enter fullscreen mode Exit fullscreen mode

Here, String is the data type, name is the variable, and "Stark" is the value assigned to it.

4. Types of Variables in Java

We commonly discuss local variables, instance variables, and static variables in Java.

Local Variable: A variable declared inside a method, constructor, or block. It can be accessed within its declared scope.

Instance Variable: A variable declared inside a class but outside methods and without the static keyword. Each object has its own copy of an instance variable.

Static Variable: A variable declared using the static keyword inside a class. It belongs to the class, and the class shares it among its objects.

For example:

class Home {
    static String type = "House";
    String owner = "Stark";

    void display() {
        int number = 10;
        System.out.println(number);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • type is a static variable because it is declared using the static keyword.
  • owner is an instance variable because it belongs to each object.
  • number is a local variable because it is declared inside the display() method.

Top comments (0)