×

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

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Manachers Algorithm in Java

Here, we'll go over the four scenarios once more in an effort to approach them differently and use the same strategy. The values of (centerRightPosition - currentRightPosition) and LPS length at...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Split the Number String into Primes in Java

Given is a string that only contains digits and serves to represent a number. Our goal is to split the string of numbers in a way that ensures each segment...

2 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.