Tutorials

Java Variables


Introduction to Variable


In java, state of the objects are stored in variables.

 

Variable can be thought of as a container that can hold certain values like int, long, byte, etc. during the life time of an application program.

 

Declare a variable

You need to have knowledge about the data type of the variable that you want to declare. You should know what type of value your variable will contain/store.

See the following chart that helps you understand different data types that a variable can be declared as.

 

Primitive data type

Declaration

int

public int number;

short

public short number;

long

public long number;

byte

public byte number;

float

public float number;

double

public double number;

char

public char number;

boolean

public boolean number;

 

Let’s consider, 

 

public int number;

 

Here,

public – It is access modifier.

int – It is the data type. It defines the type of variable this variable will contain.

Number – It is the name of the variable.

 

Similarly you can pick any other example from the given chart.

 

Initialize variable

In previous section we learnt about declaring a variable. In this section we are going to learn about initializing a variable.

 

Primitive data type

Declaration

int

public int number=9;

short

public short number=9

long

public long number=9;

byte

public byte number=9;

float

public float number=9;

double

public double number=9;

char

public char number=’A’;

boolean

public boolean number=true;

Types of variable

In java, while writing a code you will declare and initialize following types of variable at some point of time.

  • Instance variable
  • Static variable
  • Local variable
  • Method parameters

variable types: tutorials in hand

 

We will read about each one of them in next few chapters.

 



Please Share this page
Views : 116