Variables in Java

  • 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

  1. The variable name does not start with a digit
  2. Java is case – sensitive language, therefore both upper case and lower case letters should be distinct
  3. Variable names should not be a keyword
  4. There should be no white spaces
  5. A variable name can be of any length.

Syntax

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;

Variable Initialization

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
boolean Boolean 
char Character
double Double
float Float
int Integer
long Long

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.

Example 1

Example 2

VariableDremo.java

Rutu Shah