DEV Community

Anees Abdul
Anees Abdul

Posted on

Variables and Types:

What is a variable
It is a container to store data values.
Each Variable has:

  • Datatype
  • Variable Name:
  • Values

Why Do We Need Variables?
To store user inputs and to perform calculations etc

Syntax of a Variable in Java

dataType variableName = value;
Enter fullscreen mode Exit fullscreen mode

Types of Variable Scope in Java:

  1. Local Variable
  2. Instance Or Object or Global Variable
  3. Static Variable

What is a Local Variable

It is declared inside a class and inside a method, and it must be initialized. It can be accessed only within that method. It will be destroyed once the block finishes execution.

Syntax:

void display() {
    int x = 10;   // local variable
    System.out.println(x);
}
Enter fullscreen mode Exit fullscreen mode
  • It cannot be used outside the display() method.
  • It must be called from the main method using object creation and accessed by calling object reference name. method name

What is a Global Variable:

  • It is declared inside the class and outside the method.
  • We just declare the variables inside the class and the values will be initialized during object creation.

  • It can be accessed using
    Objet reference name . Variable name

Syntax

class Student {
    String name;   // instance variable
}

Enter fullscreen mode Exit fullscreen mode

What is a Static Variable:

  • Declared using the static keyword
  • Belongs to the class, not to objects
  • Shared among all objects of the class. Instead of each object having its own copy, there's only ONE copy that all objects share.

Syntax:

class College {
         static dataType variableName;
Example: static String companyName = "ABC Pvt Ltd";
}
Enter fullscreen mode Exit fullscreen mode

You can access it in these ways below:

  • Inside the class, it can be accessed by just using the variableName.
  • Outside the class, it can be accessed by ClassName.VaribleName

Top comments (0)