Variable in Java With Example

Let’s learn about the Variable in Java, In simple words, A Java variable is a piece of memory that used to store the data. Every variable must be declared, use a data type. For example, a variable could be declared to use one of the eight primitive data types: byte, short, int, long, float, double, char or boolean.

In Java, we have 3 Types of Variables.

  1. Local Variables

  2. Instance Variables

  3. Static Varibales


Variable Declaration —

How can you declare the variable depends on the type of variable. However, we follow the similar syntax —

type variable name ( like : int i)


Variable Assignment

In value assignment, java follows the below-mentioned syntax.

variables name = Value ;    (like i = 10 😉

Example :

In below example first, we declared the variable “i” and next step we assign the value to variable “i”.

In the next step, we are declaring and assigning the value in the single move.

package com.Seleniumbix.Corejava;

Local Variables

  • Local variables are variable that is declared inside the method.
  • Local variables are used to store the temporary values.
  • Local variable destroyed when method executes completely.
  • Local variables live inside the method body only.


Instance Variables

  • An instance variable is declared inside the class but outside the method or constructor body.
  • Instance variable created inside the java heap. It’s created when an object is created.
  • Instance variable declared without static keyword.
  • Instance variables are visible for all methods, constructors, and block in the class. Also, Instance variables are accessible within the subclasses base on the access modifier.


Static Variables

  • A variable declared with the keyword static is called static or class variable. It should be declared outside the method or constructor.
  • Exactly one copy of the static variable in existence, regardless of how many times the class has been instantiated.
  • Static variables are used to declare the constants in the class.
  • Static variables can be accessed using the class name only like the class name.variable name. We don’t need the reference of the class to access the static variables.


Selenium Testing Video Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply