Types of Java Variables
Overview
In this tutorial, we will discuss different types of Java variables. Variables in Java can be broadly classified into three types:
- Class variables
- Instance variables
- Local variables
Class Variables
Class variables are also called as static variables . Static variables are declared with the keyword static. Public static variables can be accessed with the class name outside the class. For example:
<class name>.<static variable>
Dog.numOfDogs
Example
numOfDogs variable in the code snippet is a static variable. There is only one copy of the static variable per class.
Instance Variable
Instance variables are also called as object variables. Instance variables are created when the object is created and the memory is allocated in the heap. Each object has one copy of the instance variables. Variables that hold the state of the object would be declared as instance variables.
Variables name, height, weight are object variables in the example.
Local Variable
Local variables are declared inside the methods, constructors and java blocks. Local variables have limited scope. They are only visible in the declared method or constructor. They cannot be accessed outside the method.
Code Listing
package com.testingdocs.demo; public class Dog { public static int numOfDogs=0; // static variable or class variable private String name; // instance variables private double height; private double weight; //Constructor public Dog(String name, double height, double weight) { this.name = name; this.height = height; this.weight = weight; numOfDogs++; } public void sound() { String dogSound= "bow-wo bow-wo"; //local variable System.out.println(dogSound); } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public static void main(String[] args) { Dog dogObject1= new Dog("Max",37.5,17.5); Dog dogObject2= new Dog("Tommy",30.0,12.75); } }
dogSound is a local method variable declared in the method sound(). The variable can only be accessed inside the sound() method.
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :