1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Variables
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
19Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Variables

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
19Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Variables

Overview

Variables are containers for storing data values in the computer's RAM. Without variables, your application would have no way to remember user input, track scores, or maintain state.

Java is a Statically Typed language. This means that unlike JavaScript or Python, you absolutely MUST declare the specific type of data a variable will hold (e.g., integer, text, boolean) before you can use it. The compiler locks this type in permanently. If you create a variable to hold numbers, attempting to store text in it will cause a hard compilation error.

Variables in Java generally consist of three components: the Type (what kind of data it holds), the Name (how you refer to it, using camelCase convention), and the Value (the actual data). You can also add modifiers like final to lock a variable so its value can never be changed after initialization.

Syntax

Notice how age can be updated with a new number, but trying to assign a string to it would instantly crash the compiler. The final keyword is heavily used for constant configuration values.

Variable Declaration and Initialization
java
public class Main {
    public static void main(String[] args) {
        // 1. Declaration and Initialization
        int age = 25;
        String name = "Alice";
        
        // 2. Declaration first, Assignment later
        double salary;
        salary = 75000.50;
        
        // 3. Re-assigning a variable
        age = 26; // Valid, age is an integer
        // age = "Twenty Six"; // ERROR: Incompatible types!
        
        // 4. Constants (Cannot be changed)
        final double PI = 3.14159;
        // PI = 3.14; // ERROR: Cannot assign a value to final variable
    }
}

Common Pitfalls

  • Forgetting to initialize a variable before using it. In Java, local variables inside methods do NOT receive a default value. If you declare int count; and immediately try to System.out.println(count);, the compiler will throw an error.
  • Using the wrong naming convention. Java strictly adheres to camelCase for variables (e.g., userAge, totalScore). Using snake_case or PascalCase for variables is considered highly unprofessional in the Java ecosystem.
  • Attempting to change the type of a variable dynamically. In JS you can do let x = 5; x = 'hello';. In Java, doing this will completely halt compilation.

Interview Questions

What is the difference between a local variable and an instance variable?

Local variables are declared inside a method and are destroyed when the method finishes. They MUST be manually initialized before use. Instance variables are declared at the Class level, are tied to an object instance, and are automatically initialized with default values (e.g., 0 for ints, null for objects).

What does the final keyword do when applied to a variable?

It makes the variable a constant. Once it is assigned a value, it can never be reassigned. For primitives, the literal value is locked. For objects, the memory reference is locked (though the internal state of the object can still be modified).

Real-World Example

When building a banking application, you must use variables to carefully track the user's account balance, account number, and transaction limits. Using final ensures that strict configuration limits (like maximum withdrawal limits) cannot be accidentally overwritten by rogue code.

example
java
public class BankAccount {
    // Instance variables maintain state across the app
    String accountHolder = "John Doe";
    double balance = 1500.00;
    
    // final constant prevents accidental tampering
    final double MAX_WITHDRAWAL = 500.00;
    
    public void withdraw(double amount) {
        if(amount <= MAX_WITHDRAWAL) {
            balance = balance - amount;
        }
    }
}

Check Your Knowledge

Test your understanding of Variables with these quick questions.

Question 1

Which of the following is a valid variable declaration in Java?

Question 2

What happens if you try to reassign a variable marked with the `final` keyword?

Question 3

What is the standard naming convention for variables in Java?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Variables

Overview

Variables are containers for storing data values in the computer's RAM. Without variables, your application would have no way to remember user input, track scores, or maintain state.

Java is a Statically Typed language. This means that unlike JavaScript or Python, you absolutely MUST declare the specific type of data a variable will hold (e.g., integer, text, boolean) before you can use it. The compiler locks this type in permanently. If you create a variable to hold numbers, attempting to store text in it will cause a hard compilation error.

Variables in Java generally consist of three components: the Type (what kind of data it holds), the Name (how you refer to it, using camelCase convention), and the Value (the actual data). You can also add modifiers like final to lock a variable so its value can never be changed after initialization.

Syntax

Notice how age can be updated with a new number, but trying to assign a string to it would instantly crash the compiler. The final keyword is heavily used for constant configuration values.

Variable Declaration and Initialization
java
public class Main {
    public static void main(String[] args) {
        // 1. Declaration and Initialization
        int age = 25;
        String name = "Alice";
        
        // 2. Declaration first, Assignment later
        double salary;
        salary = 75000.50;
        
        // 3. Re-assigning a variable
        age = 26; // Valid, age is an integer
        // age = "Twenty Six"; // ERROR: Incompatible types!
        
        // 4. Constants (Cannot be changed)
        final double PI = 3.14159;
        // PI = 3.14; // ERROR: Cannot assign a value to final variable
    }
}

Common Pitfalls

  • Forgetting to initialize a variable before using it. In Java, local variables inside methods do NOT receive a default value. If you declare int count; and immediately try to System.out.println(count);, the compiler will throw an error.
  • Using the wrong naming convention. Java strictly adheres to camelCase for variables (e.g., userAge, totalScore). Using snake_case or PascalCase for variables is considered highly unprofessional in the Java ecosystem.
  • Attempting to change the type of a variable dynamically. In JS you can do let x = 5; x = 'hello';. In Java, doing this will completely halt compilation.

Interview Questions

What is the difference between a local variable and an instance variable?

Local variables are declared inside a method and are destroyed when the method finishes. They MUST be manually initialized before use. Instance variables are declared at the Class level, are tied to an object instance, and are automatically initialized with default values (e.g., 0 for ints, null for objects).

What does the final keyword do when applied to a variable?

It makes the variable a constant. Once it is assigned a value, it can never be reassigned. For primitives, the literal value is locked. For objects, the memory reference is locked (though the internal state of the object can still be modified).

Real-World Example

When building a banking application, you must use variables to carefully track the user's account balance, account number, and transaction limits. Using final ensures that strict configuration limits (like maximum withdrawal limits) cannot be accidentally overwritten by rogue code.

example
java
public class BankAccount {
    // Instance variables maintain state across the app
    String accountHolder = "John Doe";
    double balance = 1500.00;
    
    // final constant prevents accidental tampering
    final double MAX_WITHDRAWAL = 500.00;
    
    public void withdraw(double amount) {
        if(amount <= MAX_WITHDRAWAL) {
            balance = balance - amount;
        }
    }
}

Check Your Knowledge

Test your understanding of Variables with these quick questions.

Question 1

Which of the following is a valid variable declaration in Java?

Question 2

What happens if you try to reassign a variable marked with the `final` keyword?

Question 3

What is the standard naming convention for variables in Java?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A