AlgoGalaxy

AlgoGalaxy

University
CodeRush
Jobs
Tools
Insights
Explore
Personalize
KotlinGoPHPRustGraphsArraysBit ManipulationDynamic ProgrammingGreedyHeapLinked ListStackStringsTreesTrieBacktrackingBinary SearchBSTComplexity AnalysisData Structures & Algorithms

Java | Type Casting

Type casting changes how a value is interpreted or converted. Widening conversions are usually safe because the destination can represent the source range; narrowing conversions can lose information, so they require an intentional rule, range validation and a test for the boundary.

Widening Conversion

Moving an int to a long preserves every int value. Java performs this conversion automatically because the larger type can represent the smaller type's range.

Treat this as an explicit contract in code review: name the input, validate it before a side effect, make the resulting state observable in a focused test and keep the rule close to the method that owns it.

Narrowing Conversion

Converting long to int or double to int can discard magnitude or fractional information. Make the cast explicit and validate input before the conversion becomes part of a business decision.

Treat this as an explicit contract in code review: name the input, validate it before a side effect, make the resulting state observable in a focused test and keep the rule close to the method that owns it.

Parsing Text

External text is not yet a trusted number. Parse it at the boundary, handle NumberFormatException deliberately and report which field failed without echoing sensitive input into logs.

Treat this as an explicit contract in code review: name the input, validate it before a side effect, make the resulting state observable in a focused test and keep the rule close to the method that owns it.

Preserve Domain Rules

A cast answers a language question, not a product question. Decide whether rounding, truncation or rejection is correct for the use case before writing the conversion.

Treat this as an explicit contract in code review: name the input, validate it before a side effect, make the resulting state observable in a focused test and keep the rule close to the method that owns it.

Worked Examples

Example 1: Widen an int to long

The conversion is automatic because long has a wider range. Keep the receiving variable's name meaningful so a reader can see why the larger representation is needed.

Java

public class Main {
    public static void main(String[] args) {
        int itemCount = 42;
        long totalItems = itemCount;
        System.out.println(totalItems);
    }
}

Expected Result

42

Example 2: Make a Narrowing Rule Explicit

The cast truncates the fractional part. The example makes that behavior visible; a price or measurement might need a different rounding rule instead.

Java

public class Main {
    public static void main(String[] args) {
        double average = 8.9;
        int truncated = (int) average;
        System.out.println(truncated);
    }
}

Expected Result

8

Example 3: Parse at the Boundary

Text input is parsed once and then represented as an int inside the program. Invalid text gets an intentional failure path rather than an accidental downstream error.

Java

public class Main {
    public static void main(String[] args) {
        String raw = "25";
        int pageSize = Integer.parseInt(raw);
        System.out.println(pageSize);
    }
}

Expected Result

25

Build and Practice Plan

A productive Java practice loop is deliberately small. Compile after one change, make the normal output visible, add a boundary case, and then decide whether the next improvement belongs in a method, an object or a test. The goal is not typing more Java syntax; it is building evidence that the rule continues to hold when input, scale and failure behavior change.

  • Step 1: make widening conversion observable with one normal case, one boundary case and one invalid-input or failure case before expanding the example.
  • Step 2: make narrowing conversion observable with one normal case, one boundary case and one invalid-input or failure case before expanding the example.
  • Step 3: make parsing text observable with one normal case, one boundary case and one invalid-input or failure case before expanding the example.
  • Step 4: make preserve domain rules observable with one normal case, one boundary case and one invalid-input or failure case before expanding the example.

Design Review Questions

Before accepting a change, ask what values are valid, who owns mutation, how an invalid value is reported, which unit or precision applies, and which test proves the behavior. These questions turn beginner syntax into the habits required for production Java services.

Keep framework concerns outside the small example until the local contract is clear. A controller, database client or queue cannot repair a vague type, a hidden state transition or an undefined failure result; they only make the defect harder to observe.

Example 4: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String lesson = "Java Type Casting";
        System.out.println(lesson.toUpperCase());
    }
}

Expected Result

JAVA TYPE CASTING

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 5: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String lesson = "Java Type Casting";
        System.out.println(lesson.toUpperCase());
    }
}

Expected Result

JAVA TYPE CASTING

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 6: Make the input visible

Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String lesson = "Java Type Casting";
        System.out.println(lesson.toUpperCase());
    }
}

Expected Result

JAVA TYPE CASTING

Try next: Replace the sample value with one from your own notes, predict the result, and then run it.

Example 7: Guard an empty boundary

A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static boolean accepted(String value) {
        return value != null && !value.isBlank();
    }

    public static void main(String[] args) {
        System.out.println(accepted("Java Type Casting"));
    }
}

Expected Result

true

Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.

Example 8: Keep the transformation pure

This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static int doubleValue(int value) { return value * 2; }

    public static void main(String[] args) {
        System.out.println(doubleValue(6));
    }
}

Expected Result

12

Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.

Example 9: Make a branch deliberate

Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        int score = 7;
        String result = score >= 5 ? "ready" : "review";
        System.out.println(result);
    }
}

Expected Result

ready

Try next: Change the boundary value by one and explain exactly which branch becomes active.

Example 10: Use a collection without hidden mutation

Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> lessons = List.of("Java Type Casting", "boundary");
        System.out.println(String.join(" | ", lessons));
    }
}

Expected Result

Java Type Casting | boundary

Try next: Add one more item and predict the derived result before executing the code.

Example 11: Return a named outcome

A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    record Outcome(String status, String lesson) {}

    public static void main(String[] args) {
        Outcome outcome = new Outcome("ready", "Java Type Casting");
        System.out.println(outcome.status());
    }
}

Expected Result

ready

Try next: Rename the outcome in your own words while preserving the same success and failure rule.

Example 12: Trace a small loop

Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int value : new int[] {1, 2, 3}) total += value;
        System.out.println(total);
    }
}

Expected Result

6

Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.

Example 13: Keep display at the edge

The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static String display(String value) { return "Lesson: " + value; }

    public static void main(String[] args) {
        System.out.println(display("Java Type Casting"));
    }
}

Expected Result

Lesson: Java Type Casting

Try next: Change only the display text and verify that the underlying rule and result stay unchanged.

Example 14: Test the closest boundary

A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    static int quantity(int value) {
        if (value < 1) throw new IllegalArgumentException("quantity must be positive");
        return value;
    }

    public static void main(String[] args) {
        System.out.println(quantity(1));
    }
}

Expected Result

1

Try next: Try the lowest supported value and then one value just outside the accepted range.

Example 15: Write a tiny regression check

A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting Java Type Casting.

Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.

Java

public class Main {
    public static void main(String[] args) {
        String result = "Java Type Casting".toUpperCase();
        if (!result.equals("JAVA TYPE CASTING")) throw new AssertionError("contract failed");
        System.out.println("contract holds");
    }
}

Expected Result

contract holds

Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.

Common Mistakes

  • Avoid: treating widening conversion as a syntax trick while leaving its domain rule, error behavior or ownership implicit.
  • Avoid: treating narrowing conversion as a syntax trick while leaving its domain rule, error behavior or ownership implicit.
  • Avoid: treating parsing text as a syntax trick while leaving its domain rule, error behavior or ownership implicit.
  • Avoid: treating preserve domain rules as a syntax trick while leaving its domain rule, error behavior or ownership implicit.

Interview Checklist

  • State the type, valid range and unit before describing the line of syntax.
  • Explain what happens for empty, malformed, null or boundary input and why that outcome is intentional.
  • Separate a pure calculation from printing, storage, networking or another outer side effect.
  • Name the test that would reveal a regression in the rule, not merely that a line of code executed.
  • Describe time, memory and precision costs using the actual types and collection sizes involved.
logo of AlgoGalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

AlgoGalaxy University

University HomeTechnology LearningCoding ProblemsLearning ProgressCareer OpportunitiesTechnology InsightsUtilNexa ToolsAlgoGalaxy HomeContact Support

AlgoGalaxy CodeRush

CodeRush HomeProblem SetsProgress TrackerLearn TechnologyTechnology JobsEngineering InsightsDeveloper UtilitiesAlgoGalaxy HomePrivacy Policy
Privacy Policy

 • 

Terms of Service

Copyright © AlgoGalaxy 2026