CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Variable in Java

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor

Variable in Java

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 3 min read · 0 Comments
Share: in X

A variable is a named location in memory that holds a value. They are used to store data that can be utilized throughout a program.

Table of Contents

  • Declaring and Initializing Variable in Java
    • Syntax for Variable Declaration
    • Syntax for Variable Initialization
  • Types of variable in Java
    • 1. Local Variables
    • 2. Instance Variables
    • 3. Static Variables
  • Rules for Naming Variables
  • Best Practices for Using Variables
  • Conclusion
  • Frequently Asked Questions
    • How do I declare a variable in Java?
    • What is the scope of a variable in Java?
    • How do I assign a value to a variable in Java?

Declaring and Initializing Variable in Java

To use a variable, you must first declare it and optionally initialize it with a value.

Syntax for Variable Declaration

data_type variable_name;

Syntax for Variable Initialization

data_type variable_name = value;

Examples:

int age; // Declaration
age = 25; // Initialization

double salary = 50000.50; // Declaration and initialization
String name = "Radha Krishnan"; // Declaration and initialization

Types of variable in Java

There are three types of variables:

1. Local Variables

  • Declared inside a method, constructor, or block.
  • Must be initialized before use.
  • Scope is limited to the block in which they are declared.

Example:

public class LocalVariableExample {
   public static void main(String[] args) {
      int age; // local variable
      age = 25;
      System.out.println("My age is: " + age);
   }
}

Output;

My age is: 25

2. Instance Variables

  • Declared inside a class but outside any method.
  • Initialized when an object of the class is created.
  • Scope is the entire class.

Example:

public class InstanceVariableExample {
   // instance variable
   String name;

   public static void main(String[] args) {
      InstanceVariableExample obj = new InstanceVariableExample();
      System.out.println("My name is: " + obj.name);
   }
}

Output:

My name is: null

3. Static Variables

  • Declared with the static keyword inside a class but outside any method.
  • Shared among all instances of the class.
  • Initialized only once at the start of program execution.

Example:

public class StaticVariableExample {
   // static variable
   static int count = 0;

   public static void main(String[] args) {
      StaticVariableExample obj1 = new StaticVariableExample();
      obj1.count++;
      StaticVariableExample obj2 = new StaticVariableExample();
      obj2.count++;
      StaticVariableExample obj3 = new StaticVariableExample();
      obj3.count++;
      System.out.println("Total objects created: " + count);
   }
}

Output:

Total objects created: 3

Can you answer why the output is 3?

I would love to hear your answer in the comment section below. 🙂

Rules for Naming Variables

  1. Variable names must start with a letter, underscore (_), or dollar sign ($).
  2. Variable names cannot contain spaces or special characters (except _ and $).
  3. Variable names are case-sensitive (age and Age are different).
  4. Variable names cannot be Java keywords (e.g., int, class, public).

Best Practices for Using Variables

  1. Use Descriptive Names: Choose meaningful names that reflect the purpose of the variable (e.g., employeeSalary instead of es).
  2. Follow Naming Conventions: Use camelCase for variable names (e.g., firstName, totalAmount).
  3. Initialize Variables: Always initialize variables before using them to avoid unexpected behavior.
  4. Limit Scope: Declare variables in the smallest scope possible to avoid unintended side effects.
  5. Use Constants for Fixed Values: Use the final keyword for variables whose values should not change.

Conclusion

Variables are a fundamental aspect of Java programming, providing a way to store and manipulate data throughout your program. By understanding the different types of variables, their scope, and best practices for using them, you can write cleaner, more efficient, and maintainable code. Whether you’re working with local, instance, or static variables, mastering their usage is essential for becoming a proficient Java developer.

Frequently Asked Questions

How do I declare a variable in Java?

To declare a variable in Java, specify its data type followed by the variable name, like this:
int myNumber;.

What is the scope of a variable in Java?

The scope of a variable determines where it can be accessed. Variables declared inside a block have local scope, while those declared in a class have class scope.

How do I assign a value to a variable in Java?

You can assign a value to a variable using the assignment operator (=), like this:
myNumber = 42;.

Related Posts:

  • Identifiers in Java
  • Default Variable Initialization in Java
  • Control Statements in Java
  • Compile and Run Java Program
  • Arrays in Java
  • Command Line Arguments in Java
Tags:javalanguage-fundamentals
Was this article helpful?
← Previous ArticleImport Maven project in Eclipse
Next Article →MongoDB useful commands

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap