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:
byteshortintlongfloatdoublebooleanchar
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();
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";
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);
}
}
In this example:
-
typeis a static variable because it is declared using thestatickeyword. -
owneris an instance variable because it belongs to each object. -
numberis a local variable because it is declared inside thedisplay()method.
Top comments (0)