Saturday, July 14, 2012

Variables in Java

Here we will learn how to declare variables and use them in our programs. Variable is a memory location where we store the numbers, floats, string and our objects etc. We give some name to those memory location for better understanding and to easily remember them. For example if you want to store the marks of the students in memory, you can declare or make a variable having the name "marks". Now when you use the name marks in your program, this will mean the memory location where you have stored marks. Now lets see and example.

public class Variables
{
public static void main(String[] Args)
{
int studentID;
studentID = 2001;

String name = "Ahmad Faraz";

float cgpa = 3.20;

System.out.println("My name is " + name);
System.out.println("My ID is " + studentID);
System.out.println("My CGPA " + cgpa);
}
}

Here we are using the class Variables. So don't forget to save this file with the name "Variables.java". We have the same old "main" method. But this time in main method we are using three different variables. The first variable is the integer type. As we have written "int" before it. The variable "studentID" will store only integers in it. Here we have declared "studentID" in first line and then initialized it in second line. But in next variable "name" I have declared it and initialized in the same line. You can use the both method. It depends on your preference. The thirs variable is float type "cgpa". Now see it depends on the situation that which type we will use. Floating point numbers can be stored in integer type variables and compiler will NOT generate any error. It your responsibility to check such issues. Because integer variable will skip the numbers after the decimal point and you will get wrong calculations and results. So be careful in selecting the type of the variable.
In next three line the same old stuff, we are gonna print three variables on the screen. as you can see the we have just written the variables names to print them. But wait....whats "+" doing here. Did you noticed....good..... it is doing concatenation. It means joining to variables values or two data elements. Here first we have written text in "" and the used + and then variable name. So println will join the both thing and print them on the screen.
So this was our variables lesson. Hope you have enjoyed. See you next time with some new stuff, stay with us..........Bye

No comments:

Post a Comment