Data types specifies what type and which size of data can be stored in a variable.
Suppose, you want to eat rice and drink water. you will take rice on a plate and water in a glass. You will not take rice in a glass and water on a plate. That sounds funny. Also, you can take rice in a bowl and water in a bottle. Moreover, you can specify which size of plate or glass you want to put items like a small plate or big glass.
So think that you are taking them in a container but while putting them, you are choosing different types and sizes of containers depending on which types of things you want.
In java, you have to specify which type and which size of data you want to put in a variable.
There are 2 types of data types in Java
- Primitive data types
- Non-primitive data types
Primitive Data Types: A primitive data type is pre-defined by the programming language. The size and type of variable values are specified, and it has no additional methods.
There are 8 types of primitive datatype:
- int
- float
- double
- char
- byte
- boolean
- long
- short
Non-Primitive Data Types: These data types are not actually defined by the programming language but are created by the programmer. They are also called “reference variables” or “object references” since they reference a memory location that stores the data.
There are no specific types of non-primitive data types. Some example as:
- class
- object
- interface
- abstract
- dictionary
- array
- list
- String
etc are Non-Primitive data types.
Example:
public class Main {
public static void main(String[] args) {
String name="salman"; //non-primititive
int age=27; //primitive
}
}
you can convert from a datatype to another data type. This is called type casting.
Here is an example:
public class Main {
public static void main(String[] args) {
int a=10;
double b=10.5;
System.out.println("value of b "+(int)b);
System.out.println("value of a "+(double)a);
}
}
Output:
value of b 10 //previous value of b was 10.5
value of a 10.0 // previous value of a was 10
Leave a Reply