Java Variables
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Variables

Jeevadharshan

What Are Variables?

Variables in Java act like storage boxes that hold data values.

Each variable has:
  • a data type (what kind of data it stores) 
  • a name (how we refer to it) 
  • a value (the data it holds)

Common Types of Variables in Java

Java supports many data types. Some of the most frequently used ones are:
  • String – stores text values such as "Welcome" 
  • int – stores whole numbers like 10 or -45 
  • float – stores decimal numbers like 12.75 
  • char – stores a single character such as 'X' 
  • boolean – stores logical values: true or false

Creating (Declaring) Variables

To create a variable in Java, you need to:
  1. Specify the data type 
  2. Provide a variable name 
  3. Assign a value (optional at first) 

General Syntax 

dataType variableName = value;

Example: String Variable

The example below creates a text variable and displays it.

String city = "Chennai"; 
System.out.println(city);

Example: Integer Variable

To store a whole number, use the int type.

int score = 90; 
System.out.println(score);

Declaring First, Assigning Later 

You can create a variable first and give it a value afterward.

int temperature; 
temperature = 32; 
System.out.println(temperature);

Updating Variable Values

A variable’s value can be changed after declaration. The new value replaces the old one.

int level = 1; 
level = 2;   // value updated 
System.out.println(level); 

Final (Constant) Variables  

If a value should never change, use the final keyword. Final variables are also called constants.

final int MAX_LIMIT = 100; 
// MAX_LIMIT = 120;  // This will cause an error

Once assigned, a final variable cannot be modified.

Using Multiple Data Types Together

The example below demonstrates declaring variables of different types in one program.

int items = 3; 
float price = 49.99f; 
char grade = 'A'; 
boolean isAvailable = true; 
String product = "Notebook"; 

System.out.println(items); 
System.out.println(price); 
System.out.println(grade); 
System.out.println(isAvailable); 
System.out.println(product);  

Java Printing Variables 

Displaying Variable Values 

The println() method is commonly used to output variable values to the console.

To display text together with a variable, Java uses the + operator.

Example: Text with a Variable

String user = "Anita"; 
System.out.println("Welcome, " + user); 

This joins the text and the variable value into a single output.

Combining Variables Together 

The + operator can also be used to join the values of two variables.

Example: Joining Two Strings

String city = "New "; 
String country = "Delhi"; 
String location = city + country; 
System.out.println(location);

Meaning of the + Operator in Java 

The + symbol behaves differently depending on the data type:
  • With strings → it joins values together (concatenation) 
  • With numbers → it performs arithmetic addition
Example: Adding Numbers

int a = 8; 
int b = 12; 
System.out.println(a + b);

Output

20

Step-by-Step Explanation

  • a stores the value 8 
  • b stores the value 12 
  • Java adds both values and prints the result 20

Mixing Text and Numbers

When text and numbers are used in the same statement, Java processes the expression from left to right.

Example Without Parentheses 

int marks1 = 4; 
int marks2 = 7; 

System.out.println("Total marks: " + marks1 + marks2);

Output 

Total marks: 47

Java converts numbers into text after encountering a string.

Using Parentheses for Correct Calculation

To force Java to calculate numbers first, use parentheses.

System.out.println("Total marks: " + (marks1 + marks2));

Output 

Total marks: 11

Declaring Several Variables at Once

Java allows you to create multiple variables of the same data type in a single statement by separating them with commas.

Traditional Way (One Variable per Line) 

int a = 10; 
int b = 20; 
int c = 30; 
System.out.println(a + b + c);

Shorter Way (Single Line Declaration)

int a = 10, b = 20, c = 30; 
System.out.println(a + b + c);

Both approaches work the same way. The second option reduces the number of lines, while the first may be easier to read for beginners.

Assigning One Value to Multiple Variables 

Java also allows assigning the same value to several variables in a single statement.

Example

int p, q, r; 
p = q = r = 15; 
System.out.println(p + q + r); 

Output

45

In this example:
  • All three variables receive the value 15 
  • The sum of the variables is then printed

What Are Identifiers?

In Java, every variable, method, or class must have a unique name. These names are called identifiers.

Identifiers help the compiler and programmers recognize and work with data stored in memory.

They can be: 
  • Short (like i, j) 
  • Descriptive (like studentCount, totalMarks)
Using meaningful names makes your code easier to read and maintain.

Choosing Good Identifier Names

Example

// Clear and descriptive 
int secondsPerMinute = 60; 

// Valid, but unclear 
int s = 60;

The first example clearly explains what the value represents.

Rules for Naming Identifiers in Java

When creating identifiers, keep the following rules in mind:
  • Names may include letters, numbers, underscores (_), and dollar signs ($) 
  • The first character must be a letter, underscore, or dollar sign 
  • Identifiers cannot contain spaces 
  • By convention, variable names start with a lowercase letter
  • Java is case-sensitive (count and Count are different) 
  • Java keywords cannot be used as identifiers

Examples of Invalid Identifiers

The following examples will cause compilation errors:

// Incorrect identifier names 
int 5items = 10;     // Cannot begin with a number 
int total cost = 50; // Spaces are not allowed 
int boolean = 1;     // Java keyword cannot be used

What Is a Constant in Java?

In Java, a constant is a variable whose value cannot be modified once it is assigned. To create a constant, you use the final keyword.

Once a variable is marked as final, it becomes read-only throughout the program.

Example: Using final Variables

final int MAX_USERS = 100;

// Trying to change the value will cause an error 
MAX_USERS = 120;   // Compilation error

The compiler prevents reassignment because MAX_USERS is declared as final.

When Should You Use final?

Use final when a value:
  • Should remain constant throughout the program 
  • Represents fixed data like limits, configuration values, or universal facts

Common Examples

final int DAYS_IN_WEEK = 7; 
final int CURRENT_YEAR = 2026;

These values are not expected to change during program execution.

Naming Convention for Constants 

By convention:
  • Constant names are written in UPPERCASE 
  • Words are separated using underscores (_)
final double PI_VALUE = 3.14159;

This naming style is recommended, not mandatory, but it improves readability and helps other developers quickly identify constants.



Tags
Our website uses cookies to enhance your experience. Learn More
Accept !