October 2, 2009

Variable Declarations in Java


For declaring any variable in java program, following form is used 

type var-name;
More generic form : type identifier [=value][,identifier [=value..]..];

Here type specifies the type of variable. Now first let us see what all types Java provides us:

We can have two kinds of variables in java
  • Primitive (byte, short, int, long, char, float, double and boolean)
  • Reference Variables (variables that are not of primitive data types but are of any partcular class type instead - come under this category)
Few examples of primitive type variable declarations are:
int a, b, c;
int d=5, e=10;
byte x=10;
double y=3.14159;
char z='a';
boolean x=true;

Few examples of declaring reference variables:
Object o; (Object class of Java)
Dog myNewDogReferenceVariable; (where Dog is any generic class for real world object) 
String s1, s2, s3; (declare three String variables)

Let us see writing a simple program VariableDeclarationExample.java that uses primitive type of variables declaration.

package myjava;

public class VariableDeclarationExample {

    public static void main(String[] args) {
        
        int a=10;
        char b='b';
        double c=3.14;
        
        System.out.println("int a ="+a);
        System.out.println("char b ="+b);
        System.out.println("double c ="+c);
    }
        
    }

Output is :
int a =10
char b=b
double c =3.14

In the above program, three types of primitive type of variables are declared and then while printing through System.out.println command , they are printed without enclosng them in quotes
e.g. System.out.println("int a ="+a);
So above line prints "int a=" ie. int a=10;

[ PS: Copied from Have Fun with Java ]