• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Language » Type Casting in Java
Next →
← Prev

Type Casting in Java

By Dinesh Thakur

Type Casting: The process of converting one data type to another is called casting. Casting is often necessary when a function returns a data of type in different form then we need to perform an operation. Under certain circumstances Type conversion can be carried out automatically, in other cases it must be “forced” manually (explicitly). For example, the read() member function of the standard input stream (System.in) returns an int. If we want to store data of type int returned by read() into a variable of char type, we need to cast it :

char k = (char)System.in.read();

The cast is performed by placing the desired type in parentheses to the left of the value to be converted. The System.in.read() function call returns an int value, which then is cast to a char value because of the (char) cast. The resulting char value is then stored in the char variable k. 

The storage size of the types while casting is very important otherwise the data loss will occur. For example, suppose we cast a long to an int. A long is a 64-bit value and an int is a 32-bit value. When casting a long to an int, the compiler truncates the upper 32 bits of the long value so as to fit into the 32-bit int. If the upper 32 bits of the long contain any useful information, then data loss will occur.

In some cases, the data type of the expression is changed automatically to the variable’s data type. For example, suppose that i is an integer variable declared as follows:

int i = 10;

Even though d is a variable of type double, the following assignment is valid:

double d = i; // valid, i is converted to type double

Java changes i from int to double, and then assigns it to d. This conversion does not cause any loss of information because the double data type is 64 bits wide and thus is wider than the int data type that has 32 bits. This is called a widening conversion because a narrower type is converted to a wider type, and it takes place implicitly. Here are some more examples of when widening conversions occur:

short s = 10;

int num= s;

float f = num;

double d = f;

Figure summarizes the conversion rules: A conversion occurs from a given data type to any of the data types on its right. For example, a conversion from byte to anyone of the following can take place: short, int, long,float, and double; however, a float can be converted only to a double.

                      Conversion and casting rules

On the other hand, assigning a value of type double to an int causes a compilation error:

double d = 100.5;

int i = d; // error!

Java does not allow this assignment because a double can hold a larger range of values than an int, and it could result in an inadvertent loss of data if d is larger than the largest value that can be stored in an int, or if it is smaller than the smallest value that can be stored in an into To allow this type of assignment, it is necessary for the programmer to force a conversion from double to int using a cast.

For example, a cast is used here to force a conversion of the variable d to type int and then assign it to i:

int i = (int) d; // i = 100

Note that this assignment truncates (not rounds) the fractional part so that it assigns 100 to i.

Figurealso depicts all cases when casting is needed; a cast must be used to convert a particular type to any of the types on its left. Thus, a cast is needed to convert from type float to type byte, short, int, or long:

float f = (float) 10.5;  // cast a literal of type double to float

byte b = (byte) f;      // cast a float to byte

short s1 = (short) f;   // cast a float to short

int i = (int) f;        // cast a float to int

long 1 = (long) f;     // cast a float to long

A booleanvariable can be assigned only values of type boolean. Conversely, a variable of any of the other data types cannot be assigned a boolean value.

Automatic Conversion: In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign: byte -> short -> int -> long -> float -> double.

For example :

//64 bit long integer

long myLongInteger;

//32 bit long integer

int myInteger;

myLongInteger = myInteger;

The extra storage associated with the long integer, in the above example, will simply be padded with extra zeros.

Explicit Conversion (Casting): The above will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion (assuming of course that the long integer will fit into a standard integer). This is done using a process known as a type cast :

myInteger = (int) myLongInteger

This tells the compiler that the type of myLongInteger must be temporarily changed to a int when the given assignment statement is processed. Thus, the cast only lasts for the duration of the assignment. Java type casts have the following form: (T) N where T is the name of a numeric type and N is a data item of another numeric type. The result is of type T.

Casting between classes can be broken into three different situations:

• Casting from a subclass to a superclass

• Casting from a superclass to a subclass

In the case of casting from a subclass to a superclass, we can cast either implicitly or explicitly. Implicit casting simply means auto casting; explicit casting means that we have to provide the class type in parentheses. Casting from subclass to superclass is completely reliable because subclasses contain information about their super classes.

Casting from a superclass to a subclass has to be done explicitly and is also not reliable because the compiler has no idea whether the class being cast to is a subclass of the superclass or not.

Double a = new Double (12.75);

Number b = a;

Double c = (Double) b;

Long d = a; / / results in error

In this example, data type wrapper objects are created and assigned to each other. The Double and Long sibling classes are both derived from the Number class. In the example, after the Double object a is created, it is assigned to a Number object. This is an example of implicitly casting from a subclass to a superclass. Another Double object, c, is then assigned the value of the Number object. Since, we are casting from a superclass to a subclass, an explicit casting is required. Finally, a Long object is assigned the value of a Double object. This is a casting between siblings and is not allowed in Java so results in an error.

You’ll also like:

  1. Difference Between Type Conversion and Type Casting
  2. Type Casting in Java Example
  3. Explicit Type Conversion (Type Casting)
  4. Type Casting in C
  5. Type Casting Of Pointers in C
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW