Variables and Data Types
Variables and Data Types
Understanding Variables
- A variable is like a container which holds information that can be modified or retrieved at any time in your Java program.
- Each variable has a data type which determines the size and layout of the variable’s memory, the range of values that can be stored and the set of operations that can be applied.
- The name of the variable is called an identifier. In Java, identifiers are case-sensitive.
Primitive Data Types
- Java has 8 primitive data types: byte, short, int, long, float, double, char and boolean.
- Numeric types include integer types (byte, short, int, long) and floating-point types (float, double).
- Character types include the char data type, used for storing Unicode characters.
- The boolean type has only two possible values: true or false; essentially used for logical operations.
Declaration, Initialization and Assignment
- In Java, before a variable is used, it must be declared with a statement that specifies its data type and name.
- Initialization is the process of assigning a value to a variable during its declaration.
- Assignment involves giving a variable value if not given during declaration; this is done with the use of the assignment operator (=).
Constant Variables
- A final keyword in Java is used to declare a constant variable. Its value can’t be modified.
- It’s a good practice to declare all letters of the identifier of a constant variable in uppercase.
Type Conversion and Casting
- Type conversion is a process of converting one primitive data type into another.
- Casting is a method of explicit conversion which involves converting a larger datatype into a smaller one or vice versa.