×

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java.

In Java, variables must be declared before they can be used. Java allows variables to be initialized dynamically, using any expression valid at the time, the variable is declared.

Declaration

int x = 15;

int y = Math.sqrt(a * a + b * b); // Here variable y will get the value

dynamically

//depending on the values of a, b.

Scope

The opening and closing of the curly braces describe the scope. A scope determines what objects are visible to other parts of our program. It also determines the lifetime of those objects.

Variables are created when their scope is entered and destroyed when their scope is left.

It means variables that are declared within a method will not hold their values outside it. Also, a variable declared within a block will lose its value when the block is left.

Thus, the life-cycle of a variable is within its scope.

Here are the available scopes of variables:

  • Local variables (also known as method-local variables)
  • Method parameters (also known as method arguments)
  • Instance variables (also known as attributes, fields, and non-static variables)
  • Class variables (also known as static variables)

Local variables: Local variables are defined within a method, constructor or block. We can not apply an access modifier to local variables. Local variables are visible only within the scope of the declared method, block, or constructor. The local variable should be assigned before their first use. The scope of a local variable depends on the location of its declaration within a method. The scope of local variables defined within a loop, if - else, switch statement or within a code block (marked with {} ) is limited to these curly braces. Local variables defined outside any of these constructs are accessible across the complete method.

Method parameters: The variables that accept values in a method signature are called method parameters. They’re accessible only in the method that defines them.

Instance variables: An instance variable is declared within a class, outside all the methods. It’s accessible to all the instance (or non-static) methods defined in a class.

Class variables: A class variable is defined by using the static keyword. A class variable belongs to a class, not to individual objects of the class. A class variable is shared across all objects. Objects don’t have a separate copy of the class variables. We don’t even need an object to access a class variable. It can be accessed by using the name of the class in which it is defined:

Comparing the use of local variables in different scopes.

  • Local variables are defined within a method and are normally used to store the intermediate results of a calculation.
  • Method parameters are used to pass values to a method. These values can be manipulated and may also be assigned to instance variables.
  • Instance variables are used to store the state of an object. These are the values that need to be accessed by multiple methods.
  • Class variables are used to store values that should be shared by all the objects of a class.

Variables follow naming conventions, which help improve code readability and maintainability. Variable names should start with a letter (a-z, A-Z), underscore (_), or dollar sign ($) and should not be a Java keyword. It is recommended to use camelCase for variable names.

Variable Shadowing: Shadowing occurs when a local variable has the same name as an instance or class variable. In such cases, the local variable takes precedence within its scope. To access the instance variable, we use the 'this' keyword:

class Example {

int x = 10;

void show(int x) {

System.out.println("Local variable: " + x);

 System.out.println("Instance variable: " + this.x);

 }

 }

Volatile Variables: A variable declared as 'volatile' ensures that multiple threads access its value directly from main memory, avoiding caching issues in a multi-threaded environment:

volatile int sharedResource;

Multiple Choice Questions

1. What is the correct way to declare a variable in Java?

a) int x;

b) x int;

c) int = x;

d) x = 10;

Answer: a) int x;

2. Which of the following is true about local variables?

a) They can be accessed from any method in the class.

b) They must be initialized before use.

c) They are shared across all objects of a class.

d) They are defined using the static keyword.

Answer: b) They must be initialized before use.

3. What is the default value of an instance variable of type int?

a) null

b) 0

c) 1

d) undefined

Answer: b) 0

4. Which keyword is used to define a class variable?

a) volatile

b) static

c) final

d) const

Answer: b) static

5. What will be the output of the following code?

public class Test {

    int x = 5;

    void show(int x) {

        System.out.println("Local: " + x);

        System.out.println("Instance: " + this.x);

    }

    public static void main(String[] args) {

        Test obj = new Test();

        obj.show(10);

    }

}

a) Local: 5, Instance: 10

b) Local: 10, Instance: 5

c) Local: 10, Instance: 10

d) Compilation error

Answer: b) Local: 10, Instance: 5

6. Which of the following statements about volatile variables is true?

a) They cannot be modified after initialization.

b) They are cached for faster access.

c) They ensure visibility in multi-threaded environments.

d) They must be declared as static.

Answer: c) They ensure visibility in multi-threaded environments.

7. What happens when a local variable has the same name as an instance variable?

a) The compiler throws an error.

b) The local variable takes precedence within its scope.

c) The instance variable is always accessed.

d) The program crashes at runtime.

Answer: b) The local variable takes precedence within its scope.

8. What is the naming convention for variables in Java?

a) Variable names can start with a number.

b) Variable names should use camelCase.

c) Variable names must contain only uppercase letters.

d) Variable names should use spaces for readability.

Answer: b) Variable names should use camelCase.


Related Topics

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.