Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

Java Type Casting: Widening, Narrowing and Converting Text to Numbers

Small into big is automatic; big into small needs a cast, and the cast is your responsibility. Why (int) 9.99 is 9, (byte) 200 is -56, and (double) a / b differs from (double) (a / b).

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Tell automatic widening from narrowing that needs an explicit cast
  • Predict what a cast does to 9.99, -9.99 and values too big for the type
  • Place a cast before a division so the fraction survives
  • Convert between text and numbers with Integer.parseInt and String.valueOf

Before you start

  • Java primitive types and memory
  • Java operators and expressions

Sometimes the type of a value and the type of the variable don't match. Picture containers: pour an int (a small container) into a double (a larger one) and there's plenty of room, so 10 becomes 10.0 and nothing spills. Pour a double like 9.99 into an int and something spills. That's why Java makes you write a cast for that direction.

Small into big is safe and automatic. Big into small needs your permission.

Small into big: no cast

package org.studyeasy.s02l07;

public class Ex01_Widening {
    public static void main(String[] args) {
        int count = 10;
        double price = count;
        System.out.println("int 10 into double: " + price);

        short small = 10;
        int medium = small;
        double large = medium;
        System.out.println("short, int, double: " + small + ", " + medium + ", " + large);

        int big = 123456789;
        float f = big;
        System.out.println("int into float: " + f);
    }
}
int 10 into double: 10.0
short, int, double: 10, 10, 10.0
int into float: 1.2345679E8

You wrote nothing; Java did the conversion. int into float also works, because float's range is bigger than int's. Swap a side, int back = price;, and javac says "possible lossy conversion from double to int".

The widening road

The widening road: byte to short to int to long to float to double, automatic in the arrow direction. char joins the road at int. short and char need a cast in both directions. byteshortint longfloatdouble char cast both ways With the arrows: automatic. Against the arrows: write the cast.
Widening follows the arrows. char joins at int; short and char always need a cast between them.

A char is a number underneath, which is why it joins the road at int:

package org.studyeasy.s02l07;

public class Ex02_CharNumber {
    public static void main(String[] args) {
        char letter = 'A';
        int code = letter;
        System.out.println("A is stored as " + code);

        short number = 66;
        char other = (char) number;
        System.out.println("66 as a char is " + other);
    }
}
A is stored as 65
66 as a char is B

short and char are both 16 bits, yet you need a cast between them in both directions. Remove (char) and you get "possible lossy conversion from short to char".

Big into small: the cast is your promise

package org.studyeasy.s02l07;

public class Ex03_Narrowing {
    public static void main(String[] args) {
        int i = 100;
        byte b = (byte) i;
        System.out.println("byte: " + b);

        double value = 9.99;
        System.out.println("(int) 9.99 = " + (int) value);
        System.out.println("(int) -9.99 = " + (int) -value);

        long rounded = Math.round(value);
        System.out.println("Math.round(9.99) = " + rounded);
    }
}
byte: 100
(int) 9.99 = 9
(int) -9.99 = -9
Math.round(9.99) = 10

Writing (byte) is your promise to Java: "I know 100 fits, I take responsibility". A cast to int chops the decimal part and moves toward zero: 9.99 becomes 9, -9.99 becomes -9. It never rounds. For rounding, use Math.round, which gives back a long.

Too big for the type: it wraps

package org.studyeasy.s02l07;

public class Ex04_Wrapping {
    public static void main(String[] args) {
        int fits = 100;
        int tooBig = 200;
        System.out.println("(byte) 100 = " + (byte) fits);
        System.out.println("(byte) 200 = " + (byte) tooBig);

        double huge = 3.9e10;
        System.out.println("(int) 3.9e10 = " + (int) huge);
    }
}
(byte) 100 = 100
(byte) 200 = -56
(int) 3.9e10 = 2147483647

A byte holds -128 to 127. 200 is past the top, so it wraps round to the bottom: -56. A decimal too big for an int sticks at the int maximum, 2147483647. No error appears in either case. A cast checks nothing; it just hands you a different number.

Cast before you divide

package org.studyeasy.s02l07;

public class Ex05_CastBeforeDivide {
    public static void main(String[] args) {
        int a = 7;
        int b = 2;
        double plain = a / b;
        double early = (double) a / b;
        double late = (double) (a / b);
        System.out.println("a / b = " + plain);
        System.out.println("(double) a / b = " + early);
        System.out.println("(double) (a / b) = " + late);
    }
}
a / b = 3.0
(double) a / b = 3.5
(double) (a / b) = 3.0
  • plain: 7 / 2 between two ints is 3; storing it in a double gives 3.0.
  • early: the cast touches a first, so it's 7.0 / 2 = 3.5.
  • late: the brackets divide first (3), then the cast turns 3 into 3.0. The .5 is already gone.

Put the cast on a number before the division, not on the result.

Between text and numbers

Casting only works between number types. For text you call a method:

package org.studyeasy.s02l07;

public class Ex06_TextNumber {
    public static void main(String[] args) {
        String text = "42";
        int number = Integer.parseInt(text);
        System.out.println("text to number: " + (number + 1));

        String back = String.valueOf(number);
        System.out.println("number to text: " + back + back);
    }
}
text to number: 43
number to text: 4242

Integer.parseInt turns "42" into 42, so adding 1 gives 43. String.valueOf turns the number back into text, and joining two copies gives 4242. Parse "4two" and the run stops with NumberFormatException: For input string: "4two".

Cheat sheet

DirectionExampleWhat happens
Small into bigdouble d = 10;automatic
Big into small(byte) ineeds a cast
Decimal into whole(int) 9.99chopped to 9
Too big for the type(byte) 200wraps to -56
Text to numberInteger.parseInt("42")42
Number to textString.valueOf(42)"42"

Try it yourself: compute the average of 7, 8 and 8 stored as ints so the answer is 7.666..., not 7.0. Where does the cast go?

Keep going in Java · 9 of 79

Previous
Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
Next post
Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program

Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.

Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA

Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.

Java Hello World with Maven: What the JDK Does and What Maven Adds

javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.

Java Variables, Keywords and Naming Rules

A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.

On this page

  • Small into big: no cast
  • The widening road
  • Big into small: the cast is your promise
  • Too big for the type: it wraps
  • Cast before you divide
  • Between text and numbers
  • Cheat sheet
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.