Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

Java

Learn step by step



Java Variables

Variables are the nouns of a programming language: they are the entities (values, data) that act or are acted upon. The character-counting program uses two variables--count and args. The program increments count each time it reads a character from the input source and ignores args.

You must declare all variables before they can be used. The basic form of a variable declaration is shown here:

data type variable [ = value] [, variable [= value] ...] ;

Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.

Following are valid examples of variable declaration and initialization in Java

int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a initialized with value 'a'

EXAMPLE :

class Count {
public static void main(String[] args)
throws java.io.IOException
{
int count = 0;

while (System.in.read() != -1)
count++;
System.out.println("Input has " + count + " chars.");
}
}

A variable declaration always contains two components: the type of the variable and its name. Also, the location of the variable declaration, that is, where the declaration appears in relation to other code elements, determines the scope of the variable

Variable Types

There are different types of variables in Java. They are as follows:

1. Instance Variables (Non-Static Fields)

Objects store their individual states in “non-static fields”, that is, fields declared without the static keyword.

Non-static fields are also known as instance variables because their values are unique to each instance of a class. For example, the currentSpeed of one bicycle is independent from the currentSpeed of another.


import java.io.*;

public class Employee{
// this instance variable is visible for any child class.
public String name;

// salary variable is visible in Employee class only.
private double salary;

// The name variable is assigned in the constructor.
public Employee (String empName){
name = empName;
}

// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}

// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]){
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

This would produce the following result:

name : Ransika
salary :1000.0
2. Class Variables (Static Fields)

A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since, conceptually, the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field.


import java.io.*;

public class Employee{
// salary variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]){
salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}

This would produce the following result:

Development average salary:1000

Note: If the variables are access from an outside class the constant should be accessed as Employee.DEPARTMENT

3. Local Variables

A method stores its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0; ). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared—between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

Example

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to this method only.


public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}

This would produce the following result:

Puppy age is: 7
4. Parameters

They are the variables that are passed to the methods of a class. A parameter to a method is also called a formal parameter.

PLEASE NOTE: all parameters that are not of object types are PASSED BY VALUE! All others are PASSED BY REFERENCE (including arrays). This is a common mistake made by Java newcomers

EXAMPLE :

Void method


public class VoidExample{
public static void main(String args[]){
printMessage();
} //main

public static void printMessage(){
System.out.println("Hello and welcome!");
}
} //class

All the above program does is print a simple message to the console by calling the method printMessage(). The output of the program is simply

"Hello and welcome!"

EXAMPLE

Simple static method


public class SimpleStatic{
private static int s=3, t=7;

public static void main(String args[]){
System.out.println("sum: " + sum(s,t));
}

private static int sum(int a, int b){
return a+b;
}
}

The above program will be compute the sum of the 2 instance variables. The reason the method is static is because the instance variables are static as well as the method is being called from the static main() method.

EXAMPLE:

Simple String method


public class SimpleStringMethod{
static String word1 = "Cats";
static String word2 = "Dogs";

public static void main(String args[]){

System.out.println("Before call:\nword1: " +
word1 + "\nword2: " + word2);

switches(word1,word2);

System.out.println("\nAfter call:\nword1: " +
word1 + "\nword2: " + word2);
}

private static void switches(String w1, String w2){
w1 = w2;
w2 = "Changed!";
}
}

Here, we wrote a method called switches that takes two String arguments. It is seen that we are changing the values of the words in the method. The words in the main method DO NOT change. Once we attempt to change a variable in a method, we lose the reference to it from the place we called it. Therefore, although it is passed by reference, we do not change the values of the variables.

Here is the output of the following program:

Before call:
word1: Cats
word2: Dogs

After call:
word1: Cats
word2: Dogs

EXAMPLE:

Loopy method


public class LoopyMethod{
private static int loopy(int n){
int total = 1;
for(int i = 0; i < n; i++)
total *= n;
return total;
}

public static void main(String args[]){
int n1 = 2, n2 = 5;

System.out.println("First call with " + n1
+ " = " + loopy(n1));

System.out.println("Second call with " + n2
+ " = " + loopy(n2));
} //main
} //class

The method named loopy() will multiply the given argument (int n), n times. So if we enter the value of 4, it would calculate 4*4*4*4 which is 256. In other words, this is a method to find the value of n to the nth power.

Here is the output of the following program:

First call with 2 = 4
Second call with 5 = 3125

Variable Declaration

Identifiers are the names of variables. They must be composed of only letters, numbers, the underscore, and the dollar sign ($). They cannot contain white spaces. Identifiers may only begin with a letter, the underscore, or the dollar sign. A variable cannot begin with a number. All variable names are case sensitive
Syntax for variable declaration

datatype1 variable1, datatype2 variable2, … datatypen variablen;

For example:

int a, char ch;
Initialisation
Variables can be assigned values in the following way: Variablename = value;
For example:
ch='a';
a=0;


Related Videos