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);
Output:
Flower
21
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);
}
}
Output:
Vidhya Varshini
30
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);
}
}
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();
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);
}
}
Output:
Vidya
21
Top comments (0)