variables-in-java

Variables in Java

A variable is a name given to a memory area. It is the fundamental unit of capacity in a program.

  • The worth put away in a variable can be changed during program execution.
  • A variable is just a name given to a memory area, all the tasks done on the variable impacts that memory area.
  • In Java, all the factors should be announced before use.

How to declare variables?

We can declare variables in java as follows:

type: Type of data that can be stored in this variable.
name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two ways:

  • Variable Initialization
  • Assigning value by taking input

How to initialize 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 simpleInterest; //Declaring float variable
int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable

Types of variables

There are three types of variables in Java:

  • Local Variables
  • Instance Variables
  • Static Variables

Let us now learn about each one of these variables in detail.

  1. Neighborhood Variables: A variable characterized inside a square or technique or constructor is called nearby factor.
  • These variable are made when the square in entered or the capacity is called and obliterated in the wake of leaving from the square or when the call gets back from the capacity.
  • The extent of these factors exists just inside the square in which the variable is announced. for example we can get to these variable just inside that block.
  • Initilisation of Local Variable is Mandatory.

 

Sample Program 1:

public class StudentDetails {
    public void StudentAge()
    {
        // local variable age
        int age = 0;
        age = age + 5;
        System.out.println("Student age is : " + age);
    }
 
    public static void main(String args[])
    {
        StudentDetails obj = new StudentDetails();
        obj.StudentAge();
    }
}
Output:

Student age is : 5

In the above program, the variable age is a local variable to the function StudentAge(). If we use the variable age outside StudentAge() function, the compiler will produce an error as shown in below program.

Sample Program 2:

public class StudentDetails {
    public void StudentAge()
    { // local variable age
        int age = 0;
        age = age + 5;
    }
 
    public static void main(String args[])
    {
        // using local variable age outside it's scope
        System.out.println("Student age is : " + age);
    }
}

Output:

Compilation Error in java code :- 
prog.java:12: error: cannot find symbol
        System.out.println("Student age is : " + age);
                                                 ^
  symbol:   variable age
  location: class StudentDetails
1 error
  1. Case Variables: Instance factors are non-static factors and are pronounced in a class outside any strategy, constructor or square.
  • As example factors are pronounced in a class, these factors are made when an object of the class is made and annihilated when the item is wrecked.
  • In contrast to neighborhood factors, we may utilize access specifiers for example factors. On the off chance that we don’t indicate any entrance specifier, at that point the default access specifier will be utilized.
  • Initilisation of Instance Variable isn’t Mandatory. Its default esteem is 0
  • Case Variable can be gotten to simply by making objects.

 

Sample Program:

import java.io.*;
class Marks {
    // These variables are instance variables.
    // These variables are in a class
    // and are not inside any function
    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;
 
        // displaying marks for first object
        System.out.println("Marks for first object:");
        System.out.println(obj1.engMarks);
        System.out.println(obj1.mathsMarks);
        System.out.println(obj1.phyMarks);
 
        // displaying marks for second object
        System.out.println("Marks for second object:");
        System.out.println(obj2.engMarks);
        System.out.println(obj2.mathsMarks);
        System.out.println(obj2.phyMarks);
    }
}
Output:

Marks for first object:
50
80
90
Marks for second object:
80
60
85

As should be obvious in the above program the variables, engMarks , mathsMarks , phyMarksare example factors. In the event that we have numerous items as in the above program, each article will have its own duplicates of occurrence factors. It is obvious from the above yield that each item will have its own duplicate of occasion variable.

Static Variables: Static factors are otherwise called Class factors.

  • These factors are pronounced likewise as example factors, the thing that matters is that static factors are proclaimed utilizing the static catchphrase inside a class outside any technique constructor or square.
  • Not at all like occasion factors, we can just have one duplicate of a static variable for every class regardless of the number of articles we make.
  • Static factors are made toward the beginning of program execution and crushed naturally when execution closes.
  • Initilisation of Static Variable isn’t Mandatory. Its default esteem is 0
  • On the off chance that we access the static variable like Instance variable (through an item), the compiler will show the admonition message and it won’t end the program. The compiler will supplant the item name to class name consequently.
  • On the off chance that we access the static variable without the class name, Compiler will naturally affix the class name.
  • To access static variables, we need not create an object of that class, we can simply access the variable as
class_name.variable_name;

Sample Program:

import java.io.*;
class Emp {
 
    // static variable salary
    public static double salary;
    public static String name = "Harsh";
}
 
public class EmpDemo {
    public static void main(String args[])
    {
 
        // accessing static variable without object
        Emp.salary = 1000;
        System.out.println(Emp.name + "'s average salary:"
                           + Emp.salary);
    }
}
Output:

Harsh's average salary:1000.0

Instance variable Vs Static variable

Each article will have its own copy of example variable while We can just have one copy of a static variable for every class independent of the number of items we make.

Changes made in an occasion variable utilizing one item will not be reflected in different articles as each article has its own duplicate of case variable. If there should be an occurrence of static, changes will be reflected in different items as static factors are normal to all object of a class.

We can get to case variables through object references and Static Variables can be accessed directly utilizing class name.

Syntax for static and instance variables:

class Example
    {
        static int a; //static variable
        int b;        //instance variable
    }

Similar Articles:

 

  • Extent of Variables in Java
  • Examination of static watchword in C++ and Java
  • Are static neighborhood factors permitted in Java?
  • Example Variable Hiding in Java

This article is contributed by Harsh Agarwal. On the off chance that you like GeeksforGeeks and might want to contribute, you can likewise compose an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article showing up on the GeeksforGeeks principle page and help different Geeks.

If it’s not too much trouble compose remarks on the off chance that you discover anything erroneous, or you need to share more information about the point examined previously.

Consideration peruser! Try not to quit adapting now. Get hold of the relative multitude of important Java Foundation and Collections ideas with the Fundamentals of Java and Java Collections Course at an understudy benevolent cost and become industry prepared.