Java Variables

Java variable is data container which is used to store data values. Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are different types of variables in Java

  • int - stores integers (whole numbers) like 11,22,-44,-55 etc.
  • float - stores floating point numbers with decimals like 55.32  or -53.23 etc.
  • String - stores text value like "good morning". String values are surrounded by double quotes(" ").
  • boolean - stores values true or false.
  • char - stores single characters like  'm' or 'N'. Char values are surrounded by single quotes(' ').
     

Declaring Variables

You can define variable using data type as below.

int phonenum = 9428982251;
System.out.println(phonenum);

String country = "india";
System.out.println(country);

float cost =99.67;
System.out.println(cost);

boolean isFail = true;
System.out.println(isFail);

char firstLetter = 'A';
System.out.println(firstLetter);

Types of Variables

There are three types of variables in Java

  • local variable
  • instance variable
  • static variable

 

1) Local Variable

A variable declared inside the body of the method is called local variable. we can use this variable only within that method and the other methods in the class.

A local variable cannot be defined with "static" keyword.

 

2) Instance Variable

A variable declared inside the class but outside the body of the method is called an instance variable. It is not declared as static

 

3) Static variable

A variable that is declared as static is called a static variable. Static variable can be defined by  "static" keyword. You don't need to create object to access Static variable.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

96571