DEV Community

SELVAKUMAR R
SELVAKUMAR R

Posted on

Variable and Object Creation in Java

Variable:

Variable is the named memory location to store the value with datatype

Variable is classified in to two types Local variable and Global variable

Local variable:

Local variables are declared in between the block, method when the block get ends local variable memory is deleted

Ex:

Public class Classroom{
public static void main(string args[]){
String schoolName="Sowdambikaa Matric Hr Sec School";
int Rooms= 24;
System.out.println(schoolName);
System.out.println(Rooms);

}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Sowdambikaa Matric Hr Sec School
24

Global Variable:

Global variables are created inside the class but outside the method to access the variable in another method.

Global Variable is divided in to two types static variable and Non static variable

Static Variable:

Static keyword is used in variable declaration to specifies the class information.

Public class Classroom{
static String schoolName="Sowdambikaa Matric Hr Sec School";
static int Rooms= 24;
public static void main(string args[]){
System.out.println(schoolName);
System.out.println(Rooms);
System.out.println(Classroom.schoolName);
System.out.println(Classroom.Rooms);
}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Sowdambikaa Matric Hr Sec School
24

Sowdambikaa Matric Hr Sec School
24

Non static Variable:

Non Static variable declaration to specifies the Object information.

Non static variable is unable to print directly in the main method if we try to print it throws the error

Ex:

Public class Classroom{
string Name = "Selva";
int age = 24;
public static void main(string args[]){
System.out.println(Name);
System.out.println(age);

}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Error : Non static variable name cannot be referenced from a static context

Object Creation:

Public class Classroom{
string Name = "Selva";
int age = 24;
public static void main(string args[]){
Classroom student = new Classroom();
System.out.println(student.Name);
System.out.println(student.age);

}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Selva
24

Top comments (0)