- Variables are containers for storing data values.
- In Java, there are different types of variables, for example:
- String – stores text, such as “Hello”. String values are surrounded by double quotes
- int – stores integers(whole numbers), without decimals, such as 123 or -123.
- float – stores floating-point numbers, with decimals such as 19.99 or – 19.99
- char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes.
- boolean – stores values with two states: true or false
- Variable may take different values at different times during the execution of the program.
Rules Of Variable Declaration
- The variable name does not start with a digit
- Java is case – sensitive language, therefore both upper case and lower case letters should be distinct
- Variable names should not be a keyword
- There should be no white spaces
- A variable name can be of any length.
type variable_name = value;
- Where type is one of Java’s types such as int, String and the variable name is a,b, or any name, an equal sign is used to assign values to the variable.
- Variable name and field are the same just to confuse developers
Declaration of Variables :
- String name;
- int bday, count;
- double contact;
- float x,y;
- boolean b;
- char c;
1. By using an assignment statement
- String name = “Rutu Shah”;
- int bday = 14 , count = 1;
- double number = 12123123.746;
- float x =5.6,y =12.5;
- boolean b=true;
- char c=’c’;
2. By using read statement: (readLine() method)
readLine() method reads input from the keyboard as a string which is then converted to corresponding data type using wrapper classes.
3. using command line argument by passing value at run time
❖ Wrapper classes
|No.||Primitive data type||Wrapper class|
Types of variables
1. Local variable: A variable declared inside the body of the method is called a local variable. You can use this variable only within that method and the other methods in the class aren’t even aware that the variable exists. A local variable cannot be defined with the “static” keyword.
2. Instance variable : A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static. It is called an instance variable because its value is instance-specific and is not shared among instances.
3. Static variable: A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.