Programming and Java Fundamentals
Type Conversion and Casting
You are viewing a free preview lesson.
Lesson Overview
In a program, not every value has the same data type.
Sometimes:
- An
intvalue needs to be used as along - A
doublevalue needs to be converted to anint - The text
"30"needs to be converted to numeric30 - A number needs to be converted to a
Stringfor output - The numeric value of a
charneeds to be determined
The process of changing a value from one type to another is called type conversion.
Java performs some conversions automatically. Other conversions must be performed explicitly.
In this lesson, we will learn:
- Implicit and explicit conversion
- Widening conversion
- Narrowing conversion
- Casting
- Data loss
- Numeric expression conversion
charand number conversion- Parsing String values into numbers
- Converting numbers to String
Learning Objectives
After completing this lesson, you will be able to:
- Explain type conversion
- Distinguish between widening and narrowing conversion
- Understand automatic numeric conversion
- Write explicit casts
- Convert decimal values to integers
- Understand the possibility of data loss
- Apply casts at the correct point in a calculation
- Convert between
charand integer values - Parse numbers from Strings
- Convert primitive values to String
What Is Type Conversion?
Type conversion means changing a value from one data type to another.
Example:
int studentCount = 100;
long totalStudents = studentCount;
Here, the int value has been converted to long.
Another example:
double price = 99.75;
int wholePrice = (int) price;
Result:
99
Here, the decimal part has been lost.
Two Types of Conversion
In Java, we will mainly look at two types of conversion:
- Implicit conversion
- Explicit conversion
Implicit Conversion
When Java performs a compatible type conversion automatically, it is called implicit conversion.
int value = 100;
long largerValue = value;
No cast was required here.
Java automatically converted the int value to long.
Explicit Conversion
When the developer explicitly specifies the target type and requests a conversion, it is called explicit conversion.
double value = 99.75;
int wholeValue = (int) value;
Here:
(int)
is a cast.
Widening Conversion
Conversion from a smaller numeric type to a wider compatible type is called widening conversion.
Simplified order:
byte
↓
short
↓
int
↓
long
↓
float
↓
double
Example:
byte score = 100;
int expandedScore = score;
Another example:
int studentCount = 50_000;
long totalStudentCount = studentCount;
These conversions are generally automatic.
Why Is Widening Automatic?
A wider type can generally accommodate the range of a smaller type.
For example:
byte:
-128 to 127
All of these values fit inside an int.
Therefore:
byte value = 100;
int result = value;
can be performed automatically.
Some Widening Examples
byte smallValue = 100;
int intValue = smallValue;
int quantity = 5;
long largeQuantity = quantity;
int score = 90;
double decimalScore = score;
In the last example:
90
becomes:
90.0
Narrowing Conversion
Conversion from a wider type to a smaller type is called narrowing conversion.
double price = 99.75;
int wholePrice = (int) price;
During narrowing:
- The decimal part may be lost
- The value may be outside the target type's range
- Precision may be lost
For this reason, an explicit cast is required.
Casting Syntax
Syntax:
(targetType) value
Example:
double average = 85.75;
int wholeAverage = (int) average;
Here:
Target type: int
Source type: double
Narrowing Without a Cast
Invalid:
double price = 99.75;
int wholePrice = price;
Correct:
int wholePrice = (int) price;
Casting Does Not Round
double value = 99.99;
int result = (int) value;
Result:
99
Casting does not choose the nearest integer.
The decimal part is simply discarded.
Negative Value
double value = -99.99;
int result = (int) value;
Result:
-99
The conversion truncates toward zero.
Truncation
Discarding the decimal part is called truncation.
99.99 → 99
99.10 → 99
-99.99 → -99
-99.10 → -99
Narrowing Is Not Always Safe
int value = 130;
byte result = (byte) value;
System.out.println(result);
Output:
-126
because 130 is outside the byte range.
Important:
A cast tells the compiler to allow the conversion. It does not guarantee that the result will be logically correct.
Integer and Decimal Conversion
Integer to decimal:
int score = 90;
double decimalScore = score;
Result:
90.0
Decimal to integer:
double score = 90.75;
int wholeScore = (int) score;
Result:
90
Type Conversion Inside Expressions
When operands have different numeric types, Java can use a wider compatible type for the expression.
int quantity = 3;
double price = 99.50;
double total =
quantity * price;
Result:
298.5
because the expression contains a double.
Small Integer Arithmetic
Arithmetic involving byte and short is generally evaluated as int.
byte firstValue = 10;
byte secondValue = 20;
int total =
firstValue + secondValue;
This is valid.
But:
byte total =
firstValue + secondValue;
will not compile because the expression result is int.
Cast Position Matters
Suppose:
int total = 5;
int count = 2;
Wrong:
double average =
(double) (total / count);
Step:
5 / 2 → 2
(double) 2 → 2.0
The fractional part has already been lost.
Cast Before Division
Correct:
double average =
(double) total / count;
Step:
(double) total → 5.0
5.0 / 2 → 2.5
Result:
2.5
Cast Before or After the Expression?
These two are not the same:
(int) 10.75 + 5
Here, first:
10.75 → 10
Then:
10 + 5 = 15
On the other hand:
(int) (10.75 + 5.50)
First:
10.75 + 5.50 = 16.25
Then:
16.25 → 16
Parentheses make the target of the cast clear.
Conversion Before Arithmetic Overflow
Look at this code:
int price = 2_000_000_000;
int quantity = 2;
long total =
price * quantity;
price * quantity can first be evaluated using int arithmetic and overflow.
Safer:
long total =
(long) price * quantity;
Now price is converted to long first, so the multiplication uses long arithmetic.
Numeric Conversion from char
A char represents a UTF-16 code unit.
char letter = 'A';
int code = letter;
System.out.println(code);
Output:
65
Conversion from char to int is automatic.
Numeric Value to char
int code = 65;
char letter = (char) code;
System.out.println(letter);
Output:
A
An explicit cast is required here.
Character Arithmetic
char letter = 'A';
char nextLetter =
(char) (letter + 1);
System.out.println(nextLetter);
Output:
B
letter + 1 produces an int result, so it is cast back to char.
A Digit Character and a Number Are Not the Same
char digitCharacter = '7';
int code = digitCharacter;
System.out.println(code);
Output:
55
This is not numeric 7. It is the code value of the '7' character.
String to Number Conversion
External input may often arrive as text.
String ageText = "30";
To use it in a numeric calculation, it must be parsed.
int age =
Integer.parseInt(ageText);
String to int
String quantityText = "3";
int quantity =
Integer.parseInt(quantityText);
int total =
quantity * 500;
System.out.println(total);
Output:
1500
String to long
String populationText =
"8000000000";
long population =
Long.parseLong(populationText);
String to double
String priceText = "99.50";
double price =
Double.parseDouble(priceText);
String to boolean
String activeText = "true";
boolean active =
Boolean.parseBoolean(activeText);
Result:
true
Boolean.parseBoolean() recognizes "true" case-insensitively.
Boolean.parseBoolean("TRUE")
Result:
true
Other text:
Boolean.parseBoolean("yes")
Result:
false
Parsing and Casting Are Not the Same
Casting:
double value = 10.5;
int result = (int) value;
Parsing:
String value = "10";
int result =
Integer.parseInt(value);
Difference:
- Casting converts a value between compatible types
- Parsing interprets text and creates a new typed value
String Cannot Be Directly Cast to a Number
Invalid:
String ageText = "30";
int age = (int) ageText;
Correct:
int age =
Integer.parseInt(ageText);
Invalid Numeric Text
String ageText = "thirty";
int age =
Integer.parseInt(ageText);
This will cause a NumberFormatException at runtime.
"thirty" is not a valid integer representation.
Normalize Whitespace Before Parsing
For this input:
String ageText = " 30 ";
remove surrounding whitespace before parsing:
int age =
Integer.parseInt(
ageText.strip()
);
Decimal Text Cannot Be Parsed Directly as an Integer
Invalid:
String valueText = "10.5";
int value =
Integer.parseInt(valueText);
Correct:
double value =
Double.parseDouble(valueText);
Then, if needed:
int wholeValue =
(int) value;
Number to String Conversion
To convert a primitive value to text, you can use String.valueOf().
int age = 30;
String ageText =
String.valueOf(age);
More examples:
String priceText =
String.valueOf(99.50);
String activeText =
String.valueOf(true);
String gradeText =
String.valueOf('A');
Automatic String Conversion During Concatenation
int age = 30;
String message =
"Age: " + age;
Java uses the text representation of the age value.
Output:
Age: 30
boolean Is Not a Numeric Type
Invalid:
boolean active = true;
int value = (int) active;
Similarly:
int value = 1;
boolean active =
(boolean) value;
is not valid.
In Java, true/false and numeric 1/0 belong to different parts of the type system.
Complete Example: User Input Conversion
public class Main {
public static void main(String[] args) {
String ageInput = "30";
String scoreInput = "85.5";
String activeInput = "true";
int age =
Integer.parseInt(ageInput);
double score =
Double.parseDouble(scoreInput);
boolean active =
Boolean.parseBoolean(activeInput);
System.out.println(
"Age next year: " + (age + 1)
);
System.out.println(
"Score: " + score
);
System.out.println(
"Active: " + active
);
}
}
Output:
Age next year: 31
Score: 85.5
Active: true
Complete Example: Average Calculation
public class Main {
public static void main(String[] args) {
int totalMarks = 250;
int subjectCount = 3;
double average =
(double) totalMarks
/ subjectCount;
System.out.println(
"Average: " + average
);
}
}
Output:
Average: 83.33333333333333
Common Errors
Assuming a Cast Rounds
double value = 9.9;
int result = (int) value;
Result:
9
A cast truncates.
Casting Too Late
Wrong:
double average =
(double) (5 / 2);
Result:
2.0
Correct:
double average =
(double) 5 / 2;
Result:
2.5
Out-of-Range Narrowing
int value = 130;
byte result =
(byte) value;
Result:
-126
A successful cast does not mean the value is safe.
Invalid Numeric Text
Wrong:
int age =
Integer.parseInt("30 years");
Correct input:
int age =
Integer.parseInt("30");
Wrong Parser for a Large Value
Wrong:
int population =
Integer.parseInt(
"8000000000"
);
The value is outside the int range.
Use:
long population =
Long.parseLong(
"8000000000"
);
Direct Number-to-String Cast
Invalid:
int age = 30;
String ageText =
(String) age;
Correct:
String ageText =
String.valueOf(age);
Conversion Guide
| Requirement | Approach |
|---|---|
int → long | Automatic widening |
int → double | Automatic widening |
double → int | Explicit cast |
char → int | Automatic widening |
int → char | Explicit cast |
String → int | Integer.parseInt() |
String → long | Long.parseLong() |
String → double | Double.parseDouble() |
String → boolean | Boolean.parseBoolean() |
| Primitive → String | String.valueOf() |
Important Terms
Type Conversion
Changing a value from one type to another.
Implicit Conversion
A conversion Java performs automatically.
Explicit Conversion
A conversion explicitly requested by the developer.
Widening Conversion
Conversion from a smaller compatible type to a wider type.
Narrowing Conversion
Conversion from a wider type to a smaller type.
Casting
Explicit conversion using:
(targetType) value
Truncation
Discarding the decimal part of a value.
Parsing
Interpreting text content and creating a typed value from it.
Numeric Promotion
Using a compatible wider numeric type when evaluating an expression.
Practice Exercise 1: Widening or Narrowing?
Classify each conversion:
byte→intint→longlong→intfloat→doubledouble→intchar→intint→char
Practice Exercise 2: Cast Decimal Values
Cast the following values to int:
99.99
99.01
-99.99
-99.01
Predict the result.
Practice Exercise 3: Fix the Average
Wrong:
int totalMarks = 250;
int subjectCount = 3;
double average =
totalMarks / subjectCount;
Use casting to produce a decimal average.
Practice Exercise 4: Cast Position
Predict the output:
double firstResult =
(double) (5 / 2);
double secondResult =
(double) 5 / 2;
Explain the difference.
Practice Exercise 5: Character Conversion
char letter = 'A';
Do the following:
- Get the integer code from the
char - Create a
charfrom integer66
Practice Exercise 6: Parse Values
String ageText = "30";
String populationText = "8000000000";
String scoreText = "85.5";
String activeText = "true";
Parse each value into the appropriate type.
Practice Exercise 7: Normalize Before Parsing
String quantityText = " 5 ";
Use strip() and parse it to int, then multiply the result by 2.
Expected output:
10
Practice Exercise 8: Convert to String
Convert the following values to String using String.valueOf():
int age = 30;
double score = 85.5;
boolean active = true;
char grade = 'A';
Knowledge Check
Question 1
What is type conversion?
Question 2
What is implicit conversion?
Question 3
What is explicit conversion?
Question 4
What is widening conversion?
Question 5
What is narrowing conversion?
Question 6
What is the casting syntax?
Question 7
Does converting int to long require a cast?
Question 8
Does converting double to int require a cast?
Question 9
What is the result of (int) 99.99?
Question 10
Does casting perform rounding?
Question 11
Why is it important to cast before division?
Question 12
Is conversion from char to int automatic?
Question 13
What is required to convert int to char?
Question 14
Which method parses a String into an int?
Question 15
Which method parses a String into a long?
Question 16
Which method parses a String into a double?
Question 17
What general method converts a primitive value to String?
Question 18
What can happen when invalid numeric text is parsed?
Question 19
Can a boolean be cast to a numeric type?
Question 20
Are casting and parsing the same?
Knowledge Check Answers
Answer 1
Changing a value from one data type to another is called type conversion.
Answer 2
When Java performs a conversion automatically, it is called implicit conversion.
Answer 3
When the developer explicitly uses a cast or conversion method, it is called explicit conversion.
Answer 4
Conversion from a smaller compatible type to a wider type is called widening conversion.
Answer 5
Conversion from a wider type to a smaller type is called narrowing conversion.
Answer 6
(targetType) value
Answer 7
No. This is generally an automatic widening conversion.
Answer 8
Yes.
int value =
(int) doubleValue;
Answer 9
99
Answer 10
No. It truncates the decimal part.
Answer 11
If integer division happens first, the fractional part is lost. Therefore, if a decimal result is required, one operand must be converted to floating-point before the division occurs.
Answer 12
Yes.
Answer 13
An explicit cast.
(char) 65
Answer 14
Integer.parseInt()
Answer 15
Long.parseLong()
Answer 16
Double.parseDouble()
Answer 17
String.valueOf()
Answer 18
A NumberFormatException can occur.
Answer 19
No.
Answer 20
No. Casting converts compatible typed values. Parsing interprets text and creates a typed value.
Lesson Summary
In this lesson, we learned:
- Type conversion changes a value from one type to another
- Java performs some conversions automatically
- Widening conversion is generally automatic
- Narrowing conversion requires an explicit cast
- Casting syntax is
(targetType) value - Casting from decimal to integer truncates the fractional part
- Casting does not perform rounding
- Narrowing conversion can cause data loss
- A successful cast does not guarantee that the resulting value is safe
- Numeric expression results depend on operand types
- Decimal division requires floating-point conversion before division occurs
chartointconversion is automaticinttocharrequires an explicit cast- String-to-number conversion is performed through parsing
Integer.parseInt(),Long.parseLong(), andDouble.parseDouble()are common parsing methodsString.valueOf()can convert primitive values to String- Parsing invalid numeric text can cause a runtime error
- Boolean values cannot be cast to numeric types
- Casting and parsing are different processes