Static Variables in Java – Why and How to Use Static Methods

Edeh Israel Chidera

Static variables and static methods are two important concepts in Java.

Whenever a variable is declared as static, this means there is only one copy of it for the entire class, rather than each instance having its own copy. A static method means it can be called without creating an instance of the class.

Static variables and methods in Java provide several advantages, including memory efficiency, global access, object independence, performance, and code organization.

In this article, you will learn how static variables work in Java, as well as why and how to use static methods.

The Static Keyword in Java

The static keyword is one of the most essential features in the Java programming language. We use it to define class-level variables and methods.

Here is an example of how to use the static keyword:

As you can see above, we declared the count variable as a static variable, while we declared the printCount method as a static method.

When a variable is declared static in Java programming, it means that the variable belongs to the class itself rather than to any specific instance of the class. This means that there is only one copy of the variable in memory, regardless of how many instances of the class are created.

Here's an example. Say we have a Department class that has a static variable called numberOfWorker . We declare and increment the static variable at the constructor level to show the value of the static variable whenever the class object is created.

The results of the above code show that as we create new Department objects, the static variable numberOfWorker retains its value.

When we print out the value of numberOfWorker in the console, we can see that it retains its value across all instances of the Department class. This is because there is only one copy of the variable in memory, and any changes to the variable will be reflected across all instances of the class.

We can also use the static keyword to define static methods.

Static methods are methods that belong to the class rather than to any specific instance of the class. Static methods can be called directly on the class itself without needing to create an instance of the class first. See the code below:

In the above code, the Calculation class has two static methods. The declared static methods can be called directly on the Calculation class without creating an instance of the class first. That is to say, you do not need to create an object of the Calculation class before you access the static add and multiply classes.

The main() method in Java is an example of a static method. The main() method is a special static method that is the entry point for Java applications. The Math class in Java also provides many static methods that perform mathematical operations.

The above code shows that the entry point for Java applications is a static method. It also shows that the max() method is a static method of the Math class and does not require an instance of the Math class to be created.

As you can see, static methods can be useful in providing utility functions that do not necessitate the creation of a class object.

The static keyword is a powerful tool in Java that can help solve many programming challenges. It aids in memory consumption management, improves code consistency, and helps speed up applications.

To prevent unforeseen issues from cropping up in the code, it is crucial to use the static keyword wisely and be aware of its limitations.

Code that relies heavily on static variables and methods can be harder to test because it introduces dependencies between different parts of the program. Static variables and methods can introduce hidden dependencies between different parts of the program, making it harder to reason about how changes in one part of the code might affect other parts.

Code that relies heavily on static variables can also be less flexible and harder to extend over time. Static variables can also lead to concurrency issues if multiple threads access and modify the same variable at the same time.

Lastly, if a static variable is not properly released or disposed of when it is no longer needed, it can lead to memory leaks and other performance issues over time.

By using static variables and methods appropriately, you can create efficient and maintainable code that will be easier to work with over time.

Happy coding!

Technical Writer and Software Developer

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Guru99

Static Variable in Java: What is Static Block & Method [Example]

James Hartman

  • Static Variables
  • Static Methods
  • Static Blocks Of Code.

Let’s look at static variables and static methods first.

What is Static Variable in Java?

Static variable in Java is variable which belongs to the class and initialized only once at the start of the execution. It is a variable which belongs to the class and not to object(instance ). Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.

  • A single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object

What is Static Method in Java?

Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. It is a method which belongs to the class and not to the object(instance). A static method can access only static data. It cannot access non-static data ( instance variables ).

  • A static method can call only other static methods and can not call a non-static method from it.
  • A static method can be accessed directly by the class name and doesn’t need any object
  • A static method cannot refer to “this” or “super” keywords in anyway

Note: main method is static, since it must be accessible for an application to run, before any instantiation takes place.

Example: How to call static variables & methods

Step 1) Copy the following code into a editor

Step 2) Save & Compile the code. Run the code as, java Demo .

Step 3) Expected output show below

Java Static Methods and Variables

Following diagram shows, how reference variables & objects are created and static variables are accessed by the different instances.

Java Static Methods and Variables

Step 4) It is possible to access a static variable from outside the class using the syntax ClassName.Variable_Name . Uncomment line # 7 & 8 . Save , Compile & Run . Observe the output.

Step 5) Uncomment line 25,26 & 27 . Save , Compile & Run.

What is Static Block in Java?

The static block is a block of statement inside a Java class that will be executed when a class is first loaded into the JVM . A static block helps to initialize the static data members , just like constructors help to initialize instance members.

Following program is the example of java static block.

Example: How to access static block

you will get following output of the program.

  • Program to Print Prime Number From 1 to 100 in Java
  • Palindrome Number Program in Java Using while & for Loop
  • Bubble Sort Algorithm in Java: Array Sorting Program & Example
  • Insertion Sort Algorithm in Java with Program Example
  • Selection Sorting in Java Program with Example
  • Abstract Class vs Interface in Java – Difference Between Them
  • 100+ Java Interview Questions and Answers (2024)
  • JAVA Tutorial PDF: Basics for Beginners (Download Now)

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator
  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors

Java Static Keyword

  • Java Strings

Java Access Modifiers

  • Java this Keyword

Java final keyword

  • Java Recursion
  • Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

Java Nested and Inner Class

Java Nested Static Class

  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

  • What is a static keyword in Java?

In Java, if we want to access class members, we must first create an instance of the class. But there will be situations where we want to access class members without creating any variables.

In those situations, we can use the static keyword in Java. If we want to access class members without creating an instance of the class, we need to declare the class members static.

The Math class in Java has almost all of its members static. So, we can access its members without creating instances of the Math class. For example,

In the above example, we have not created any instances of the Math class. But we are able to access its methods: abs() and pow() and variables: PI and E .

It is possible because the methods and variables of the Math class are static.

  • Static Methods

Static methods are also called class methods. It is because a static method belongs to the class rather than the object of a class.

And we can invoke static methods directly using the class name. For example,

Here, we can see that the static method can be accessed directly from other classes using the class name.

In every Java program, we have declared the main method static . It is because to run the program the JVM should be able to invoke the main method during the initial phase where no objects exist in the memory.

Example 1: Java static and non-static Methods

In the above program, we have declared a non-static method named multiply() and a static method named add() inside the class StaticTest .

Inside the Main class, we can see that we are calling the non-static method using the object of the class ( st.multiply(2, 2) ). However, we are calling the static method by using the class name ( StaticTest.add(2, 3) ).

  • Static Variables

In Java, when we create objects of a class, then every object will have its own copy of all the variables of the class. For example,

Here, both the objects test1 and test2 will have separate copies of the variable age. And, they are different from each other.

However, if we declare a variable static, all objects of the class share the same static variable. It is because like static methods, static variables are also associated with the class. And, we don't need to create objects of the class to access the static variables. For example,

Here, we can see that we are accessing the static variable from the other class using the class name.

Example 2: Java static and non-static Variables

In the above program, we have declared a non-static variable named min and a static variable named max inside the class Test .

Inside the Main class, we can see that we are calling the non-static variable using the object of the class ( obj.min + 1 ). However, we are calling the static variable by using the class name ( Test.max + 1 ).

Note : Static variables are rarely used in Java. Instead, the static constants are used. These static constants are defined by static final keyword and represented in uppercase. This is why some people prefer to use uppercase for static variables as well.

Access static Variables and Methods within the Class

We are accessing the static variable from another class. Hence, we have used the class name to access it. However, if we want to access the static member from inside the class, it can be accessed directly. For example,

Here, we are able to access the static variable and method directly without using the class name. It is because static variables and methods are by default public. And, since we are accessing from the same class, we don't have to specify the class name.

  • Static Blocks

In Java, static blocks are used to initialize the static variables. For example,

Here we can see that we have used a static block with the syntax:

The static block is executed only once when the class is loaded in memory. The class is loaded if either the object of the class is requested in code or the static members are requested in code.

A class can have multiple static blocks and each static block is executed in the same sequence in which they have been written in a program.

Example 3: Use of static block in java

In the above program. as soon as the Main class is loaded,

  • The value of a is set to 23 .
  • The first static block is executed. Hence, the string First Static block is printed and the value of b is set to a * 4 .
  • The second static block is executed. Hence, the string Second Static block is printed and the value of max is set to 30 .
  • And finally, the print statements inside the method display() are executed.
  • Nested Static Class

In Java, we can declare a class inside another class. Such classes are known as nested classes. Nested classes are of 2 types:

  • Static Nested Classes
  • Non-static Nested Classes

For example,

To learn more, visit the Java Nested Class .

Table of Contents

  • Static Variables and Methods within the Class

Sorry about that.

Related Tutorials

Java Tutorial

Static Variable in Java

Java Course - Mastering the Fundamentals

A static variable is associated with a class rather than an instance. A static field is declared using the static keyword . Static variables are shared across all instances of a class.

There is only one copy of a static variable per class. Non-static variables cannot be called inside static methods .

If any class instance modifies a static variable's value, the change is reflected across all class instances. Static variables in Java are memory-efficient as they are not duplicated for each instance.

What is a Static Variable in Java?

Let’s start this article with a real-life example. Consider a machine that produces different varieties of pens like blue, black, green, etc. for a company ‘X’ .

All pens are different in their properties. Some are blue with different body structures, and some are black. But one attribute is common among all the pens: their company name, i.e., ‘X’ .

Let's implement a class Pen incorporating the abovementioned details.

The companyName variable is of the static type, which implies that it is shared among all instances of the Pen class.

What is the purpose of declaring the companyName variable as static ? It is because since the value of companyName variable is same for all the Pen objects, maintaining it separately for each instance is not memory efficient. Hence, the static variable is associated with the class rather than objects.

  • The static variables are those that are common to all the class instances.
  • Only a single copy of the static variable is created and shared among all the class instances.
  • Because it is a class-level variable, memory allocation of such variables only happens once when the class is loaded in the memory.
  • If an object modifies the value of a static variable, the change is reflected across all objects.

What is the Use of static Keyword in Java

The main use of the static keyword in Java is memory management. Whenever we place a static keyword before initialising a particular class’s methods or variables, these static methods and variables belong to the class instead of their instances or objects.

Syntax of Static Variable in Java

static variable in java data types

Explanation:

  • In the example above, we have created a class Country with a static variable countryCounter .
  • We have created two objects: ob1 and ob2 of Country class and incremented the value of countryCounter using them.
  • Finally, we have accessed the value of the countryCounter variable in three different ways, and the value is the same as it can be seen in the output.
  • This shows the variable is shared across all instances and can be accessed using the class identifier.

Working on the above program diagrammatically.

During compilation of the Country.java file, the Java compiler binds the static variables to the class; in this case, the countryCounter variable is bound to the compiled class.

In the diagram below, we can see that the static variable countryCounter is linked to the class and shared among all class instances.

In this case, two instances of the country class are accessing the same static variable shown below in the diagram. Since the countryCounter variable is a static variable and static variable is a class variable so any changes in these variables are reflected among all the instances of the class, so after the first increment the value of countryCounter is 1 and after another increment, the final value is 2 .

example of static variable in java

Storage Area of Static Variable in Java

The static variables and methods are stored in the heap memory. In fact, all static methods are stored in the Heap memory.

Before the Java 8 version, static variables of the class were stored in a separate section of the non-heap memory named Method Area created by the Java Virtual Machine after the class compilation. Method area section was used to store static variables of the class, metadata of the class, etc. Whereas, non-static methods and variables were stored in the heap memory.

storage area of static variable in java

How to Declare a Static Variable in Java

static variable in java are declared through the use of static keyword. The static keyword indicates to the JVM (Java Virtual Machine) that this variable should be loaded with the class during the compilation of the program.

If we don’t initialize the static variable, the default value of the static variable data type will be automatically assigned to it in Java. For example, the default value of integers is zero , objects is null , and so on.

Declaration Examples

  • If we don’t assign an initial value to any static variable, the default value is automatically initialized for that particular variable.
  • In the above example, there are static variables, one of which is a boolean type, and the second is an integer type.
  • We didn’t initialize these variables, so whenever we try to access them, we will get their default values: false for boolean type variables and 0 for integers. These are the default values for these data types.

Declaration Scope of the Static Variable in Java

We cannot declare static variables in the main() method or any kind of method of the class. The static variables must be declared as a class member in the class.

Because during compilation time, JVM binds static variables to the class level, which means they have to be declared as class members.

  • In Java, static variables can be declared like class members, like static int number , which is a valid declaration of the static variable. However, static variables cannot be declared inside any method scope.
  • The compiler will show a syntax error if we try to declare static variables inside any method.
  • In the above example, if we try to declare a static variable in the main() method, the compiler will show an' illegal modifier' syntax error.

Initialization of Static Final Variables in Java

The static variables are also used as constants with the final keyword in Java . Constants must be initialized and any kind of update is not allowed on them. Let’s understand this with an example.

  • Variables declared with static and final keywords must be initialized with a value.
  • Final variables cannot be modified as shown below.
  • In the above example, if we don’t initialize the static variables compiler will show an error during compilation time.
  • In the above program final static variable b is not initialized and hence it will throw an compile-time error.
  • The final keyword restricts any changes in the variable, so any kind of increment, decrement, or any other change will violate this restriction, and that’s why the compiler will show an error in the above case. The “a++” line is not a valid statement.

Accessibility of the Static Variable in Java

Static variables can be accessed by calling the class name of the class. There is no need to create an instance of the class for accessing the static variables because static variables are the class variables and are shared among all the class instances.

  • The static variables can be accessed in all types of methods: static or non-static.
  • We cannot access non-static variables in static methods because non-static variables can only be accessed by creating an instance of the class.
  • However, static methods can be called without creating an instance of the class.
  • This leads to reference error for the non-static variable because non-static variables can be accessed only through an instance of the class that’s why static methods cannot access non-static variables.
  • Another way of understanding this: If we have not created any instance of a class and call the static method which contains a non-static reference, which object should the non-static member point to?
  • In the above example, a non-static variable named number is called in two methods: one is a static method check() and the other is a non-static method i.e check1() .
  • We can only access the non-static variable only after creating an instance of the class.
  • But static methods can be called without creating an instance of the class,
  • That’s why during accessing the non-static variable in the static method compiler will show reference error .

Syntax for Accessing

  • Classname : Name of the class containing the static variable.
  • (.) dot operato r: Operator used to access static variables.

syntax for accessing

  • In the above example, the static variable named ans is accessed in two ways. One way is without creating an instance of the class using the class reference only and the second way is using the instance of the class.
  • While accessing the static variable in java using the instance of the class, the compiler will show a warning: The static field Main.ans should be accessed in a static way .
  • This is because there is no need to create an instance of accessing the static members of the class.

1. Common for all instances

The static variables are common for all the instances. A single copy of the static variables is shared among all the instances of the class. If any object of the class modifies the value of a static field, the modification is reflected across all instances.

  • In the above example, a single copy of the static variable in java, i.e, number is shared among all the two instances of the class.
  • First instance named as ob1 increments the value of number variable by 1 and the second instance named as ob2 again increments the value of a static variable number by 1 finally making it 2 ,

Class containing static members and non-static members

  • In the above program, static variable insert() is called by every new instance of the class and it inserts the name for every new instance and increments the count_clicks variable.
  • Since a static variable is shared among all the instances, any changes done due to any instance automatically update its original state.
  • In the above program, we increment static members three times. Hence the output is 3 . This value is same across all instances, which means changes done by any one instance is reflected across all instances. Use this Compiler to compile your Java code.

Memory Management of the above program

memory management in static variable in java

  • Whenever we create an instance of the class, a separate copy of all the class methods and variables except static members is created for all respective instances of the class in the heap memory.
  • In the above example the method name as insert() is called by the three instances of the class and each time insert() method is called the value of count_clicks is increment by one.
  • Since count_clicks is a static variable, it is shared among all the instances of the class, so any changes to this variable are reflected among all the instances of the class.

A Real-Life Example of Static Variable in Java

  • The simplest real-life example of a static variable is supposed to have a class named Student that represents the details of any student who took admission to the school.
  • Now we have to count how many students were admitted to the school.
  • In this case, the concept of static variables in Java can be used. We simply create a static variable named count_student inside the Student class.
  • Increment the value of count_student inside the constructor for Student class. As a result, whenever we create a new instance of Student class, count_student will automatically increase by 1.
  • In this way, we can count the number of new students admitted to the school.
  • Static variables in Java are shared across all instances of a class. Static variables are associated with the class rather than with the objects.
  • Static variables are loaded at the time of class compilation.
  • Static variables can be used in any type of method: static or non-static .
  • Non-static variables cannot be used inside static methods. It will throw a compile-time error.
  • Static variables are memory efficient and are created only once per class. Unlike instance variables, static variables are not created separately for each instance.
  • Static variables can be accessed using either the class name or instance name. However, it is recommended that you access static variables using the class name.

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Static variables in Java

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.

There would only be one copy of each class variable per class, regardless of how many objects are created from it.

Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.

Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.

Static variables are created when the program starts and destroyed when the program stops.

Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.

Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.

Static variables can be accessed by calling with the class name ClassName.VariableName .

When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Online Demo

This will produce the following result −

Note  − If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT

Paul Richard

Related Articles

  • Final static variables in Java
  • Static and non static blank final variables in Java
  • Class and Static Variables in Java
  • Can we serialize static variables in Java?
  • Are static local variables allowed in Java?\n
  • Demonstrate static variables, methods and blocks in Java
  • Static Variables in C
  • Assigning values to static final variables in java\n
  • Can static variables be called using className.variableName in Java?
  • Do static variables get initialized in a default constructor in java?
  • Declare static variables and methods in an abstract class in Java
  • Can we initialize static variables in a default constructor in Java?
  • Can we create non static variables in an interface using java?
  • Interface variables are static and final by default in Java, Why?
  • Class or Static Variables in Python?

Kickstart Your Career

Get certified by completing the course

To Continue Learning Please Login

Live Training, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Java Interview Questions and Answers
  • Java Developer Salary Guide in India – For Freshers & Experienced

02 Beginner

  • What are Copy Constructors In Java? Explore Types,Examples & Use
  • Single Inheritance in Java
  • Ternary Operator in Java - (With Example)
  • Top 50 Java Full Stack Developer Interview Questions and Answers
  • Hierarchical Inheritance in Java
  • Arithmetic operators in Java
  • Unary operator in Java
  • Relational operators in Java
  • Assignment operator in Java
  • Logical operators in Java
  • Primitive Data Types in Java
  • Parameterized Constructor in Java
  • What is a Bitwise Operator in Java? Type, Example and More
  • Constructor Overloading in Java
  • Best Java Developer Roadmap 2024
  • Constructor Chaining in Java
  • Multiple Inheritance in Java
  • do...while Loop in Java
  • for Loop in Java: Its Types and Examples
  • Java Full Stack Developer Salary
  • while Loop in Java
  • Hybrid Inheritance in Java
  • Top 10 Reasons to know why Java is Important?
  • What is Java? A Beginners Guide to Java
  • Differences between JDK, JRE, and JVM: Java Toolkit

Variables in Java: Local, Instance and Static Variables

  • Data Types in Java - Primitive and Non-Primitive Data Types
  • Conditional Statements in Java: If, If-Else and Switch Statement
  • What are Operators in Java - Types of Operators in Java ( With Examples )
  • Java VS Python
  • Looping Statements in Java - For, While, Do-While Loop in Java
  • Jump Statements in JAVA - Types of Statements in JAVA (With Examples)
  • Java Arrays: Single Dimensional and Multi-Dimensional Arrays
  • What is String in Java - Java String Types and Methods (With Examples)

03 Intermediate

  • OOPs Concepts in Java: Encapsulation, Abstraction, Inheritance, Polymorphism
  • What is Class in Java? - Objects and Classes in Java {Explained}
  • Access Modifiers in Java: Default, Private, Public, Protected
  • Constructors in Java: Types of Constructors with Examples
  • Polymorphism in Java: Compile time and Runtime Polymorphism
  • Abstract Class in Java: Concepts, Examples, and Usage
  • What is Inheritance in Java: Types of Inheritance in Java
  • Exception handling in Java: Try, Catch, Finally, Throw and Throws

04 Questions

  • Java Multithreading Interview Questions and Answers 2024
  • Top 50 Java MCQ Questions
  • Top 50 Java 8 Interview Questions and Answers

05 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • MERN: Full-Stack Web Developer Certification Training
  • Data Structures and Algorithms Training
  • Variables In Java: Local,..

Variables in Java: Local, Instance and Static Variables

Java Programming For Beginners Free Course

Variables in java: an overview.

static variable assignment in java

Read More - Top 50 Java Interview Questions For Freshers

What is a Variable in Java?

Variable declaration.

Various types of declaration happen by using Java variables such as

  • Strings- which stores text, Such as "Hello world".
  • Int- it stores any integer, specifically any whole number without decimal.
  • Float- stores "floating point" numbers that include decimal values.
  • Char- it stores characters such as 'x', and 'y'. It is denoted by single quotes.
  • Boolean- store values if true or false state.
  • datatype:  It denotes the types of Data that are going to be stored.
  • data_name: A particular name of that variable

Rules for Declaring Variables in Java

  • You can begin the variable's name with an alphabet, a dollar or underscore symbol, or a currency symbol, but not any other special symbol.
  • A variable's name cannot contain more than 64 characters.
  • You cannot use blank spaces while declaring a variable.
  • Java-reserved keywords cannot be used as variable names.
  • The variable name must appear to the left of the assignment operators.

Let's look at the variable declaration in our Java Playground .

Variable Initialization

  • datatype: it defines what type of data is going to be stored in a variable
  • variable_name: Particular name of the variable
  • value: initially stored value in the variable

static variable assignment in java

Read More - Java Web Developer Salary

Types of Variables in Java

Types of Variables in Java

2. Instance Variables in Java

  • An instance variable is created when an object class is generated and it gets destroyed when the same object class is destroyed
  • Programmers can use access specifiers for instance variables
  • It is not mandatory to initialize instance variables

In this Java example, the class "DNT" contains a declaration for an instance variable named "student" that is initialized in the default constructor to demonstrate the use of instance variables. An object of the class is then constructed to allow access to and printing of the student's name.

3. Static Variables in Java

  • Static variables are declared as instance variables.
  • It is created to start the execution of the program and then destroy it automatically after the execution ends.
  • It uses static keywords for the declaration of the static variable within a class

This Java example prints the value "Urmi Bose" from a static variable named "student" that is declared inside the class "DNT," enabling access by class name simply without creating an object.

Difference between Instance and Static Variable in Java

  • In Java, instance variables are stored in separate copies within each object, but static variables are shared across all objects within a class to facilitate memory management. 
  • While changes to static variables impact all objects since the class shares them, changes to instance variables are limited to the object to which they belong. 
  • Static variables can only be accessed directly with the class name; instance variables can only be accessed through object references. 
  • Static variables are produced at the program start and destroyed at the program conclusion, whereas instance variables are created and destroyed along with objects.

Q1. What are the variables in Java?

Q2. what are the 3 types of variables in java, q3. what is a variable declaration in java, q4. what is variable initialization in java, about author.

Author image

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

  • Guidelines to Write Experiences
  • Write Interview Experience
  • Write Work Experience
  • Write Admission Experience
  • Write Campus Experience
  • Write Engineering Experience
  • Write Coaching Experience
  • Write Professional Degree Experience
  • Write Govt. Exam Experiences
  • IBM Interview Experience 2021 for Software Developer
  • IBM Interview Experience As A Java Developer
  • Infosys Interview Experience for Java Developer
  • Sapient Interview Experience for Java Developer 2020
  • IBM Interview Experience for Software Developer
  • IBM Interview Experience for Java Full-Stack Developer
  • Qloron Interview Experience for Java Developer
  • Health Edge Interview Experience for Java Developer
  • IBM Interview Experience for ASE 2023
  • Power2SME Interview Experience for Java Developer
  • HSBC Interview Experience for SDE-2(Java Dev) exp. 4 yrs
  • JP Morgan Chase Interview Experience for Java Developer
  • Tech Mahindra Interview Experience for Java Developer
  • Societe Generale Interview Experience for Java Developer
  • IBM Interview Experience for ASE (On-Campus) 2023
  • Capgemini Interview Experience for Full Stack Java Developer
  • DXC Technology Interview Experience for Java Developer
  • AMDOCS Interview Experience for Software Developer
  • IBM Interview Experience For ASE (Off-Campus) 2023

IBM Interview Experience for Java Developer 2024

I had an interview with IBM for the Java Developer role. Here are the questions they asked:

Round 1: Coding Test

Two Data Structures and Algorithms questions with 1 SQL based Question:

  • The stock span problem
  • Flatten a linked list with next and child pointers

SQL-based Question: Refer to this will be enough SQL Interview Questions

Round 2: Data Structure and Algorithm Round

Again One Data Structure and Algorithm questions with java based questions:

  • Find the common elements of three sorted arrays

Java-Based Questions: Refer to this will be enough Java Questions

Round 3: Data Structure and Algorithm Round 2

Again One Data Structure and Algorithm questions with project-based questions:

  • Maximum sum increasing subsequence

— interviewer not happy with my solution and ask for optimal solution at that time I am not able to optimal my solution.

Springboot Based Questions:

  • Why Spring Boot over Spring?
  • Can we override or replace the Embedded tomcat server in Spring Boot?
  • What is the difference between @RestController and @Controller in Spring Boot?
  • What is an IOC container?

Overall, the last round not went very well as interviewer expecting optimal solution.

Got Rejection!

Please Login to comment...

Similar reads.

  • Java Developer
  • Write It Up 2024
  • Experiences
  • Interview Experiences

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Static Variable in Java

    static variable assignment in java

  2. static variable in java and How static variable does work

    static variable assignment in java

  3. Static variables in Java

    static variable assignment in java

  4. Static Method in Java with Example

    static variable assignment in java

  5. A Guide to the Static Keyword in Java

    static variable assignment in java

  6. Java Static Variable

    static variable assignment in java

VIDEO

  1. 45. Introduction to Static And Non-static Variables & Methods in Java

  2. Static Variable and Dynamic Variable

  3. Java Variables #Shorts

  4. 20. static vs non static variables

  5. Mastering Java Variables: A Complete Guide

  6. Static variable is used for memory efficiency #java #coding #oopsconcept #programming #job #career

COMMENTS

  1. Static Variables in Java

    The static keyword is one of the most essential features in the Java programming language. We use it to define class-level variables and methods. Here is an example of how to use the static keyword: public class StaticKeywordExample { private static int count = 0; // static variable public static void printCount() { // static method System.out ...

  2. A Guide to the Static Keyword in Java

    2. The Anatomy of the static Keyword. In the Java programming language, the keyword static means that the particular member belongs to a type itself, rather than to an instance of that type. This means we'll create only one instance of that static member that's shared across all instances of the class. We can apply the keyword to variables ...

  3. When Are Static Variables Initialized in Java?

    At a high level, the JVM performs the following steps: First, the class is loaded and linked. Then, the "initialize" phase of this process processes the static variable initialization. Finally, the main method associated with the class is called. In the next section, we'll look at class variable initialization. 3.

  4. Static Variables in Java with Examples

    Static Variables in Java with Examples. When a variable is declared as. , then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable. Important points for static variables:

  5. setting a static variable in java

    2. As stated by the other answers, you should set your initial value like so: private static String foo = "initial value"; Additionally, if you want to access this variable from anywhere, you need to reference it in a static context, like so: Foo.foo. where Foo is the class name, and foo is the variable name.

  6. static Keyword in Java

    static Keyword in Java. The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class.

  7. Static Variable in Java: What is Static Block & Method [Example]

    The static block is a block of statement inside a Java class that will be executed when a class is first loaded into the JVM. A static block helps to initialize the static data members, just like constructors help to initialize instance members. class Test{. static {. //Code goes here.

  8. Java Static Keyword (With Examples)

    In the above program, we have declared a non-static variable named min and a static variable named max inside the class Test. Inside the Main class, we can see that we are calling the non-static variable using the object of the class (obj.min + 1). However, we are calling the static variable by using the class name (Test.max + 1).

  9. Static Variable in Java with Examples

    How to Declare a Static Variable in Java. static variable in java are declared through the use of static keyword. The static keyword indicates to the JVM (Java Virtual Machine) that this variable should be loaded with the class during the compilation of the program.. If we don't initialize the static variable, the default value of the static variable data type will be automatically assigned ...

  10. Static variables in Java

    Static variables in Java. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are rarely used other than being declared as ...

  11. Java

    Like variables we can have static block, static method and static class, to read about them refer: static keyword in java. Static variable Syntax. static keyword followed by data type, followed by variable name. static data_type variable_name;

  12. Static Final Variables in Java

    2.2. static final Objects. We can also create static final object references: public static final HashMap<String, Integer> PART = new HashMap <>(); Since the PART reference is constant, it can't be reassigned: PART = new HashMap <>(); The code above throws an exception because we assign a new reference to an immutable variable.

  13. Java

    Java Static Variables. A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words you can say that only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded ...

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

  15. Java Variables

    5. Difference between Instance and Class Variables. Instance variables ( non-static fields) are unique to each instance of a class. Class variables ( static fields) are fields declared with the static modifier; there is exactly one copy of a class variable, regardless of how many times the class has been instantiated.

  16. Variables in Java: Local, Instance and Static Variables

    The variable name must appear to the left of the assignment operators. Let's look at the variable declaration in our Java Playground. Example. class Example { public static void main ( String[] args ) ... Difference between Instance and Static Variable in Java. In Java, instance variables are stored in separate copies within each object, but ...

  17. java

    A workaround is to create a non static setter to assign your value into the static variable: @Service public class UserService { private static String SVN_URL; @Value("${SVN_URL}") public void setSvnUrl(String svnUrl) { SVN_URL = svnUrl; } } ... This approach was tested with Spring Boot 3 and Java 17. It is of course possible to provide the ...

  18. Java Variables

    Variables in Java. Java variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Variables in Java are only a name given to a memory location. All the operations done on the variable affect that memory location.

  19. java

    You did this by the following assignment: -. Test.o4All = this.o4This; In the above assignment, you are not creating a copy of the instance referred to by o4This, rather, you are just copying the value of o4This in the o4All reference. Now, since o4This value is a reference to some instance. So, o4All now have reference to the same instance as ...

  20. java

    A final variable is not assigned default value by the JVM, you need to initialise it with some value. A static final class variable should be either initialised at declaration or inside a static block. private static final int HEIGHT; static {. HEIGHT = 10; You cannot assign a new value to a final variable.

  21. java

    5. If you want to use the value of a method you have to call it. val = getSugar(num); Using static fields to pass arguments or return values is bad practice. This is likely to cause confusion and be a cause of subtle multi-threaded bugs. Its also more complex than just returning the value like you do with getMocha()

  22. IBM Interview Experience for Java Developer 2024

    I had an interview with IBM for the Java Developer role. Here are the questions they asked: Round 1: Coding Test. Two Data Structures and Algorithms questions with 1 SQL based Question: SQL-based Question: Refer to this will be enough SQL Interview Questions. Round 2: Data Structure and Algorithm Round. Again One Data Structure and Algorithm ...