Java Type Casting

</>Coding Tamilan.← Java course & curriculum
Java Masterclass · Lesson 08 / 50 · English

Java Type Casting

Convert deliberately. Notice what you lose.

Step-by-step explanationsRunnable JavaPractice + answer

Read this topic in தமிழ் ↗.

By the end of this lesson, you can…

  • Explain the key idea behind Type Casting.
  • Read and run a complete example, then predict what changes.
  • Recognize the topic-specific mistake discussed below.
01 / The concept

Understand the idea

Widening and narrowing conversions have different consequences. Converting an int to double is automatic here. Converting a double to int requires a cast and truncates the fractional part toward zero; it does not round to the nearest integer.

02 / Step by step

Explore the details

Java Type Casting

Type casting means converting a value from one data type into another. Java has two kinds — one happens automatically, and one you must do yourself.

  • Widening Casting (automatic) — smaller type → larger type. Java does this for you because no data can be lost.
  • Narrowing Casting (manual) — larger type → smaller type. You must write it explicitly because data may be lost (e.g. decimals are truncated).

Widening Casting

Widening casting is automatic — Java converts the value without any extra syntax. It is safe because a larger type can always hold a smaller type's value without losing any information.

Code anatomy / கோடின் விளக்கம்

CodeMeaning
doubleThe target (larger) type. Java will automatically accept the int value here.
myDoubleThe new variable that will hold the widened value.
=Assignment operator. Java automatically converts the int on the right to double.
myIntThe int variable being widened. No cast syntax needed — Java handles it automatically.
;End of statement.

Narrowing Casting

Narrowing casting is manual — you must place the target type in parentheses (targetType) before the value. This tells Java you are aware data might be lost.

Data loss example: Casting 9.78 (double) to int gives 9 — the decimal part .78 is silently dropped (truncated, not rounded).

Code anatomy / கோடின் விளக்கம்

CodeMeaning
intThe target (smaller) type we want to convert to.
myIntThe new variable that will hold the narrowed value.
=Assignment operator.
(int)The cast operator. Placed in parentheses before the value, it tells Java to convert to int — and that you accept any possible data loss.
myDoubleThe double variable being narrowed. The decimal part will be truncated (cut off), not rounded.
;End of statement.

Real-Life Example

Imagine a game where a player scores 700 points out of a maximum of 1000. To display the score as a percentage with decimals, we need to cast to double before dividing — otherwise Java performs integer division and drops the decimal:

Java reference fragmentJAVA
// Widening (automatic): smaller → larger type
int myInt = 9;
double myDouble = myInt;   // int automatically becomes double
System.out.println(myDouble);  // 9.0

// Narrowing (manual): larger → smaller type (decimal truncated)
double pi = 3.14159;
int piInt = (int) pi;
System.out.println(piInt);  // 3

// Real-life use: percentage calculation
int score = 700, maxScore = 1000;
double pct = (double) score / maxScore * 100;
System.out.println(pct + "%");  // 70.0%
03 / Read and predict

A complete runnable example

This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.

Main.java · complete runnable exampleJAVA
public class Main {
    public static void main(String[] args) throws Exception {
        int count = 9;
        double widened = count;
        double price = 19.95;
        int narrowed = (int) price;
        System.out.println(widened);
        System.out.println(narrowed);
    }
}
Predict first. Then reveal the expected output / வெளியீடு
9.0
19

The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.

04 / Learn by changing

Change it. Run it. Understand it.

Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.

Open Java editor ↗
After the editor loads, choose Load this lesson example, then press RUN.

Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.

05 / Your turn

Make it your own

Practice challenge

Change price to -19.95. What will narrowed contain?

Reveal the answer and reasoning / விடை

The result is -19 because conversion to int truncates toward zero.

One mistake to avoid: A cast can discard information. Do not use a cast as a substitute for checking whether a value is in the expected range.

Your learning checkpoint

  • Explain the example without reading the output first.
  • Make the change requested in the practice task.
  • Describe why the result changed—or why compilation failed.

Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.

Coding Tamilan · Understand the idea. Try the code. Build the habit.