Skip To Content
Skip To Content
geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests
Sign In
Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate
Variables in Java
Java variable is a name given to a memory location. It is the basic unit of storage
in a program.
Variables in Java
From the image, it can be easily perceived that while declaring a variable, we need
to take care of two things that are:
Variable Initialization
Assigning value by taking input
How to Initialize Variables in Java?
It can be perceived with the help of 3 components that are as follows:
Illustrations:
Local Variables
Instance Variables
Static Variables
Types of Variables in Java
Let us discuss the traits of every type of variable listed here in detail.
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
The Local variable is created at the time of declaration and destroyed after
exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variables
are declared, i.e., we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined
scope.
Time Complexity of the Method:
Time Complexity: O(1)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
class GFG {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
Output
Local Variable: 10
Example :
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// x is a local variable
int x = 10;
if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
System.out.println(result);
}
Output
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of
any method, constructor, or block.
As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier, then the default access specifier will be
used.
Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable. For String it is null, for float it is
0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
Instance variables can be accessed only by creating objects.
We initialize instance variables using constructors while creating an object. We
can also use instance blocks to initialize the instance variables.
The complexity of the method:
Time Complexity: O(1)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
class GFG {
// Declared Instance Variable
public String geek;
public int i;
public Integer I;
public GFG()
{
// Default Constructor
// initializing Instance Variable
this.geek = "Shubham Jain";
}
// Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
System.out.println("Default value for int is "
+ name.i);
Output
Geek name is: Shubham Jain
Default value for int is 0
Default value for Integer is null
3. Static Variables
Static variables are also known as class variables.
class GFG {
// Declared static variable
public static String geek = "Shubham Jain";
Output
Geek Name is : Shubham Jain
Differences Between the Instance Variables and the Static Variables
Now let us discuss the differences between the Instance variables and the Static
variables:
Each object will have its own copy of an instance variable, whereas we can only
have one copy of a static variable per class, irrespective of how many objects we
create. Thus, static variables are good for memory management.
Changes made in an instance variable using one object will not be reflected in
other objects as each object has its own copy of the instance variable. In the case
of a static variable, changes will be reflected in other objects as static
variables are common to all objects of a class.
We can access instance variables through object references, and static variables
can be accessed directly using the class name.
Instance variables are created when an object is created with the use of the
keyword ‘new’ and destroyed when the object is destroyed. Static variables are
created when the program starts and destroyed when the program stops.
Syntax: Static and instance variables
class GFG
{
// Static variable
static int a;
// Instance variable
int b;
}
Conclusion
The Important points to remember in the articles are mentioned below:
Variables in Java is a data container that saves the data values during Java
program execution.
There are three types of variables in Java Local variables, static variables, and
instance variables.
FAQs on Variables in Java
What are variables in Java?
Variables are the containers in Java that can store data values inside them.
Local Variables
Static Variables
Instance Variables
How to declare variables in Java examples?
We can declare variables in java with syntax as mentioned below:
data_type variable_name;
Example:
Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
600
Previous Article
Operators in Java
Next Article
Scope of Variables In Java
Read More
Down Arrow
Similar Reads
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic
Variables The Local variables and Instance variables are together called Non-Static
variables. Hence it can also be said that the Java variables can be divided into 2
categories: Static Variables: When a variable is declared as static, then a single
copy of the vari
4 min read
Using Static Variables in Java
Here we will discuss the static variables in java. Java actually doesn’t have the
concept of Global variable. To define a Global variable in java, the keyword static
is used. The advantage of the static variable is discussed below. Now geeks you
must be wondering out what are the advantages of static variable, why to
incorporate in our program. Now
3 min read
Variables in Java Do Not Follow Polymorphism and Overriding
Variables in Java do not follow polymorphism. Overriding is only applicable to
methods but not to variables. In Java, if the child and parent class both have a
variable with the same name, Child class's variable hides the parent class's
variable, even if their types are different. This concept is known as Variable
Hiding. In the case of method over
2 min read
Local Variables in Java
The variables declared inside the body of the method are termed local variables. A
function is a collection of statements that are designed to perform a specific
task. Functions take certain input(s) and its parameter and give output or return
value. A function is created that one can not have to write the same code, again
and again, we call to use
6 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there
is a necessity of using the Wrapper Class. In this article, we can discuss briefly
both wrapper class and primitive data type. A primitive data type focuses on
variable values, without any additional methods.The Default value of Primitive
class variables are given b
3 min read
Environment Variables in Java
In Java, Environment variables are widely used by operating systems to deliver
configuration data to applications. Environment variables are key/value pairs with
both the key and the value being strings, similar to properties in the Java
platform. What are Environment Variables in Java?In Java, Environment variables are
values that are stored outsi
5 min read
Are static local variables allowed in Java?
Unlike C/C++, static local variables are not allowed in Java. For example,
following Java program fails in compilation with error "Static local variables are
not allowed" C/C++ Code class Test { public static void main(String args[])
{ System.out.println(fun()); } static int fun() { static int x= 10; //Error: Static
local variables are not allowed
1 min read
Assigning values to static final variables in Java
Assigning values to static final variables in Java: In Java, non-static final
variables can be assigned a value either in constructor or with the declaration.
But, static final variables cannot be assigned value in constructor; they must be
assigned a value with their declaration.For example, following program works fine.
Java Code class Test { //
1 min read
Final local variables in Java
Prerequisite : final keyword, Variables, Scope of Variables A local variable in
Java is a variable that’s declared within the body of a method. Then you can use
the variable only within that method. Other methods in the class aren’t even aware
that the variable exists. If we are declaring a local variable then we should
initialize it within the blo
2 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There
are two types of data variables in a class: Instance variables : Instance variables
are declared in a class, but outside a method, constructor or any block. When a
space is allocated for an object in the heap, a slot for each instance variable
value is created. Instan
5 min read
Article Tags :
Java
java-basics
Practice Tags :
Java
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Avail 90% Refund
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox