Basic Primitive Datatypes supported by Java:-
| Data Type | Size |
|---|---|
| byte | 1 byte |
| short | 2 byte |
| int | 4 byte |
| long | 8 byte |
| float | 4 byte |
| double | 8 byte |
| char | 2 byte |
| boolean | 1 byte |
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
Primitive types are predefined (already defined) in Java.
Non-primitive types are created by the programmer and is not defined by Java (except for String).
Non-primitive types can be used to call methods to perform certain operations,
while primitive types cannot.
A primitive type has always a value, while non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
The size of a primitive type depends on the data type, while non-primitive types have all the same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
Java Variables
Variables are containers for storing values.
Declaring Variables:-
'type variableName = value;'
All the other conventions and rules regarding variables are same as other languages.
You can add the final keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "final" or "constant", which means unchangeable and read-only)
Displaying values:-
The println() method is often used to display variables.
To combine both text and a variable, use the + character
Java Type Casting:-
Type casting is when you assign a value of one primitive data type to another type
These are of two types in Java:-
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte