- Variables are use to store values.
- Variables can be use in a math expression.
- Variables can be use to show values to user.
- Variables can be use to assign value to another variable.
- Variable creation is done in 2 steps
- First step is variable declaration
- Another step is initialization of variable.
- Syntax:
Data_Type Variable_Name = value;
Casting in Primitive Data type
Casting is use to convert value from one data type to another.
There are 2 types of casting
Implicit casting
- Casting done automatically/internally by java
- No needs to write any extra code to do this type of casting.
Explicit Casting
- Casting which has to be done by developer.
- Need to write code manually to achieve this casting.
- You may get an logically incorrect output if it is done in wrong way.
Different type of values store in Variables
Decimal value
- All whole numbers.
- Ex : 10, 20 ,123
Binary Value (JDK 1.7 onwards)
- Always start with 0B or 0b
- It contains only 0 or 1 digits.
- Ex : 0B1010, 0b0101
Octal Value
- Always start with 0
- It contains only 0 to 7 digits.
- Ex : 027, 033
Hex-Decimal Value
- Always start with 0X or 0x
- It contains only 0 to 15 numeric digit (for 10 to 15 use A-E)
- Ex : 0XABC, 0x123ABC, 0xdad
Example :-
public class VariableValueType { public static void main(String args[]) { int dec = 22; int binary = 0B0101; int octal = 027; int hex = 0XABC; System.out.println(dec); System.out.println(binary); System.out.println(octal); System.out.println(hex); } }
Type of Variable
Type of variable, decided on the bases of the variable declaration location.
- Local Variable
- Which is created inside method or at method declaration level.
- Instance variable
- Which is created inside class and outside any method.
- Class/Static variable
- Which is created inside class and outside any method with static keyword.
Example :-
public class VariableTypes { int b = 30; // Instance Variable static int c = 40; // Static / Class Variable public static void main(String args[]) { int a = 20; // Local Variable System.out.println(a); System.out.println(c); System.out.println(b); } }
Join Telegram : Click Here
All Full Stack Java Study Material
Job’s For Fresher