JAVA TUTORIAL

Java Intro Java Features Java vs C++ Java Simple Program Java Applet vs Application JVM,JDK or JRE Java Keywords Java Variables Java Literals Java Separators Java Datatypes Java Operators Java Statements Java Array Java String

CONTROL STATEMENTS

Java If-else Java While Loop Java Do-While Loop Java For Loop Java For-each Loop Java Switch Java Break/Continue

JAVA METHODS

Java Method Java Overloading Java Overriding

JAVA CLASSES

Java OOPs Java Classes/Objects Java Inheritance Java Polymorphism Java Encapsulation Java Abstraction Java Modifiers Java Constructors Java Interface Java static keyword Java this keyword

Java Variables

A variable is a basic unit of storage in a Java Program. Variables represent memory location in which value can be stored. Before using any variable, you have to declare it. After it is declared, you can then assign values to it.

int a;
byte b;
boolean male;
short age;

You can also declare and assign a value to a variable at the same time.

int a = 3;
byte b = 23;
short age = 20;

In this we declare and assign a value to a variable at the same time.

We can also declare multiple variables of one type in one expression such as in the following example:

int age, enrollnum, name, numChildren;

Types of Variables

In java variables are define into three ways:

1. Instance variable

2. Class variable

3. Local Variable.

1) Instance variable

Instance variables are used to define the attributes of a particular object.

It is not possible to declared instance variable as static.

2) Class variable

Class Variables are similar to instance variables, except their values apply to all the instances of a class (and to the class itself) rather than having different values for each object.

3) Local variable

Local variables are declared and used inside methods, for example, for index counters in loops, temporary variables or to hold values that you need only inside the method definition itself.

A local variable cannot be defined as "static"

For Example: Add Two Numbers

class Simple{
public static void main(String args[]){
int x = 22;
int y = 62;
int z = x+y;
    System.out.println(z);
    }
}

Output:

84

Another Example: Multiplication of Two Numbers

class Simple{
public static void main(String args[]){
int x = 2;
int y = 6;
int z = x*y;
    System.out.println(z);
    }
}

Output:

12