×

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

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 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.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 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.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

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...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.