<< Back to JAVA
Java Cast and Convert Types
Cast variables, including objects and numbers. Arrays too are cast.Casts. Data is typed. Often its type is considered part of the data: it is metadata, information about itself. Casting, in converting types, thus changes data.
Casting and converting in Java is a practical operation. We use implicit (hidden) and explicit (specified) casts. Complex conversions too are needed.
Object and String. This program casts a String variable to its ancestor class Object (all classes derive from Object). It then casts the object back to a String.
Implicit: An implicit cast uses no special expression syntax. Rather it converts one type to another—the compiler decides on its own.
Explicit: This is specified directly in the syntax. The Object is explicitly cast to a String in the third statement.
Java program that uses String, Object cast
public class Program {
public static void main(String[] args) {
String value = "cat";
Object temp = value; // Implicitly cast to Object.
String value2 = (String) temp; // Cast to String.
System.out.println(value2);
}
}
Output
cat
Numeric. Numbers can be cast with the same syntax as classes. For casting to a larger byte size number (a "widening" cast) no cast is required.
But: For "narrowing" casts, where a larger byte size number is reduced to fit in a smaller type, a cast is required.
Data loss: This may occur in a narrowing conversion. Be sure the value can be represented in the new data size.
Java program that uses numeric casts
public class Program {
public static void main(String[] args) {
int size = 5;
double size2 = size; // No cast needed.
byte size3 = (byte) size; // A larger type must be cast down.
System.out.println(size);
System.out.println(size2);
System.out.println(size3);
}
}
Output
5
5.0
5
Invalid cast, ClassCastException. Some casts will fail. And often the compiler will detect an invalid cast at compile-time, saving us the trouble of running an invalid program.
Here: The Object cannot be cast to String, because it is of type StringBuilder. A ClassCastException occurs.
Java program that uses invalid cast
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.append("cat");
Object temp = builder; // This is fine.
String value = (String) temp; // This causes an error.
System.out.println(value);
}
}
Output
Exception in thread "main" java.lang.ClassCastException:
java.lang.StringBuilder cannot be cast to java.lang.String
at program.Program.main(Program.java:10)
Array covariance. This concept means an array of a derived class can be cast to an ancestor class array. So an array of Strings can be cast to an array of Objects.
Object ArraysTip: Array covariance is most often useful when we want to pass an array of any type as an Object array to a commonly-used method.
And: In most programs, array covariance is not important. Using exact types is clearer and faster.
Java program that uses Object array
public class Program {
public static void main(String[] args) {
String[] values = { "cat", "dog", "rabbit" };
// A String array is also an Object array.
Object[] array = values;
// Loop over objects and print String lengths.
for (Object v : array) {
System.out.println(((String) v).length());
}
}
}
Output
3
3
6
Number to String. A number cannot be cast to a String—instead we must convert it with a method like Integer.toString. This method returns a String version of the int argument.
Java program that converts number to String
public class Program {
public static void main(String[] args) {
int number = 100;
String result = Integer.toString(number); // Number to String.
System.out.println(result);
}
}
Output
100
String to number. We convert a String to an integer by parsing it. The Integer.parseInt method can do this. It receives a String argument and returns an int.
StringsJava program that converts String to number
public class Program {
public static void main(String[] args) {
String value = "100";
int result = Integer.parseInt(value); // String to number.
System.out.println(result);
}
}
Output
100
Long to int. Suppose we have a long value and wish to have an int. We can cast the long to an int directly with a cast expression. This works if the int can store the long's value.
However: If the long is out of range and cannot be represented by an int, we will have an incorrect value in the int.
Java program that casts long to int
public class Program {
public static void main(String[] args) {
// Cast long to int directly.
long test = 200;
int result = (int) test;
System.out.println("INT: " + result);
}
}
Output
INT: 200
Long to int, exact. With Math.toIntExact, we can safely convert a long to an int. This may cause an exception if the value cannot be stored in the int, so we must have a try and catch.
MathJava program that converts long to int
import java.lang.Math;
public class Program {
public static void main(String[] args) {
try {
// Use Math.toIntExact to convert long to int.
long test = 200;
int result = Math.toIntExact(test);
System.out.println("INT: " + result);
} catch (ArithmeticException ex) {
System.out.println("ERROR: " + ex);
}
}
}
Output
INT: 200
Double to int. To truncate a double, we can cast it to an int. This eliminates all digits past the decimal place. We can also truncate with Math.floor and Math.ceil.
Truncate NumberJava program that casts double to int
public class Program {
public static void main(String[] args) {
double value = 100.567;
int result = (int) value;
// Write results.
System.out.println("BEFORE: " + value);
System.out.println("AFTER: " + result);
}
}
Output
BEFORE: 100.567
AFTER: 100
Casts versus conversions. Typically casts describe special syntax instructions to convert types. Conversions meanwhile include more complex operations, like converting a String to an array.
Boolean to int. Sometimes we want to convert a boolean into an int. Typically we want true to equal 1, and false to be 0. This is done with a simple method and a ternary expression.
Convert boolean to int
Float. We can cast doubles to floats, but we must specify this with a cast expression. Some conversions to float, like from int, can be done without any special syntax.
FloatCasting is complex. It is often language-specific. Conversions require more steps. They are often reused in many projects and stored in utility classes.
Related Links:
- Java Continue Keyword
- Java Convert Char Array to String
- Java Combine Arrays
- Java Console Examples
- Java Web Services Tutorial
- Java Odd and Even Numbers: Modulo Division
- Java IO
- Java 9 Features
- Java 8 Features
- Java String
- Java Regex | Regular Expression
- Java Filename With Date Example (Format String)
- Java Applet Tutorial
- Java Files.Copy: Copy File
- Java filter Example: findFirst, IntStream
- Java Final and final static Constants
- Java Super: Parent Class
- Java Date and Time
- Java do while loop
- Java Break
- Java Continue
- Java Comments
- Java Splitter Examples: split, splitToList
- Java Math.sqrt Method: java.lang.Math.sqrt
- Java Reflection
- Java Convert String to int
- JDBC Tutorial | What is Java Database Connectivity(JDBC)
- Java main() method
- Java HashMap Examples
- Java HashSet Examples
- Java Arrays.binarySearch
- Java Integer.bitCount and toBinaryString
- Java Overload Method Example
- Java First Words in String
- Java Convert ArrayList to String
- Java Convert boolean to int (Ternary Method)
- Java regionMatches Example and Performance
- Java ArrayDeque Examples
- Java ArrayList add and addAll (Insert Elements)
- Java ArrayList Clear
- Java ArrayList int, Integer Example
- Java ArrayList Examples
- Java Boolean Examples
- Java break Statement
- Java Newline Examples: System.lineSeparator
- Java Stream: Arrays.stream and ArrayList stream
- Java charAt Examples (String For Loop)
- Java Programs | Java Programming Examples
- Java OOPs Concepts
- Java Naming Conventions
- Java Constructor
- Java Class Example
- Java indexOf Examples
- Java Collections.addAll: Add Array to ArrayList
- Java Compound Interest
- Java Int Array
- Java Interface Examples
- Java 2D Array Examples
- Java Remove HTML Tags
- Java Stack Examples: java.util.Stack
- Java Enum Examples
- Java EnumMap Examples
- Java StackOverflowError
- Java startsWith and endsWith Methods
- Java Initialize ArrayList
- Java Object Array Examples: For, Cast and getClass
- Java Objects, Objects.requireNonNull Example
- Java Optional Examples
- Java Static Initializer
- Java static Keyword
- Java Package: Import Keyword Example
- Java Do While Loop Examples
- Java Double Numbers: Double.BYTES and Double.SIZE
- Java Truncate Number: Cast Double to Int
- Java Padding: Pad Left and Right of Strings
- Java Anagram Example: HashMap and ArrayList
- Java Math.abs: Absolute Value
- Java Extends: Class Inheritance
- Java String Class
- Java String Switch Example: Switch Versus HashMap
- Java StringBuffer: append, Performance
- Java Array Examples
- Java Remove Duplicates From ArrayList
- Java if, else if, else Statements
- Java Math.ceil Method
- Java This Keyword
- Java PriorityQueue Example (add, peek and poll)
- Java Process.start EXE: ProcessBuilder Examples
- Java Palindrome Method
- Java parseInt: Convert String to Int
- Java toCharArray: Convert String to Array
- Java Caesar Cipher
- Java Array Length: Get Size of Array
- Java String Array Examples
- Java String compareTo, compareToIgnoreCase
- Java String Concat: Append and Combine Strings
- Java Cast and Convert Types
- Java Math.floor Method, floorDiv and floorMod
- Java Math Class: java.lang.Math
- Java While Loop Examples
- Java Reverse String
- Java Download Web Pages: URL and openStream
- Java Math.pow Method
- Java Math.round Method
- Java Right String Part
- Java MongoDB Example
- Java Substring Examples, subSequence
- Java Prime Number Method
- Java Sum Methods: IntStream and reduce
- Java switch Examples
- Java Convert HashMap to ArrayList
- Java Remove Duplicate Chars
- Java Constructor: Overloaded, Default, This Constructors
- Java String isEmpty Method (Null, Empty Strings)
- Java Regex Examples (Pattern.matches)
- Java ROT13 Method
- Java Random Number Examples
- Java Recursion Example: Count Change
- Java reflect: getDeclaredMethod, invoke
- Java Count Letter Frequencies
- Java ImmutableList Examples
- Java String equals, equalsIgnoreCase and contentEquals
- Java valueOf and copyValueOf String Examples
- Java Vector Examples
- Java Word Count Methods: Split and For Loop
- Java Tutorial | Learn Java Programming
- Java toLowerCase, toUpperCase Examples
- Java Ternary Operator
- Java Tree: HashMap and Strings Example
- Java TreeMap Examples
- Java while loop
- Java Convert String to Byte Array
- Java Join Strings: String.join Method
- Java Modulo Operator Examples
- Java Integer.MAX VALUE, MIN and SIZE
- Java Lambda Expressions
- Java lastIndexOf Examples
- Java Multiple Return Values
- Java String.format Examples: Numbers and Strings
- Java Joiner Examples: join
- Java Keywords
- Java Replace Strings: replaceFirst and replaceAll
- Java return Examples
- Java Multithreading Interview Questions (2021)
- Java Collections Interview Questions (2021)
- Java Shuffle Arrays (Fisher Yates)
- Top 30 Java Design Patterns Interview Questions (2021)
- Java ListMultimap Examples
- Java String Occurrence Method: While Loop Method
- Java StringBuilder capacity
- Java Math.max and Math.min
- Java Factory Design Pattern
- Java StringBuilder Examples
- Java Mail Tutorial
- Java Swing Tutorial
- Java AWT Tutorial
- Java Fibonacci Sequence Examples
- Java StringTokenizer Example
- Java Method Examples: Instance and Static
- Java String Between, Before, After
- Java BitSet Examples
- Java System.gc, Runtime.getRuntime and freeMemory
- Java Character Examples
- Java Char Lookup Table
- Java BufferedWriter Examples: Write Strings to Text File
- Java Abstract Class
- Java Hashtable
- Java Math class with Methods
- Java Whitespace Methods
- Java Data Types
- Java Trim String Examples (Trim Start, End)
- Java Exceptions: try, catch and finally
- Java vs C#
- Java Float Numbers
- Java Truncate String
- Java Variables
- Java For Loop Examples
- Java Uppercase First Letter
- Java Inner Class
- Java Networking
- Java Keywords
- Java If else
- Java Switch
- Loops in Java | Java For Loop
- Java File: BufferedReader and FileReader
- Java Random Lowercase Letter
- Java Calendar Examples: Date and DateFormat
- Java Case Keyword
- Java Char Array
- Java ASCII Table
- Java IntStream.Range Example (Get Range of Numbers)
- Java length Example: Get Character Count
- Java Line Count for File
- Java Sort Examples: Arrays.sort, Comparable
- Java LinkedHashMap Example
- Java Split Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf