• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Type Casting in Java – Implicit and Explicit Casting

February 29, 2016 by javainterviewpoint 3 Comments

Type Casting in Java is  nothing but converting a primitive or interface or class in Java into other type. There is a rule in Java Language that classes or interface which shares the same type hierrachy only can be typecasted. If there is no relationship between then Java will throw ClassCastException. Type casting are of two types they are

  1. Implicit Casting (Widening)
  2. Explicit Casting (Narrowing)

Implicit Casting in Java / Widening / Automatic type converion

Automatic type conversion can happen if both type are compatible and target type is larger than source type.

Java Type Casting - Widening

Implicit Casting of a Primitive

No Explicit casting required for the above mentioned sequence.

public class Implicit_Casting_Example 
{
	public static void main(String args[])
	{
	    byte i = 50;
	    // No casting needed for below conversion
	    short j = i;
	    int k = j;
	    long l = k;
	    float m = l;
	    double n = m;
	    
	    System.out.println("byte value : "+i);
	    System.out.println("short value : "+j);
	    System.out.println("int value : "+k);
	    System.out.println("long value : "+l);
	    System.out.println("float value : "+m);
	    System.out.println("double value : "+n);
	}
}

Output :

byte value : 50
short value : 50
int value : 50
long value : 50
float value : 50.0
double value : 50.0

Implicit Casting of a Class Type

We all know that when we are assigning smaller type to a larger type, there is no need for a casting required. Same applies to the class type as well. Lets look into the below code.

class Parent
{
	public void disp()
	{
		System.out.println("Parent disp called");
	}
}
public class Child extends Parent
{
	public static void main(String args[])
	{
		Parent p = new Child();
		p.disp();
	}
}

Here Child class is smaller type we are assigning it to Parent class type which is larger type and hence no casting is required.

Explicit Casting in Java / Narrowing

When you are assigning a larger type to a smaller type, then Explicit Casting is required

Java Type Casting - Narrowing

public class Explicit_Casting_Example 
{
	public static void main(String args[])
	{
		double d = 75.0;
		// Explicit casting is needed for below conversion
		float f = (float) d;
		long l = (long) f;
		int i  = (int) l;
		short s = (short) i;
		byte b = (byte) s;
		
		System.out.println("double value : "+d);
		System.out.println("float value : "+f);
		System.out.println("long value : "+l);
		System.out.println("int value : "+i);
		System.out.println("short value : "+s);
		System.out.println("byte value : "+b);
	}
}

Output :

double value : 75.0
float value : 75.0
long value : 75
int value : 75
short value : 75
byte value : 75

Narrowing a Class Type

We all know that when we are assigning larger type to a smaller type, then we need to explicitly type cast it. Lets take the same above code with a slight modification

class Parent
{
	public void disp()
	{
		System.out.println("Parent disp called");
	}
}
public class Child extends Parent
{
	public void disp()
	{
		System.out.println("Child disp called");
	}
	public static void main(String args[])
	{
		Parent p = new Child();
		p.disp();
		Child c = p;
		c.disp();
	}
}

When we run the above code we will be getting exception stating “Type mismatch: cannot convert from Parent to Child”

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from Parent to Child

	at Child.main(Child.java:18)

In order to fix the code, then we need to cast it to Child class

Child c = (Child) p;

Happy Learning !! 🙂

Other interesting articles which you may like …

  • Java StringTokenizer Example
  • How to Reverse String in Java using String Tokenizer
  • What is the use of a Private Constructors in Java
  • Fibonacci Series Java Example
  • For Loop in Java with Example
  • For-each loop or Enhanced For loop in Java
  • Use of Class.forName in java
  • why we Use Class.forName in SQL JDBC
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Inheritance in Java with Example Programs
  • Types of Inheritance in Java

Filed Under: Core Java, Java Tagged With: Explicit Casting, Implicit Casting, Java, Type Casting

Comments

  1. Priya says

    October 16, 2017 at 11:56 am

    java object typecasting one object reference can be type cast into another object reference. Really thanks for sharing this.

    Reply
  2. Arturo says

    December 18, 2017 at 12:24 am

    Excellent and easy explanation. Thanks a lot!

    Reply
  3. Amjed Anver says

    July 30, 2018 at 9:49 pm

    well and excellent explanation wow. thank you so much 🙂

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·