×

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

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.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.