Saturday, 24 August 2019

Java Tutorials | Variables in Java



A variable is a name given to a memory location which can be used to perform operations on the value stored in the memory location. It is the basic unit of storage in a program and the value stored in the variable can be changed during program execution.

In Java, all the variables must be declared before use.

How to declare variables?




datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Examples
float interestRate; // Declaring float variable
int speed = 20; // Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable

Types of variables
Local Variables
Instance Variables
Static Variables




Local Variables
A variable defined within a block or method or constructor is called local variable.
These variables are created when the method or constructor is called and destroyed after exiting from the method or constructor.
The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variables only within that method/constructor.

public class EmployeeAge {

            public static int getAge(int dobYear) {
                        // local variable age
                        int age = 0;
                        int currentYear = 2019;
                        age = currentYear - dobYear;
                        return age;
            }

            public static void main(String args[]) {
                        System.out.println("Age of Rajesh: " + getAge(1991));
            }
}
Output:
Age of Rajesh: 28

Important points about local variable
  • Initialization of Local Variable is Mandatory.
  • A local variable cannot be defined with the static keyword.

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.

class Student {
            public String name;
            public int age;
            public int rollNo;

            public Student(String name) {
                        this.name = name;
            }
}

public class TestInstanceVariable {

            public static void main(String[] args) {
                        Student std1 = new Student("Nitin");
                        std1.age = 19;
                        std1.rollNo = 1;

                        Student std2 = new Student("Arun");
                        std2.age = 20;
                        std2.rollNo = 2;

                        System.out.println("\nStudent1 information");
                        System.out.printf("Name:%s Age:%d RollNo:%d ", std1.name, std1.age, std1.rollNo);

                        System.out.println("\nStudent2 information");
                        System.out.printf("Name:%s Age:%d RollNo:%d ", std2.name, std2.age, std2.rollNo);
            }
}

As you can see in the above program age, rollNo and name are instance variables. In case we have multiple objects, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of the instance variable.

Important points about instance variable
  • Initialization of instance variable is not Mandatory. If it not declared, will be assigned to default value.
  • Instance Variable can be accessed only by creating objects.

Static Variables
Static variables are also known as Class variables.
Static variables are declared similarly as instance variables, the only difference is, static variables are declared using the static keyword within a class outside any method or constructor.
Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
Static variables are created when the class is loaded in JVM and destroyed the end of executions.

class StudentSectionC {
            public String name;
            public static String section;

            public StudentSectionC(String name) {
                        this.name = name;
            }
}

public class TestInstanceVariable {

            public static void main(String[] args) {
                        StudentSectionC std1 = new StudentSectionC("Nitin");
                        StudentSectionC std2 = new StudentSectionC("Arun");
                        StudentSectionC.section = "C";

                        System.out.println("\nStudent1 information");
                        System.out.printf("Name:%s Section:%s ", std1.name, std1.section);

                        System.out.println("\nStudent2 information");
                        System.out.printf("Name:%s Section:%s ", std2.name, std2.section);
            }
}
Output:
Student1 information
Name:Nitin Section:C
Student2 information
Name:Arun Section:C

Important points about static variable
  • Initialization of Static Variable is not Mandatory. If it not declared, will be assigned to default value like instance variables.
  • To access static variables, we need not create an object of that class, we can simply access the variable using the class name only.
  • If we access the static variable like Instance variable (through an object), the compiler will show the warning message and it won’t halt the program. The compiler will replace the object name to class name automatically.
  • If we access the static variable without the class name, Compiler will automatically append the class name.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...