← Back to Chapters

Java Variables & Constants

? Java Variables & Constants

? Quick Overview

Variables and constants are fundamental building blocks in Java. Variables store changeable data, while constants store fixed values that cannot be modified once assigned.

? Key Concepts

  • Variables must be declared with a data type
  • Java is a statically typed language
  • Constants use the final keyword
  • Variables have scope and lifetime

? Syntax & Theory

  • Variable → data that can change
  • Constant → fixed value using final
  • Java naming conventions use camelCase

? Code Examples

? View Code Example
// Declaring and using variables in Java
int age = 20;
double salary = 45000.50;
char grade = 'A';
boolean isStudent = true;

System.out.println(age);
System.out.println(salary);
System.out.println(grade);
System.out.println(isStudent);
? View Code Example
// Declaring constants using final keyword
final double PI = 3.14159;
final int MAX_USERS = 100;

System.out.println(PI);
System.out.println(MAX_USERS);

? Output / Explanation

Variables like age and salary can be changed during program execution. Constants such as PI remain fixed and cannot be reassigned once initialized.

? Tips & Best Practices

  • Always initialize variables before use
  • Use meaningful variable names
  • Write constants in uppercase with underscores
  • Prefer constants for fixed configuration values

? Try It Yourself

  • Create variables for student details
  • Define a constant for GST percentage
  • Try changing variable values and observe output
  • Attempt to modify a constant and see the compiler error