Codectionary / Developer documentation / Java

Type Casting

Type casting converts a value from one data type to another. Widening (implicit) casting happens automatically when converting a smaller type to a larger one, like int to double, since no data can be lost. Narrowing (explicit) casting requires you to manually write the target type in parentheses, since converting a larger type to a smaller one - like double to int - can lose data or precision.

Syntax

(targetType) value

Examples

Widening (Implicit) Casting

Automatic conversion from a smaller type to a larger one - safe, no data loss.

int num = 100;
double converted = num;  // int -> double, happens automatically

System.out.println(converted);  // 100.0

long bigNumber = num;    // int -> long, also automatic
System.out.println(bigNumber);

Narrowing (Explicit) Casting

Manually converting a larger type to a smaller one - potential data loss, so it must be explicit.

double price = 19.99;
int wholePrice = (int) price;  // explicit cast required

System.out.println(wholePrice);  // 19 (decimal part is truncated, not rounded)

long bigValue = 1234567890123L;
int truncated = (int) bigValue;  // may overflow/produce unexpected results
System.out.println(truncated);

Casting Between String and Numeric Types

Strings require conversion methods rather than a simple cast, since String and numeric types are unrelated.

String numberText = "42";
int parsed = Integer.parseInt(numberText);
double parsedDouble = Double.parseDouble("3.14");

System.out.println(parsed + 8);         // 50
System.out.println(parsedDouble * 2);   // 6.28

int value = 100;
String asText = String.valueOf(value);
System.out.println(asText + " units");  // "100 units"

Best practices

  • Use explicit casting only when you understand and accept the potential loss of precision or data
  • Use Integer.parseInt() / Double.parseDouble() to convert String to a number - a direct cast does not work between them
  • Wrap Integer.parseInt() in a try/catch for NumberFormatException when parsing text that might not be a valid number
  • Prefer widening conversions (letting Java do it automatically) over narrowing ones whenever the larger type is acceptable for your use case

At a glance

Purpose
General-purpose application development
File extension
.java
Runs in
Java Virtual Machine
Usually used with
JDK and Java libraries

Specifications & further reading

Related Java documentation

Variables & Primitive Data Types
Java is a statically-typed language, meaning every variable must be declared with an explicit type before use, and that type cannot change afterward. Java has eight primitive types - byte, short, int, long, float, double, char, and boolean - which store simple values directly rather than references, making them fast and memory-efficient. Anything beyond primitives (String, arrays, custom classes) is a reference type instead.
System.out.println / print / printf
System.out is Java's standard output stream, and it exposes three main methods for writing text to the console. println() prints its argument followed by a newline, print() prints without adding a newline, and printf() gives C-style formatted output using format specifiers like %d, %s, and %.2f for precise control over how values are displayed.
Comments & Javadoc
Java supports single-line comments with //, multi-line comments with /* */, and a special documentation format called Javadoc, written as /** */. Javadoc comments support tags like @param, @return, and @throws, and can be processed by the javadoc tool to automatically generate HTML API documentation - the same format used for Java's own official standard library docs.
Arithmetic & Assignment Operators
Java provides the standard arithmetic operators for numeric computation: +, -, *, / for division, and % for the remainder (modulus). It also has compound assignment operators (+=, -=, etc.) that combine an operation with assignment, along with increment (++) and decrement (--) operators in both prefix and postfix forms, which subtly differ in when the value is updated relative to being used.