Java Programming - Lesson 10
Java Variables Explained: Data Types, Declarations, Initialization and Literals
Introduction
Variables are among the most fundamental concepts in computer programming. Almost every useful computer program needs to store, retrieve, process, or modify information. Variables make this possible.
In Java, a variable is a named storage location associated with a particular data type. The data type determines the kind of value the variable can hold and the operations that can be performed on it.
For example, a program that calculates the total cost of purchased items may use variables to store prices, quantities, and the final amount.
Similarly, a student management application may use variables to store names, ages, examination scores, and other information.
In this tutorial, we will explore Java variables, their different data types, variable declaration and initialization, literal formats, and naming conventions.
What You Will Learn
By the end of this lesson, you should understand:
What variables are and why programmers use them.
How to declare and initialize variables.
The different primitive data types in Java.
How to write decimal, octal, and hexadecimal literals.
The differences between float and double.
How to declare character and Boolean variables.
How Unicode and escape sequences work.
The naming conventions used by Java programmers.
1. What Is a Variable in Java?
A variable is a named location used by a program to store a value.
Think of a variable as a labelled container. The label identifies the variable, while the value stored inside it is the information the program needs.
For example:
int age = 25;
In this statement:
int specifies the data type.
age is the variable name.
25 is the value assigned to the variable.
= is the assignment operator.
; terminates the statement.
The variable age stores the integer value 25.
We can display its value using:
System.out.println(age);
Output:
25
Variables can also be updated after they have been declared.
int age = 25;
age = 26;
System.out.println(age);
Output:
26
The original value has been replaced with a new value.
2. Declaring Variables in Java
Variable declaration tells Java the data type and name of a variable.
The general syntax is:
dataType variableName;
For example:
int age;
double salary;
char grade;
boolean isStudent;
These statements declare four variables with different data types.
Notice that none of them has been assigned a value yet.
A variable declaration can also include an initial value.
For example:
int age = 25;
double salary = 75000.50;
char grade = 'A';
boolean isStudent = true;
This process is called initialization.
Declaration Versus Initialization
It is important to understand the difference.
Declaration means introducing a variable and specifying its type and name.
int age;
Initialization means giving the variable its first value.
age = 25;
We can also declare and initialize a variable in one statement:
int age = 25;
For local variables, Java requires that they be definitely assigned before they are used.
For example, this will cause a compilation error:
public class Example {
public static void main(String[] args) {
int age;
System.out.println(age);
}
}
The problem is that age has been declared but not initialized before being used.
The correct version is:
public class Example {
public static void main(String[] args) {
int age = 25;
System.out.println(age);
}
}
Important: Instance variables and class variables receive default values when they are created. Local variables do not receive automatic default values and must be initialized before use.
3. Understanding Java's Primitive Data Types
Java has eight primitive data types.
These types are used to represent basic values such as integers, decimal numbers, individual UTF-16 code units, and logical values.
The eight primitive types are:
byte
short
int
long
float
double
char
boolean
Let's examine them individually.
A. Integer Data Types
Java provides four primitive integer types.
Data type
Storage size
Value range
byte
8 bits
-128 to 127
short
16 bits
-32,768 to 32,767
int
32 bits
-2,147,483,648 to 2,147,483,647
long
64 bits
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
These data types are used to store whole numbers.
1. The byte data type
The byte type is an 8-bit signed integer.
Example:
byte age = 25;
byte maximumValue = 127;
byte minimumValue = -128;
A byte is useful when working with small numerical values or binary data.
2. The short data type
The short type is a 16-bit signed integer.
Example:
short temperature = 250;
short population = 30000;
It can store larger values than a byte but has a smaller range than an integer.
3. The int data type
The int type is a 32-bit signed integer and is one of the most commonly used numerical data types in Java.
Example:
int age = 35;
int salary = 250000;
int numberOfStudents = 500;
For most ordinary whole-number calculations, int is a suitable choice.
4. The long data type
The long type is a 64-bit signed integer.
It is useful when dealing with very large whole numbers.
Example:
long nationalPopulation = 200000000L;
long distance = 9876543210L;
The suffix L identifies a long integer literal.
Using uppercase L is generally recommended because lowercase l can look like the digit 1.
4. Understanding Integer Literal Formats
A literal is a value written directly into a program rather than obtained from a variable or calculation.
Java supports several integer literal formats.
A. Decimal Literals
Decimal is the ordinary number system we use in everyday life.
It uses ten digits, from 0 to 9.
For example:
int number = 127;
The number 127 is interpreted as a decimal value.
B. Octal Literals
Octal is a base-8 number system.
It uses only eight digits:
0, 1, 2, 3, 4, 5, 6, and 7.
In Java, an integer literal beginning with a leading zero is interpreted as octal.
Example:
int octalNumber = 0177;
The octal value 0177 is equivalent to decimal 127.
Be careful when using leading zeros. For example:
int number = 010;
This represents decimal 8, not decimal 10.
C. Hexadecimal Literals
Hexadecimal is a base-16 number system.
It uses sixteen symbols:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.
In Java, hexadecimal integer literals begin with 0x or 0X.
Example:
int hexadecimalNumber = 0x7F;
This is equivalent to decimal 127.
Comparing the Three Formats
All three examples below represent the same numerical value:
int decimal = 127;
int octal = 0177;
int hexadecimal = 0x7F;
System.out.println(decimal);
System.out.println(octal);
System.out.println(hexadecimal);
Output:
127
127
127
Java also supports binary integer literals using the prefix 0b or 0B.
For example:
int binaryNumber = 0b01111111;
This also represents decimal 127.
5. Floating-Point Data Types
Not all numerical values are whole numbers.
Sometimes we need to represent numbers containing fractional parts, such as 25.5, 3.75, or 100.25.
Java provides two floating-point data types:
Data type
Storage size
Approximate precision
float
32 bits
About 6–7 decimal digits
double
64 bits
About 15–16 decimal digits
A. Float
The float data type stores single-precision floating-point numbers.
Example:
float temperature = 36.5F;
float price = 125.75F;
Notice the F suffix.
Java treats floating-point literals containing a decimal point as double by default. Therefore, the suffix F or f is required when assigning such a literal directly to a float.
B. Double
The double data type stores double-precision floating-point numbers.
Example:
double salary = 85000.75;
double distance = 125.6789;
Unlike float, a double literal does not require a suffix because it is the default floating-point literal type.
You may also write an explicit D or d suffix:
double amount = 125.75D;
However, this is optional.
Scientific Notation
Java also supports floating-point literals written in scientific notation.
For example:
double largeNumber = 1.5E6;
double smallNumber = 2.5E-3;
These represent:
1.5E6 = 1,500,000.
2.5E-3 = 0.0025.
Scientific notation is useful when working with extremely large or very small numbers.
Important: Floating-point types cannot represent every decimal fraction exactly. For applications requiring exact decimal arithmetic, such as financial calculations, consider using BigDecimal.
6. Understanding Character Variables (char)
Java provides the char data type for representing a single UTF-16 code unit.
A char occupies 16 bits and is used to represent Unicode values within the Basic Multilingual Plane.
A character literal is enclosed in single quotation marks.
Example:
char letter = 'A';
char grade = 'B';
char symbol = '@';
We can display a character using:
System.out.println(letter);
Output:
A
Character Literals and String Literals
It is important to distinguish between a character and a string.
A character uses single quotation marks:
char letter = 'A';
A string uses double quotation marks:
String name = "Emmanuel";
A char represents one UTF-16 code unit, while a String represents a sequence of characters.
Unicode Character Representation
Unicode is a universal character encoding standard designed to represent text from different writing systems around the world.
Java supports Unicode, allowing programmers to work with many international characters and symbols.
For example:
char letter = '\u0041';
System.out.println(letter);
Output:
A
The Unicode escape \u0041 represents the uppercase letter A.
This format is particularly useful when a character is difficult to type directly using a keyboard.
An important clarification: Some Unicode characters, such as many emoji and certain supplementary-plane characters, require two char values (a surrogate pair). Therefore, a Java char does not represent every possible Unicode character by itself.
7. Understanding Escape Sequences
Java supports special character sequences called escape sequences.
They begin with a backslash (\) and represent characters that may be difficult to type directly or that have special meanings.
Common Java escape sequences include:
Escape sequence
Meaning
\n
Newline
\t
Horizontal tab
\b
Backspace
\r
Carriage return
\f
Form feed
\'
Single quotation mark
\"
Double quotation mark
\\
Backslash
Example:
public class EscapeExample {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
System.out.println("First line\nSecond line");
System.out.println("Name:\tEmmanuel");
System.out.println("She said, \"Hello!\"");
}
}
Output:
Welcome to Java!
First line
Second line
Name: Emmanuel
She said, "Hello!"
Escape sequences are useful when formatting output or representing special characters.
8. Understanding Boolean Variables
Java provides the boolean data type for representing logical values.
A Boolean variable can hold only two values:
true
false
Example:
boolean isRegistered = true;
boolean isAvailable = false;
Boolean variables are particularly useful when a program needs to make decisions.
For example:
public class BooleanExample {
public static void main(String[] args) {
int age = 25;
boolean isAdult = age >= 18;
System.out.println(isAdult);
}
}
Output:
true
The expression age >= 18 evaluates to true, so that value is assigned to isAdult.
Java Boolean Rules
Unlike some programming languages, Java does not automatically interpret numerical values as Boolean values.
For example, the following is invalid:
int number = 1;
// Invalid Java:
boolean result = number;
The correct approach is to use a Boolean expression:
int number = 1;
boolean result = number != 0;
Now the expression explicitly evaluates to either true or false.
9. Java Variable Naming Conventions
Meaningful variable names make programs easier to read, understand, maintain, and debug.
Java programmers generally follow a naming convention called camelCase.
Under this convention:
Variable names begin with a lowercase letter.
The first letter of each subsequent word is capitalized.
Spaces are not used between words.
Examples:
String firstName = "Emmanuel";
int studentAge = 25;
double totalAmount = 4500.75;
boolean isAvailable = true;
Good and Bad Variable Names
Good variable name
Poor variable name
studentName
sn
totalPrice
tp
accountBalance
ab
numberOfStudents
nos
isAvailable
x
Short names are not always wrong. For example, i is commonly used as a loop counter. However, descriptive names are generally preferable when they improve clarity.
Java Naming Rules
Java also has rules governing valid identifiers.
A variable name:
Must not begin with a digit.
Cannot contain spaces.
Cannot be a Java reserved keyword.
Can contain letters, digits, underscores, and dollar signs, subject to Java's identifier rules.
Is case-sensitive.
For example:
int studentAge = 20;
int StudentAge = 25;
These are two different variable names because Java is case-sensitive.
Although the dollar sign and underscore are permitted in identifiers, ordinary variable names are generally clearer when they use descriptive words and camelCase.
Common Java Naming Conventions
Program element
Common convention
Example
Variables
camelCase
studentAge
Methods
camelCase
calculateTotal()
Classes
PascalCase
StudentRecord
Constants
UPPER_SNAKE_CASE
MAXIMUM_SCORE
Packages
Lowercase
studentmanagement
Following these conventions makes your code easier for other Java programmers to understand.
10. Complete Java Program: Demonstrating Variables and Data Types
Now let's combine what we have learned in one practical Java program.
Create a Java Application project in NetBeans named variables.
Create a class called Variables and enter the following code:
public class Variables {
public static void main(String[] args) {
// Integer data types
byte smallNumber = 127;
short mediumNumber = 30000;
int normalNumber = 100000;
long largeNumber = 5000000000L;
// Floating-point data types
float temperature = 36.5F;
double price = 1250.75;
// Character data type
char letter = 'A';
char unicodeLetter = '\u0041';
// Boolean data type
boolean isLearningJava = true;
boolean isCompleted = false;
// Different integer literal formats
int decimalValue = 127;
int octalValue = 0177;
int hexadecimalValue = 0x7F;
int binaryValue = 0b01111111;
// Display integer variables
System.out.println("INTEGER VARIABLES");
System.out.println("Byte: " + smallNumber);
System.out.println("Short: " + mediumNumber);
System.out.println("Int: " + normalNumber);
System.out.println("Long: " + largeNumber);
// Display floating-point variables
System.out.println("\nFLOATING-POINT VARIABLES");
System.out.println("Float: " + temperature);
System.out.println("Double: " + price);
// Display character variables
System.out.println("\nCHARACTER VARIABLES");
System.out.println("Character: " + letter);
System.out.println("Unicode character: " + unicodeLetter);
// Display Boolean variables
System.out.println("\nBOOLEAN VARIABLES");
System.out.println("Learning Java: " + isLearningJava);
System.out.println("Completed: " + isCompleted);
// Display integer literal formats
System.out.println("\nINTEGER LITERAL FORMATS");
System.out.println("Decimal: " + decimalValue);
System.out.println("Octal: " + octalValue);
System.out.println("Hexadecimal: " + hexadecimalValue);
System.out.println("Binary: " + binaryValue);
}
}
Expected Output
When you run the program, you should see:
INTEGER VARIABLES
Byte: 127
Short: 30000
Int: 100000
Long: 5000000000
FLOATING-POINT VARIABLES
Float: 36.5
Double: 1250.75
CHARACTER VARIABLES
Character: A
Unicode character: A
BOOLEAN VARIABLES
Learning Java: true
Completed: false
INTEGER LITERAL FORMATS
Decimal: 127
Octal: 127
Hexadecimal: 127
Binary: 127
Understanding the Complete Program
The program demonstrates how Java stores different kinds of information.
First, we declare four integer variables: byte, short, int, and long.
Next, we declare two floating-point variables: float and double.
We then demonstrate the char type using an ordinary character literal and a Unicode escape sequence.
The Boolean variables demonstrate how Java represents logical values using true and false.
Finally, we demonstrate four different ways of writing integer literals: decimal, octal, hexadecimal, and binary.
Although these numerical literals use different formats, they all represent the same numerical value: 127.
11. Practice Exercises
To strengthen your understanding, complete the following exercises.
Exercise 1: Declaring Variables
Declare variables for the following information:
Your name.
Your age.
Your height.
Your examination grade.
Whether you are learning Java.
Choose appropriate Java data types for each variable.
Exercise 2: Variable Initialization
Create three integer variables.
Declare the first variable without assigning a value, initialize it later, and display its value.
Exercise 3: Integer Literal Formats
Create four integer variables representing the decimal value 100 using:
Decimal notation.
Octal notation.
Hexadecimal notation.
Binary notation.
Display all four values.
Exercise 4: Floating-Point Variables
Declare one float variable and one double variable.
Assign each a decimal value and display the results.
Exercise 5: Character Variables
Declare a character variable containing the letter A.
Declare another character variable using its Unicode escape sequence.
Display both values.
Exercise 6: Boolean Variables
Create Boolean variables named isStudent and hasCompletedCourse.
Assign appropriate true or false values and display them.
Exercise 7: Personal Information Program
Write a Java program that declares and displays your name, age, occupation, and whether you are currently learning Java.
Use meaningful variable names and appropriate data types.
Conclusion
Variables are essential to Java programming because they allow applications to store, retrieve, and manipulate information.
In this lesson, we explored how to declare and initialize varia
bles, the eight primitive data types, integer and floating-point literals, character representation, Unicode, escape sequences, Boolean values, and Java naming conventions.
Understanding these concepts will provide a strong foundation for the more advanced programming topics you will encounter as you continue learning Java.
Remember that good programming is not simply about writing instructions that work. It is also about writing code that is clear, organized, understandable, and easy to maintain.
Watch the accompanying video tutorial via the link below:
https://youtu.be/6b0h6wFMbZY?si=4SwQOMQMhcWeg7Mj
Keep learning, keep practising, and keep developing your programming skills!


Comments
Post a Comment
Welcome to Creative Skills & Hobbies Hub!
This blog is dedicated to recognizing, showcasing, and promoting diverse creative skills and hobbies, with the aim of helping individuals discover and nurture their own creative potentials, etc. We encourage you to share your thoughts, ask questions, and engage with our community.
Your voice matters! Whether you have a new hobby to explore, insights to offer, or creative stories to tell, we’d love to hear from you. Leave a comment below and join the conversation!