Master Java variables! From declaration to usage, grasp the fundamentals. Explore data types, scopes, and best practices for effective variable handling in Java programming. Start your Java journey now!
A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed.
int data=50;//Here data is variable
There are three types of variables in Java:
A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among instances.
A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Output:
20
public class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}
Output:
10
10.0
public class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
Output:
10.5
10
class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}}
Output:
130
-126
class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c);
}}
Output:
20
In Java, Variables are the data containers that save the data values during Java program execution. Every Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable is a memory location name for the data.
Java variable is a name given to a memory location. It is the basic unit of storage in a program.
We can declare variables in Java as pictorially depicted below as a visual aid.
From the image, it can be easily perceived that while declaring a variable, we need to take care of two things that are:
In this way, a name can only be given to a memory location. It can be assigned values in two ways:
It can be perceived with the help of 3 components that are as follows:
Illustrations:
// Declaring float variable
float simpleInterest;
// Declaring and initializing integer variable
int time = 10, speed = 20;
// Declaring and initializing character variable
char var = 'h';
Now let us discuss different types of variables which are listed as follows:
Let us discuss the traits of every type of variable listed here in detail.
A variable defined within a block or method or constructor is called a local variable.
Time Complexity: O(1)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
// Java Program to implement
// Local Variables
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Output
Local Variable: 10
Example :
package a;
public class LocalVariable {
public static void main(String[] args)
{
// x is a local variable
int x = 10;
// message is also a local
// variable
String message = "Hello, world!";
System.out.println("x = " + x);
System.out.println("message = " + message);
if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
System.out.println(result);
}
// Uncommenting the line below will result in a
// compile-time error System.out.println(result);
for (int i = 0; i < 3; i++) {
String loopMessage
= "Iteration "
+ i; // loopMessage is a local variable
System.out.println(loopMessage);
}
// Uncommenting the line below will result in a
// compile-time error
// System.out.println(loopMessage);
}
}
Output :
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block.
Time Complexity: O(1)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
// Java Program to demonstrate
// Instance Variables
import java.io.*;
class GFG {
// Declared Instance Variable
public String geek;
public int i;
public Integer I;
public GFG()
{
// Default Constructor
// initializing Instance Variable
this.codequs = "Shubham Jain";
}
// Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Codequsname is: " + name.codequs);
System.out.println("Default value for int is "
+ name.i);
// toString() called internally
System.out.println("Default value for Integer is "
+ name.I);
}
}
Output
codequs name is: Shubham Jain
Default value for int is 0
Default value for Integer is null
Static variables are also known as class variables.
Time Complexity: O(1)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
// Java Program to demonstrate
// Static variables
import java.io.*;
class GFG {
// Declared static variable
public static String codequs= "Shubham Jain";
public static void main(String[] args)
{
// geek variable can be accessed without object
// creation Displaying O/P GFG.geek --> using the
// static variable
System.out.println("Codequs Name is : " + GFG.codequs);
// static int c=0;
// above line,when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}
Output
Codequs Name is : Shubham Jain
Now let us discuss the differences between the Instance variables and the Static variables:
Syntax: Static and instance variables
class GFG
{
// Static variable
static int a;
// Instance variable
int b;
}
The Important points to remember in the articles are mentioned below:
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
String
- stores text, such as "Hello". String values are surrounded by double quotesint
- stores integers (whole numbers), without decimals, such as 123 or -123float
- stores floating point numbers, with decimals, such as 19.99 or -19.99char
- stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotesboolean
- stores values with two states: true or falseTo create a variable, you must specify the type and assign it a value:
type variableName = value;
Where type is one of Java's types (such as int
or String
), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Create a variable called name of type String
and assign it the value "John":
String name = "John";
System.out.println(name);
To create a variable that should store a number, look at the following example:
Create a variable called myNum of type int
and assign it the value 15:
int myNum = 15;
System.out.println(myNum);
You can also declare a variable without assigning the value, and assign the value later:
int myNum;
myNum = 15;
System.out.println(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Change the value of myNum
from 15
to 20
:
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);
If you don't want others (or yourself) to overwrite existing values, use the final
keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only):
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a final variable
A demonstration of how to declare variables of other types:
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Variables play a fundamental role in the world of programming, and Java, being one of the most widely used programming languages, relies heavily on them. Whether you are an experienced Java developer or just starting to explore the basics of programming, understanding variables in Java is essential to harnessing the power of this language.
Java variables act as containers that store data and allow us to manipulate and operate on that data within our programs. They provide a way to hold information temporarily or permanently, enabling us to create dynamic and interactive applications. By using variables, we can assign values to them, modify those values, and perform various computations based on the stored data.
Java, being a statically-typed language, requires us to declare variables explicitly before using them. This declaration process involves specifying the type of data a variable will hold, giving it a meaningful name, and optionally assigning an initial value. Once declared, we can access and modify the data stored in a variable throughout the program, making it a powerful tool for building complex applications.
Variables in Java come in different types, including primitive types such as integers, floating-point numbers, characters, and booleans, as well as more complex types like objects and arrays. Each type has its own characteristics and usage patterns, and understanding them is crucial for effective programming.
Here, we will learn everything about variables in Java, including their types, rules for declaration and initialization, and examples, and much more.
The word variable is a combination of two words, ‘vary’ and ‘able’, meaning its value can be changed. Java Variable is a named memory location that programs can easily manipulate. In other words, it is a data container to store values of data during the execution of a Java program.
Each variable is assigned a specific data type, which determines the type of quantity of the value it holds along with the range of values that can be stored in the memory and the set of operations that are possible to apply to a variable.
A variable is a basic storage unit in a program that has the following features:
Here's an example of a variable declaration and initialization in Java:
public class Example {
public static void main(String[] args) {
// Declaring and initializing a variable
int age = 25;
// Printing the value of the variable
System.out.println("Age: " + age);
// Modifying the value of the variable
age = 30;
// Printing the updated value of the variable
System.out.println("Updated Age: " + age);
}
}
In this example, we declare a variable called age of type int and initialize it with the value 25. We then print the value of the variable using System.out.println(). After that, we modify the value of the age variable to 30 and print the updated value.
To declare a variable in Java, it’s required to specify the data type and assign a unique name to the variable.
The diagram below accurately shows Java variables declaration:
According to the diagram, it is clear that we need to consider two key factors while declaring a variable:
datatype: It means the type of data stored in the variable.
data_name: It signifies the name given to the variable.
A name is given to a memory location, which can be assigned values in two ways:
Variable Initialization
Assigning value by taking input
Here's an example of variable declaration in Java:
public class Example {
public static void main(String[] args) {
// Variable declaration
int age;
double salary;
String name;
boolean isEmployed;
In this example, we declare four variables: age of type int, salary of type double, name of type String, and isEmployed of type boolean.
Variable initialization is perceived with the help of three components:
You can initialize variables in Java at the time of declaration or later in the code.
Here are a few examples:
int age = 25;
double salary = 50000.00;
String name = "John Doe";
boolean isEmployed = true;
int age; // Declaration
age = 25; // Initialization
double salary; // Declaration
salary = 50000.00; // Initialization
String name; // Declaration
name = "John Doe"; // Initialization
boolean isEmployed; // Declaration
isEmployed = true; // Initialization
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your name: ");
String name = scanner.next();
System.out.println("Age: " + age);
System.out.println("Name: " + name);
scanner.close();
}
}
There are three variable types in the Java programming language:
Variables that can’t be defined with the ‘static’ keyword are called local variables in Java. They are declared inside the method body and used only within that method, while other methods in a class don’t know that the variable exists.
A local variable in Java is created when the constructor, block, or method is entered and destroyed when it exits from the constructor, block, or method.
They exist only within the constructor, method, or block they are declared, which means we can access the local variables only within the declared block.
They are implemented at the stack level internally.
You can’t use access modifiers for local variables in Java.
It is necessary to initialize local variables before using them in a defined scope.
Local variables have no default value, so they are declared and assigned an initial value before the first use.
Example of Local Variable in Java
public class LocalVariableExample {
public static void main(String[] args) {
int x = 5; // Local variable declaration and initialization
System.out.println("The value of x is: " + x);
// Updating the value of x
x = 10;
System.out.println("The updated value of x is: " + x);
// Using a local variable in a loop
for (int i = 0; i < 5; i++) {
System.out.println("The value of i is: " + i);
}
// Uncommenting the line below will result in a compile-time error
// System.out.println("The value of i outside the loop is: " + i);
}
}
In the example, we declare a local variable named x of type int inside the main method. We initialize it with the value 5 and then print its value to the console. Later, we update the value of x to 10 and print the updated value.
Additionally, we show the usage of a local variable i within a for loop. The i variable is declared within the loop's scope and is used to control the loop iteration. It is only accessible within the loop block and cannot be accessed outside of it.
If you uncomment the last line, an error will occur because i is a local variable limited to the scope of the for loop, and attempting to access it outside the loop is not allowed.
Instance variables are declared within a class but outside a method. They are defined without the ‘static’ keyword. As their value is instance-specific and they are not shared among instances, they are called instance variables.
These types of variables in Java are declared in a class and outside the body of a method, block, or constructor. They are declared at a class level before or after use.
They are created when an object is created using the ‘new’ keyword and destroyed when the object is destroyed.
Initialization of instance variables is not necessary, and their default value is based on the data type. For example, String is null; int is 0, the float is 0.0f, and the Wrapper class, such as integer, is null.
Intialialization is possible using constructors while creating an object or using instance blocks.
They hold values referenced by more than one method, block, constructor, or key part of an object’s state present throughout the class.
Unlike local variables, instance variables can use access modifiers. If no access modifier is specified, the default modifier will be used.
It is possible to access instance variables only by creating objects. You can access instance variables directly by calling the variable name within a class. When they are within static methods, they must be accessed using the fully qualified name.
They are visible for all blocks, constructors, and methods in a class. It is better to make these variables private, but they can have visibility for subclasses by using access modifiers.
They have default values. For example, Boolean has false; default has a 0 value and object reference has a null value. The values are assigned during variable declaration or within the constructor.
Example of Instance Variable in Java:
public class InstanceVariableExample {
private int count; // Instance variable
public void increment() {
count++; // Accessing and modifying the instance variable
}
public void displayCount() {
System.out.println("The count is: " + count); // Accessing the instance variable
}
public static void main(String[] args) {
InstanceVariableExample obj1 = new InstanceVariableExample();
InstanceVariableExample obj2 = new InstanceVariableExample();
obj1.increment();
obj1.displayCount(); // Output: The count is: 1
obj2.increment();
obj2.displayCount(); // Output: The count is: 1
}
}
In the example, we define a class named InstanceVariableExample. Inside this class, we declare an instance variable named count of type int. The count variable is not static, which means it is associated with each instance of the class rather than being shared among all instances.
Within the class, we have two methods: increment() and displayCount(). The increment() method increments the value of the count instance variable by one. The displayCount() method simply prints the value of the count instance variable.
In the main() method, we create two objects (obj1 and obj2) of the InstanceVariableExample class. Each object has its own copy of the instance variable count. We call the increment() method on both objects, and then we call the displayCount() method to print the value of count for each object.
As a result, we see that each object maintains its own separate copy of the instance variable count. When we increment count on one object, it does not affect the value of count in the other object.
Static variable, or a class variable in Java, is declared as static and is initialized only once at the beginning of the program execution. They must be initialized before initializing any instance variables. You can share a single copy of these variables and share it with the instances of the class.
Class variables is another name for static variables in Java. They are declared the same way as instance variables. But the difference is static variables are declared within the static keyword in a class but outside of any method, block, or constructor.
Their visibility is also similar to instance variables. Most class variables are declared public as they need to be available for users of a class.
They can be accessed with the class name ClassName.VariableName. If you access a class variable like an instance variable, the compiler will send a warning message and replace the object name with the class name automatically without stopping the program.
Static variables are created at the beginning of program execution and destroyed automatically once the execution ends.
They are stored in the static memory.
You can have only one copy of a static variable per class, no matter how many objects you create from it.
Initializing static variables is not mandatory. Values can be assigned either during declaration or within the constructor. The default values of these variables are dependent on the data type of the variable. For Boolean, it is false; for String, it is null; for numbers, it is 0; and for the object reference, it is null.
They are hardly used other than being declared constants, which can be final, public/private, and static. Also, constant variables don’t change their initial value.
Example of Static Variable in Java
public class StaticVariableExample {
private static int count; // Static variable
public StaticVariableExample() {
count++; // Incrementing the static variable in the constructor
}
public void displayCount() {
System.out.println("The count is: " + count); // Accessing the static variable
}
public static void main(String[] args) {
StaticVariableExample obj1 = new StaticVariableExample();
obj1.displayCount(); // Output: The count is: 1
StaticVariableExample obj2 = new StaticVariableExample();
obj2.displayCount(); // Output: The count is: 2
}
}
Here, we define a class named StaticVariableExample. Inside this class, we declare a static variable named count of type int. The count variable is declared with the static keyword, which means it is associated with the class itself rather than individual instances (objects) of the class. All objects of the class share the same copy of the static variable.
We also have a constructor in the class, which is invoked when an object is created. In the constructor, we increment the value of the static variable count by one.
The displayCount() method simply prints the value of the static variable count.
In the main() method, we create two objects (obj1 and obj2) of the StaticVariableExample class. When we create each object, the constructor is called, and the static variable count is incremented.
Finally, we call the displayCount() method on both objects, which prints the value of count for each object. Since the static variable is shared among all objects, the count increments for each object creation.
As a result, we see that both objects have access to and modify the same static variable, and any changes made to the static variable are reflected across all instances of the class.
Variables in Java ✘【12 minutes】
Variables in Java
Introduction to Variables in Java
#java