Java Variables: Understanding Variables, Printing, Multiple Variables & Identifiers
Variables are a foundational concept in programming and are used to store data that can be referenced and manipulated in a program. In Java, variables are used to store various types of data like numbers, characters, strings, and more.
This module will help you understand what variables are, how to print them, how to declare multiple variables, and what identifiers are. It is structured to help beginners grasp the key concepts and best practices.
1. What is a Variable?
A variable in Java is a container that holds data during the execution of a program. Each variable in Java has:
- A name (identifier)
- A type (data type)
- A value
Syntax:
type variableName = value;
Example:
int age = 25;
String name = "Alex";
In the above examples:
- int is the data type, age is the variable name, and 25 is the value.
- String is the data type, name is the variable name, and "Alex" is the value.
2. Types of Variables in Java
Java supports three main types of variables:
- Local Variables
- Declared inside a method, constructor, or block.
- Scope is limited to the block in which they are defined.
- Instance Variables
- Declared inside a class but outside methods.
- Each object has its own copy of instance variables.
- Static Variables (Class Variables)
- Declared with the static keyword.
- Belong to the class rather than instances.
Example:
public class Student {
static String schoolName = "ABC School"; // Static variable
String studentName; // Instance variable
public void display() {
int rollNumber = 10; // Local variable
System.out.println(rollNumber);
}
}
3. Declaring and Initializing Variables
Java is a statically-typed language, so every variable must have a declared type.
Syntax:
type variableName; // Declaration
variableName = value; // Initialization
You can also do both in one line:
type variableName = value;
Examples:
int age = 30;
float price = 99.99f;
boolean isJavaFun = true;
char grade = 'A';
4. Printing Variables
You can use the System.out.println() method to print variable values to the console.
Example:
public class PrintExample {
public static void main(String[] args) {
int age = 20;
String name = "Rahul";
System.out.println(age); // Prints 20
System.out.println(name); // Prints Rahul
System.out.println("Name: " + name); // Prints Name: Rahul
System.out.println("Age: " + age); // Prints Age: 20
}
}
5. Declaring Multiple Variables
You can declare multiple variables of the same type in one line.
Syntax:
type var1 = value1, var2 = value2, var3 = value3;
Example:
int x = 5, y = 10, z = 15;
System.out.println(x + y + z); // Output: 30
Or declare without initializing:
int a, b, c;
a = 1;
b = 2;
c = 3;
6. Variable Naming Rules (Identifiers)
Identifiers are the names used for variables, methods, classes, etc. In Java, naming conventions and rules must be followed.
Rules for Identifiers:
- Can contain letters, digits, underscore _, and dollar sign $
- Must begin with a letter (A-Z or a-z), _, or $
- Cannot start with a digit
- Cannot be a Java reserved keyword (e.g., class, public, int, etc.)
- Java is case-sensitive, so total and Total are different
Examples of valid identifiers:
int total;
float average_score;
String $name;
Examples of invalid identifiers:
int 1number; // Starts with a digit
float class; // 'class' is a reserved keyword
String my-name; // '-' is not allowed
7. Best Practices for Variable Naming
- Use meaningful names (e.g., studentAge instead of a)
- Use camelCase for variable names (e.g., totalMarks, employeeName)
- Avoid single-letter names except in small loops (like i, j)
- Do not use $ or _ unless necessary (though technically valid)
Example of bad naming:
int a = 10;
String s = "John";
Better naming:
int studentAge = 10;
String studentName = "John";
8. Final Variables (Constants)
Use the final keyword to declare a constant (a variable whose value cannot be changed).
Example:
final int MAX_AGE = 100;
- Constants are usually named in uppercase letters with underscores.
Trying to change MAX_AGE later will result in a compile-time error.
9. Data Types Recap for Variables
Here are some common data types used with variables:
Data Type | Description | Example |
---|---|---|
int | Integer value | int age = 20; |
double | Decimal number (64-bit) | double price = 19.99; |
float | Decimal number (32-bit) | float tax = 5.5f; |
char | Single character | char grade = 'A'; |
boolean | True/False value | boolean isPassed = true; |
String | Sequence of characters | String name = "Amit"; |
10. Code Example: Declaring, Printing & Using Variables
public class VariableDemo {
public static void main(String[] args) {
// Declaring variables
int age = 25;
double salary = 45000.50;
String name = "Sneha";
boolean isEmployed = true;
// Printing values
System.out.println("Employee Details:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Employed: " + isEmployed);
// Multiple variable declaration
int x = 10, y = 20, z = 30;
System.out.println("Sum: " + (x + y + z));
// Final variable
final int MAX_LOGIN_ATTEMPTS = 5;
System.out.println("Max Login Attempts: " + MAX_LOGIN_ATTEMPTS);
}
}
Conclusion
Variables are the basic units of storage in a Java program. They allow programmers to store, retrieve, and manipulate data efficiently. By understanding how to declare, initialize, print, and name variables correctly, students lay a strong foundation for more advanced concepts like conditional statements, loops, and object-oriented programming.
Always follow naming conventions and write readable code. Practice declaring different types of variables, printing them, and working with them in various ways to strengthen your understanding.
Next Blog- Java Data Types: Primitive and Non-Primitive Types