Java TUTORIAL - Variable

So far we learned how to compile and run a Java program. We know how to add comments to our source code. We have learned a little bit of what is class and main funtion.

Let us now move beyond Hello World, and try to get someting more meaningful. Before we are able to do some real programming we need to understand the concept of variables. A variable can be of different type, for example an integer variale or a character variable.

We will now write a short java program that declares and then assigns a variable and prints it using the System.out. println statement. Take a look at the following java code.

class example1 { public static void main ( String[] args ) { int x; //a declaration of an integer variable x x = 47; System.out.println("The variable x has a value of : " + x ); } }

Some Explanation

The statement

int x; 

declares that x is a variable of type integer. The statement

x = 47; 

Assigns value 47 to the variable x.

And finally, the statement

System.out.println("The variable x has a value of : " + x ); 

Prints out the value of x. Notice that the println has two parts - one is fixed part and other that prints the string "The variable x has a value of : " as it is. The second part prints the vale of x. The two parts are joined by a + sign.

If you compile and run this program, the output looks as follows.


C:\javatutorial>java example1
The variable x has a value of : 47


This program does not do anything much meaningful. It was presented to enhance the understanding of the concept of variable and assignment of the value to the variable.

Let us now write a program that is more meaningful. We will write a program that will print the area of a rectangle, for a given length and width.

Take a look at the following example

class example2 { public static void main ( String[] args ) { int length,width,area ; //declaration of integer variables length,width and area length = 8; width = 6; area = length * width ; // Calculate the area System.out.println("The Area of rectangle is : " + area ); } }

If you compile and run this program, you should output something like


C:\javatutorial>java example2
The Area of rectangle is : 48

Most of the code should be self evident.

The Javascript statement

area = length * width ; 

Multiplies the variables length and width and assigns the result to the variable area.

You may want to do some simple exercises to enhance your understanding

Exercise 1 : Write a java code that will take one length and width of a rectangle and will print its perimeter.

Exercise 2 : Write a java code that has one variable - the side a square. You will then calculate the area and the perimeter of the square and print it out.

Integers are not the only data types in Java. This is something we will learn in the next chapter.