Java Programming - Lesson 9
Java Data Types, Type Casting and Operators: A Complete Beginner's Guide
Introduction
Every programming language has rules governing how information is stored, manipulated, and compared. Java is no exception.
When writing Java programs, you will frequently work with different types of data, perform mathematical calculations, compare values, and assign results to variables.
Java provides specific rules that determine which data types can be used together and how values can be converted from one type to another.
In this lesson, we will explore Java's data type rules, type casting, arithmetic operators, increment and decrement operators, assignment operators, and comparison operators.
By the end of this tutorial, you should understand how to:
Recognize the differences between Java's integer data types.
Understand widening and narrowing conversions.
Convert values using type casting.
Perform mathematical calculations using arithmetic operators.
Use increment and decrement operators.
Apply assignment and compound assignment operators.
Compare values using comparison operators.
Understand the difference between assignment and equality testing.
1. Understanding Java's Integer Data Types
Java is a strongly and statically typed programming language. This means variables have declared types, and the compiler checks whether operations and assignments are compatible with those types.
Java provides several primitive data types for storing whole numbers.
The three integer types examined in this lesson are short, int, and long.
Data type
Size
Value range
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
The size of a data type determines how much information it can represent.
For example:
short smallNumber = 100;
int normalNumber = 50000;
long largeNumber = 5000000000L;
Notice the letter L at the end of the long literal. It identifies the number as a long value.
2. Understanding Widening Conversion
Widening conversion occurs when a value is converted from a smaller compatible data type into a larger data type.
Java performs many widening conversions automatically.
For example:
short shortNumber = 100;
int intNumber = shortNumber;
System.out.println(intNumber);
Output:
100
This works because every possible value of a Java short can be represented by an int.
Similarly:
int number = 50000;
long largeNumber = number;
System.out.println(largeNumber);
Output:
50000
The conversion happens automatically because a long can accommodate every possible int value.
This is called implicit widening conversion.
3. Understanding Narrowing Conversion
Narrowing conversion occurs when a value is converted from a wider data type into a narrower one.
Unlike widening conversion, narrowing usually requires an explicit cast.
For example:
long largeNumber = 50000;
short smallNumber = (short) largeNumber;
System.out.println(smallNumber);
Output:
-15536
Why does this happen?
A Java short can only represent values between -32,768 and 32,767.
The original value, 50,000, is outside that range. When Java narrows the value to a short, the resulting 16-bit pattern is interpreted as a signed short, producing -15,536.
This illustrates an important principle:
A successful cast does not necessarily mean that the original value has been preserved.
Always consider the possible loss of information when converting from a wider type to a narrower type.
4. Understanding the Type Casting Operator
Type casting allows programmers to request an explicit conversion.
The general syntax is:
targetDataType variableName = (targetDataType) value;
For example:
double price = 45.75;
int wholePrice = (int) price;
System.out.println(wholePrice);
Output:
45
When a floating-point number is converted to an integer, Java discards the fractional part. It does not round to the nearest whole number.
For negative numbers, conversion to an integer also truncates toward zero.
A Practical Example Using Hexadecimal Values
Consider the following:
long number = 0xCAFEBABEL;
short result = (short) number;
System.out.println(number);
System.out.println(result);
The hexadecimal number 0xCAFEBABE contains more bits than a short can store.
When converted to a short, only the lowest 16 bits are retained. These are:
0xBABE
Interpreted as a signed 16-bit integer, this produces:
-17730
The original positive long value is therefore not preserved.
This example demonstrates why narrowing conversions must be handled carefully.
5. Understanding Java Arithmetic Operators
Arithmetic operators allow us to perform mathematical calculations.
Java provides five basic arithmetic operators.
Operator
Name
Example
Result
+
Addition
64 + 64
128
-
Subtraction
128 - 127
1
*
Multiplication
1 * 100
100
/
Division
100 / 10
10
%
Remainder
10 % 4
2
Addition Operator (+)
The addition operator combines two numerical values.
int firstNumber = 64;
int secondNumber = 64;
int result = firstNumber + secondNumber;
System.out.println(result);
Output:
128
Subtraction Operator (-)
The subtraction operator calculates the difference between two values.
int result = 128 - 127;
System.out.println(result);
Output:
1
Multiplication Operator (*)
The multiplication operator multiplies two values.
int result = 10 * 10;
System.out.println(result);
Output:
100
Division Operator (/)
The division operator divides one number by another.
int result = 100 / 10;
System.out.println(result);
Output:
10
Important: When both operands are integers, Java performs integer division.
For example:
System.out.println(10 / 4);
Output:
2
The fractional part is discarded.
To obtain a decimal result, use a floating-point operand:
System.out.println(10.0 / 4);
Output:
2.5
Also remember that integer division by zero throws an ArithmeticException.
Remainder Operator (%)
The remainder operator, also called the modulus operator, returns the remainder after division.
For example:
int result = 10 % 4;
System.out.println(result);
Output:
2
This is because 4 goes into 10 twice, leaving a remainder of 2.
The remainder operator is useful for determining whether a number is even or odd.
int number = 15;
if (number % 2 == 0) {
System.out.println("Even number");
} else {
System.out.println("Odd number");
}
Output:
Odd number
6. Understanding Increment and Decrement Operators
Java provides two operators that make it easy to increase or decrease a variable's value by one.
Increment Operator (++)
The increment operator increases a variable by one.
int number = 5;
number++;
System.out.println(number);
Output:
6
The statement number++ is equivalent to:
number = number + 1;
Decrement Operator (--)
The decrement operator decreases a variable by one.
int number = 5;
number--;
System.out.println(number);
Output:
4
It is equivalent to:
number = number - 1;
Pre-Increment and Post-Increment
There are two ways to use the increment operator.
Post-increment:
int number = 2;
System.out.println(number++);
System.out.println(number);
Output:
2
3
With post-increment, the current value is used in the expression before the variable is increased.
Pre-increment:
int number = 2;
System.out.println(++number);
System.out.println(number);
Output:
3
3
With pre-increment, the variable is increased before its value is used in the expression.
Pre-Decrement and Post-Decrement
The same principle applies to decrement.
Post-decrement:
int number = 3;
System.out.println(number--);
System.out.println(number);
Output:
3
2
Pre-decrement:
int number = 3;
System.out.println(--number);
System.out.println(number);
Output:
2
2
Practical advice: Although these operators are useful, avoid placing several increments or decrements in a complicated expression. Simple statements are easier to read, understand, and debug.
7. Understanding Assignment Operators
The assignment operator (=) assigns a value to a variable.
For example:
int number = 99;
System.out.println(number);
Output:
99
Assignment is also an expression that produces the assigned value.
For example:
int number;
System.out.println(number = 99);
Output:
99
The expression assigns 99 to number and evaluates to 99.
Remember:
= means assignment.
== means equality comparison.
They perform different operations.
8. Understanding Compound Assignment Operators
Compound assignment operators combine an operation with assignment.
For example:
int number = 10;
number += 5;
System.out.println(number);
Output:
15
The statement:
number += 5;
is equivalent to:
number = number + 5;
Other compound assignment operators include:
Operator
Meaning
Example
+=
Add and assign
number += 5
-=
Subtract and assign
number -= 5
*=
Multiply and assign
number *= 5
/=
Divide and assign
number /= 5
%=
Calculate remainder and assign
number %= 5
An Important Feature of Compound Assignment
Compound assignment can perform an implicit narrowing conversion that ordinary assignment would not allow.
For example:
short number = 10;
number += 5;
This is valid Java.
However, the following statement is not valid without a cast:
short number = 10;
number = number + 5;
This is because the arithmetic expression involving short values is promoted to int.
The compound assignment operator automatically converts the result back to the type of the variable on the left.
This convenience should be used carefully because narrowing can cause information loss.
9. Understanding Java Comparison Operators
Comparison operators allow a program to compare two values.
The result of a comparison is always a Boolean value: true or false.
Java provides six commonly used comparison operators.
Operator
Meaning
Example
Result
>
Greater than
100 > 99
true
<
Less than
100 < 99
false
>=
Greater than or equal to
100 >= 100
true
<=
Less than or equal to
100 <= 99
false
==
Equal to
100 == 99
false
!=
Not equal to
100 != 99
true
Greater Than (>)
Checks whether the value on the left is greater than the value on the right.
System.out.println(100 > 99);
Output:
true
Less Than (<)
Checks whether the left value is smaller than the right value.
System.out.println(100 < 99);
Output:
false
Greater Than or Equal To (>=)
Checks whether the left value is greater than or equal to the right value.
System.out.println(100 >= 100);
Output:
true
Less Than or Equal To (<=)
Checks whether the left value is smaller than or equal to the right value.
System.out.println(100 <= 99);
Output:
false
Equal To (==)
Checks whether two primitive values are equal.
System.out.println(100 == 100);
Output:
true
Not Equal To (!=)
Checks whether two values are different.
System.out.println(100 != 99);
Output:
true
Important: The order of the symbols matters. Write >= and <=, not => or =<.
10. Assignment (=) Versus Equality (==)
This is one of the most important distinctions in Java.
The single equals sign assigns a value:
int age = 25;
The double equals sign compares values:
System.out.println(age == 25);
Output:
true
Using the wrong operator can cause errors or unexpected results.
For primitive types such as int, short, and long, == compares their numerical values.
For objects, however, == checks whether two references point to the same object, not whether their contents are equal. To compare many objects by their contents, programmers use methods such as equals() where appropriate.
11. Complete Java Program: Demonstrating Operators
Let's combine several of the operators we have studied in one Java application.
Create a Java project named operators in NetBeans and use the following code.
public class Operators {
public static void main(String[] args) {
// Integer data types
short shortNumber = 100;
int intNumber = shortNumber;
long longNumber = 500000L;
System.out.println("DATA TYPE CONVERSION");
System.out.println("Short value: " + shortNumber);
System.out.println("Integer value: " + intNumber);
System.out.println("Long value: " + longNumber);
// Explicit type casting
short convertedNumber = (short) longNumber;
System.out.println("Casted short value: " + convertedNumber);
// Arithmetic operators
System.out.println("\nARITHMETIC OPERATORS");
int a = 64;
int b = 64;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (128 - 127));
System.out.println("Multiplication: " + (10 * 10));
System.out.println("Division: " + (100 / 10));
System.out.println("Remainder: " + (10 % 4));
// Increment and decrement
System.out.println("\nINCREMENT AND DECREMENT");
int number = 2;
System.out.println("Post-increment: " + number++);
System.out.println("After post-increment: " + number);
System.out.println("Pre-increment: " + ++number);
System.out.println("Post-decrement: " + number--);
System.out.println("After post-decrement: " + number);
System.out.println("Pre-decrement: " + --number);
// Assignment operators
System.out.println("\nASSIGNMENT OPERATORS");
int score = 99;
System.out.println("Assigned value: " + score);
score += 10;
System.out.println("After += 10: " + score);
score -= 5;
System.out.println("After -= 5: " + score);
score *= 2;
System.out.println("After *= 2: " + score);
// Comparison operators
System.out.println("\nCOMPARISON OPERATORS");
System.out.println("100 > 99: " + (100 > 99));
System.out.println("100 < 99: " + (100 < 99));
System.out.println("100 >= 100: " + (100 >= 100));
System.out.println("100 <= 99: " + (100 <= 99));
System.out.println("100 == 99: " + (100 == 99));
System.out.println("100 != 99: " + (100 != 99));
}
}
Expected Output
DATA TYPE CONVERSION
Short value: 100
Integer value: 100
Long value: 500000
Casted short value: -24288
ARITHMETIC OPERATORS
Addition: 128
Subtraction: 1
Multiplication: 100
Division: 10
Remainder: 2
INCREMENT AND DECREMENT
Post-increment: 2
After post-increment: 3
Pre-increment: 4
Post-decrement: 4
After post-decrement: 3
Pre-decrement: 2
ASSIGNMENT OPERATORS
Assigned value: 99
After += 10: 109
After -= 5: 104
After *= 2: 208
COMPARISON OPERATORS
100 > 99: true
100 < 99: false
100 >= 100: true
100 <= 99: false
100 == 99: false
100 != 99: true
12. Practice Exercises
The best way to understand programming is to practise writing and running your own code.
Try these exercises:
Exercise 1: Data Type Conversion
Declare a short, an int, and a long variable. Assign the short value to the integer variable and the integer value to the long variable.
Observe the results.
Exercise 2: Type Casting
Declare a double variable with the value 45.89. Convert it into an integer using an explicit cast.
What value do you get, and why?
Exercise 3: Arithmetic Operators
Write a program that accepts or declares two numbers and performs addition, subtraction, multiplication, division, and remainder calculations.
Exercise 4: Increment and Decrement
Create an integer variable with an initial value of 10. Demonstrate the difference between pre-increment, post-increment, pre-decrement, and post-decrement.
Exercise 5: Compound Assignment
Create a variable named balance with an initial value of 500.
Use compound assignment operators to:
Add 200.
Subtract 100.
Multiply the result by 2.
Divide the result by 4.
Display the final value.
Exercise 6: Comparison Operators
Write a program that compares two numbers using all six comparison operators.
Display the Boolean result of each comparison.
Conclusion
Java's data type rules and operators are essential building blocks for writing effective programs.
We have learned that Java allows compatible widening conversions automatically but requires explicit casting for many na
rrowing conversions. We have also explored how arithmetic operators perform calculations, how increment and decrement operators modify values, and how assignment operators simplify variable updates.
Finally, we examined comparison operators, which produce Boolean values and allow programs to evaluate conditions.
As you continue learning Java, you will discover that these operators are used throughout programming—from simple calculations to complex decision-making, data processing, and application development.
Watch the accompanying video tutorial via the link below:
https://youtu.be/WF-wRVgnWRc?si=tMWr7DAd-okDiLid
Keep practising, keep experimenting, and keep building 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!