Variables in Java
Variables in Java
LOCAL VARIABLES
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}
1. import java.io.*;
class Marks {
int engMarks;
int mathsMarks;
int phyMarks;
}
class MarksDemo {
public static void main(String args[])
{
// first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;
// second object
Marks obj2 = new Marks();
obj2.engMarks = 80;
obj2.mathsMarks = 60;
obj2.phyMarks = 85;
1. import java.io.*;
class Emp {
2.
class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
3. class JavaExample{
static int age;
static String name;
//This is a Static Method
static void disp(){
System.out.println("Age is: "+age);
System.out.println("Name is: "+name);
}
// This is also a static method
public static void main(String args[])
{
age = 30;
name = "Steve";
disp();
}
}
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
}
Instance Variables: Instance variables are non-static variables and are declared in
a class outside any method, constructor or block.
As instance variables are declared in a class, these variables are created when
an object of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier then the default access specifier will be
used.
Initilisation of Instance Variable is not Mandatory. Its default value is 0
Instance Variable can be accessed only by creating objects.