Variable Declaration
Variable Declaration
A variable is a named container that stores a value. In Java, you must declare the type before using a variable.
Syntax
// declaration: type name;
int age;
double salary;
String name;
boolean isActive;
// declaration with initialization
int age = 25;
double salary = 150000.00;
String name = "Amazon";
boolean isActive = true;
Multiple Declarations
// Declare multiple variables of same type
int x, y, z;
int a = 1, b = 2, c = 3;
// Cannot mix types in one declaration
int x, double y; // ERROR!
int x; double y; // OK
Type Inference with var (Java 10+)
// Java 10+ allows var for local variables
var name = "Amazon"; // inferred as String
var age = 25; // inferred as int
var pi = 3.14159; // inferred as double
var list = new ArrayList<>(); // inferred as ArrayList<Object>
// Cannot use var for:
// - Class fields
// - Method parameters
// - Method return types
// - Uninitialized variables
var x; // ERROR: cannot infer type
Effective Final Variables
// Variables that are never reassigned are effectively final
final int MAX = 100; // explicitly final
int threshold = 50; // effectively final (never reassigned)
// Can be used in lambda expressions
Runnable r = () -> System.out.println(threshold);
// Not effectively final
int counter = 0;
counter++; // reassigned
// Runnable r = () -> System.out.println(counter); // ERROR!
Variable Initialization
Initialization Rules
Java requires variables to be initialized before use. Uninitialized variables cause compilation errors.
// ERROR: variable might not have been initialized
public class InitError {
public static void main(String[] args) {
int x;
System.out.println(x); // Compilation error!
}
}
// CORRECT: initialize before use
public class InitCorrect {
public static void main(String[] args) {
int x = 0;
System.out.println(x); // Output: 0
}
}
Default Values
// Instance and class variables get default values
public class Defaults {
// Primitive defaults
byte byteDefault; // 0
short shortDefault; // 0
int intDefault; // 0
long longDefault; // 0L
float floatDefault; // 0.0f
double doubleDefault; // 0.0d
char charDefault; // '\u0000' (null character)
boolean boolDefault; // false
// Reference defaults
String stringDefault; // null
int[] arrayDefault; // null
Object objectDefault; // null
public void printDefaults() {
System.out.println("byte: " + byteDefault);
System.out.println("int: " + intDefault);
System.out.println("double: " + doubleDefault);
System.out.println("boolean: " + boolDefault);
System.out.println("String: " + stringDefault);
}
}
// NOTE: Local variables have NO default values!
public class LocalDefaults {
public void method() {
int localInt; // Not initialized
// System.out.println(localInt); // ERROR!
}
}
Initialization Patterns
// Direct initialization
int count = 0;
String name = "Java";
// Initialization blocks
public class InitBlock {
int value;
// Instance initializer
{
value = 42;
}
// Static initializer
static {
System.out.println("Class loaded");
}
}
// Constructor initialization
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name; // parameter shadows field
this.age = age;
}
}
Scope of Variables
public class ScopeDemo {
int instanceVar = 10; // accessible throughout class
static int classVar = 20; // accessible through class
public void method() {
int localVar = 30; // accessible within method
for (int i = 0; i < 5; i++) { // i accessible within loop
int loopVar = i * 2; // accessible within loop
System.out.println(loopVar);
}
// System.out.println(i); // ERROR: i not in scope
if (true) {
int ifVar = 100; // accessible within if block
System.out.println(ifVar);
}
// System.out.println(ifVar); // ERROR: ifVar not in scope
}
}
Types of Variables
Three Types of Variables
public class VariableTypes {
// 1. Class Variables (Static Fields)
// Shared across all instances, belong to the class
static int totalCount = 0;
static final String COMPANY = "Amazon";
// 2. Instance Variables (Non-static Fields)
// Unique to each object instance
String name;
int age;
double salary;
// 3. Local Variables
// Declared inside methods, constructors, or blocks
public void calculateTax() {
double taxRate = 0.3;
double tax = salary * taxRate;
System.out.println("Tax: " + tax);
}
public static void main(String[] args) {
// Local variable
VariableTypes obj1 = new VariableTypes();
obj1.name = "Alice";
obj1.age = 30;
VariableTypes obj2 = new VariableTypes();
obj2.name = "Bob";
obj2.age = 25;
// Class variable is shared
VariableTypes.totalCount = 2;
System.out.println(VariableTypes.totalCount); // 2 for both
}
}
Comparison Table
| Feature | Class Variable | Instance Variable | Local Variable |
|---|---|---|---|
| Keyword | static | none | none |
| Scope | Class | Object instance | Method/block |
| Lifetime | Application | Object lifetime | Method call |
| Default Value | Yes | Yes | No |
| Access | Through class or instance | Through instance only | Within scope only |
Parameter Variables
public class ParameterDemo {
// Parameters are a special type of local variable
public int add(int a, int b) {
return a + b;
}
public String formatName(String first, String last) {
return first + " " + last;
}
// Variable arguments (varargs)
public int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
public static void main(String[] args) {
ParameterDemo demo = new ParameterDemo();
System.out.println(demo.add(5, 3)); // 8
System.out.println(demo.sum(1, 2, 3, 4, 5)); // 15
}
}
Shadowing
public class ShadowDemo {
int x = 10; // instance variable
public void method() {
int x = 20; // local variable shadows instance variable
System.out.println(x); // 20 (local)
System.out.println(this.x); // 10 (instance)
}
public void nestedMethod() {
int x = 30;
if (true) {
int x = 40; // ERROR: already defined in scope
}
}
}
Naming Rules
Java Naming Conventions
Legal Names
// MUST follow these rules:
// 1. Can contain letters, digits, $, and _
// 2. Cannot start with a digit
// 3. Cannot be a reserved keyword
// 4. Case-sensitive
int age; // OK
int $price; // OK (but not recommended)
int _count; // OK (but not recommended)
int userName123; // OK
int 1stPlace; // ERROR: starts with digit
int class; // ERROR: reserved keyword
int my-var; // ERROR: contains hyphen
Naming Conventions (Best Practices)
// Variables and methods: camelCase
int studentAge;
String firstName;
double monthlySalary;
void calculateTax() { }
boolean isEligible() { }
// Classes and Interfaces: PascalCase
public class StudentRecord { }
public interface Payable { }
// Constants: UPPER_SNAKE_CASE
static final int MAX_RETRY = 3;
static final String DATABASE_URL = "jdbc:mysql://localhost";
// Packages: lowercase
package com.amazon.prep;
package java.util;
// Enums: PascalCase for type, UPPER_SNAKE_CASE for values
public enum Color {
RED, GREEN, BLUE
}
// Generic type parameters: single uppercase letter
public class List<T> { }
public interface Map<K, V> { }
Common Naming Mistakes
// BAD: single letter (except loops)
int x = 10; // What is x?
// GOOD: descriptive name
int studentCount = 10;
// BAD: abbreviations
int cnt = 10;
dbl sal = 50000.0;
// GOOD: full words
int count = 10;
double salary = 50000.0;
// BAD: boolean with is/get prefix
boolean isActive = true;
boolean getIsValid() { return true; } // confusing
// GOOD: clear boolean names
boolean active = true;
boolean valid = true;
// BAD: Hungarian notation (Java doesn't use this)
String strName;
int nCount;
// GOOD: Java convention
String name;
int count;
Reserved Keywords
// Cannot be used as identifiers:
abstract, assert, boolean, break, byte, case, catch, char, class,
const, continue, default, do, double, else, enum, extends, final,
finally, float, for, goto, if, implements, import, instanceof, int,
interface, long, native, new, package, private, protected, public,
return, short, static, strictfp, super, switch, synchronized, this,
throw, throws, transient, try, void, volatile, while
// Also reserved: true, false, null (literals)
Practice Problems
What is the output of this code?
Example:
Input: public class Test { static int x = 10; public static void main(String[] args) { int x = 20; System.out.println(x); System.out.println(Test.x); } }
Output: 20 10
Local variable x shadows the static field. Test.x accesses the static field.
Optimal Solution — O(1) time, O(1) space
Understand variable scope and shadowing rules
public class Test {
static int x = 10;
public static void main(String[] args) {
int x = 20; // shadows static x
System.out.println(x); // prints 20 (local)
System.out.println(Test.x); // prints 10 (static)
}
}Edge Cases:
- Shadowing with instance variables
- Nested scopes
Find and fix the bug in this code.
Example:
Input: public class Bug { public static void main(String[] args) { int result; result = result + 5; System.out.println(result); } }
Output: Compilation error: variable might not have been initialized
Variable 'result' is used before initialization. Initialize to 0 first.
Optimal Solution — O(1) time, O(1) space
Initialize variable before use
public class Bug {
public static void main(String[] args) {
int result = 0; // Initialize first
result = result + 5;
System.out.println(result); // Output: 5
}
}Edge Cases:
- Instance variables have defaults
- Local variables do not
Quiz
1. What is the default value of a boolean instance variable?
2. Which of the following is a valid variable name?
3. When was the 'var' keyword introduced for type inference?
4. What is the primary purpose of Variables?
Flashcards
Question
What are the three types of variables in Java?
Click to reveal answer
Answer
1) Class variables (static fields) - shared across instances 2) Instance variables (non-static fields) - unique to each object 3) Local variables - declared inside methods, no default values
Question
Do local variables have default values?
Click to reveal answer
Answer
No. Local variables must be explicitly initialized before use. Uninitialized local variables cause compilation errors.
Question
What is variable shadowing?
Click to reveal answer
Answer
When a local variable has the same name as a field/variable in an outer scope. Use 'this.field' to access the shadowed field.
Question
What is Variables?
Click to reveal answer
Answer
Variables is a key concept in Java programming.
Question
When to use Variables?
Click to reveal answer
Answer
Use Variables when building production systems that require reliability, scalability, and maintainability.
Revision Notes
Key Takeaways
- 1.Local variables must be initialized before use
- 2.Instance variables get default values, local variables do not
- 3.Use var for type inference in local variables (Java 10+)
- 4.Variable shadowing requires this keyword to access fields
- 5.Follow Java naming conventions for readable code
Interview Tips
- •Know the difference between local and instance variable defaults
- •Understand variable scope for debugging
- •Use descriptive variable names in interview code
- •Explain type inference with var keyword
Cheat Sheet
Variables Cheat Sheet
Declaration:
int age = 25;
var name = "Java"; // Java 10+ type inference
Three Types:
- Class (static): Shared, belong to class
- Instance: Unique to each object
- Local: Method-scoped, no defaults
Default Values (instance/class only):
- Numeric: 0/0.0
- boolean: false
- char: '\u0000'
- Reference: null
Naming Rules:
- Letters, digits, $, _
- Cannot start with digit
- Cannot be keyword
- camelCase for variables/methods
- PascalCase for classes