DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on

Variable and Object in Java

What is variable: Variables are containers for storing data values. It acts like a name given to a value stored in memory. This can be classified into two types : local and global variable.

Ex: int age = 21;

Here int - data type
age - variable name
21 - value assigned to a variable

Local variable: It is declared inside a class but outside any method. Each object gets its own copy of instance variables.
This can have default values and used to represent object properties.

Ex:

public class Home{
public static void main(String[] args){
String name = "Flower";
int age = 21;
System.out.println(name);
System.out.println(age);
Enter fullscreen mode Exit fullscreen mode

Output:

Flower
21

Enter fullscreen mode Exit fullscreen mode

Global variable: It is declared outside the methods or blocks and can be accessed anywhere in the program. This can be further divided into two types : static and non-static.

Static variable: This variable is declared using static keyword inside a class. It is shared by all objects in class and has 1 memory copy.

Ex:

public class House{
public static String name = "Vidhya Varshini";
static int Doorno = 30;
public static void main(String[] args){
System.out.println(name);
System.out.println(Doorno);
}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Vidhya Varshini
30
Enter fullscreen mode Exit fullscreen mode

Non-static: This variable is declared to a specific object information. It has multiple memory copy based on object.

Ex:

public class House{
String name = "Flower";
int age = 21;
public static void main(String args[]){
System.out.println(name);
System.out.println(age);
}
}
Enter fullscreen mode Exit fullscreen mode

Output: non-static variable name cannot be referenced from a static context.

Object: An object is a real-world entity that has state (data) and behavior (actions). In Java, an object is an instance of a class.

Syntax:

ClassName objectName = new ClassName();
Enter fullscreen mode Exit fullscreen mode

Ex:

public class House{
String name = "Vidya";
int age = 21;
public static void main(String[] args){
House person = new House();
System.out.println(person.name);
System.out.println(person.age);
}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Vidya
21

Enter fullscreen mode Exit fullscreen mode

Top comments (0)