Type Casting in Java: Everything You Need to Know

Type casting, also known as type conversion, is an important concept in Java that allows us to convert one data type into another. It is useful when we need to perform operations on different data types or when you want to store a value of one data type into a variable of another data type. 

Type casting in Java involves converting variables between different data types, essential for versatile programming. Mastery of type casting ensures efficient handling of data, whether primitive types or objects. Enroll in a Java Course to deepen your understanding and gain practical experience in this fundamental concept.

In this article, we will know the basics of type casting in Java and how it can be used effectively. We have also included some common type casting in Java with example of various kinds of typecasting in Java. This will enable you to understand the type casting or conversion in a better way.

What is Type Casting?

Typecasting is the process of converting the value of a single data type (such as an integer [int], float, or double) into another data type. This conversion is done either automatically or manually. The compiler performs the automatic conversion, and a programmer does the manual conversion. To use a variable in a particular way in automatic conversion, we need to explicitly tell the Java compiler to convert a variable from one data type to another data type.

Syntax:

<datatype> variableName = (<datatype>) value;

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Importance of Type Casting in Java Programming

Type conversion and casting in Java bear huge importance. Below are the most significant reasons to use type casting or type conversion.

  • Preventing Data Loss: When we change data from one type to another, we need to ensure that we do not lose any valuable information. Type casting helps us convert data safely while keeping its integrity intact.
  • Making Operations Work: Imagine trying to mix a glass of water with a cup of sugar. It just would not blend! Similarly, some operations can not work with different data types. Type casting makes these operations possible by making data types compatible.
  • Efficient Memory Use: Type casting and type conversion in Java help manage memory better. Sometimes, a larger data type might be used for a smaller value. This can waste memory. Type casting lets us use the right size for the right data.
  • Handling User Input: When we get input from users, it is usually in text form. But, we need numbers for calculations. Type casting helps convert this text into numbers for proper processing.
  • Better Programming Control: Java is a strongly-typed language, which means it is strict about data types. Type casting and type conversion in Java allow programmers to take control and ensure the right data type is used at the right time.

Types of Type Casting in Java

There are 13 different types of type conversion in Java. In this tutorial, we are only going to look at the two main types.

1. Widening Type Casting

Widening type casting is the process of converting a lower data type to a higher data type. It is also referred to as implicit conversion or casting down. This process is performed automatically and is safe, as there is no risk of data loss. This kind of type conversion and casting in Java happens when:

  • The target type is greater than the source type.
  • The two data types are compatible.

byte -> short -> char -> int -> long -> float -> double  (From left to right: Lower data type to Higher data type)

Syntax:

larger_data_type variable_name = smaller_data_type_variable;

2. Narrowing Type Casting

Narrowing type casting is the process of reducing a larger data type to a smaller one. Other names for this are casting up or explicit type casting in Java. It does not happen on its own. If we do not do this explicitly, we will get a compile-time error. The narrowing type casting is unsafe because data loss might occur due to the smaller range of allowed values of the lower data type. A cast operator helps in explicit casting.

double -> float -> long -> int -> char -> short -> byte  (From left to right: Higher data type to Lower data type)

Syntax:

larger_data_type variable_name = smaller_data_type_variable;

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Examples of Type Casting in Java

Here are some type casting in Java with example.

1. Converting Int to Double

class Main {

  public static void main(String[] args) {

    // create int type variable

    int num = 50;

    System.out.println("The integer value: " + num);

    // convert into double type

    double data = num;

    System.out.println("The double value: " + data);

  }

}

Output:

Integer value: 50

Double value: 50.0

2. Converting Double into an Int

class Main {

  public static void main(String[] args) {

    // create double type variable

    double num = 50.55;

    System.out.println("The double value: " + num);

    // convert into int type

    int data = (int)num;

    System.out.println("The integer value: " + data);

  }

}

Output:

Double value: 50.55

Integer value: 50

3. Converting Int to String

class Main {

  public static void main(String[] args) {

    // create int type variable

    int num = 50;

    System.out.println("The integer value is: " + num);

    // convert int to string type

    String data = String.valueOf(num);

    System.out.println("The string value is: " + data);

  }

}

Output:

Integer value: 50

String value: 50

4. Converting String to Int

class Main {

  public static void main(String[] args) {

    // create string type variable

    String data = "50";

    System.out.println("The string value is: " + data);

    // convert string variable to int

    int num = Integer.parseInt(data);

    System.out.println("The integer value is: " + num);

  }

}

Output

String value: 50

Integer value: 50

Choose The Right Software Development Program For You

This table compares various courses offered by Simplilearn, based on several key features and details. The table provides an overview of the courses' duration, skills you will learn, additional benefits, among other important factors, to help learners make an informed decision about which course best suits their needs.

Program Name Full Stack Java Developer Career Bootcamp Automation Testing Masters Program Post Graduate Program in Full Stack Web Development
GeoINAllNon-US
UniversitySimplilearnSimplilearnCaltech
Course Duration11 Months11 Months9 Months
Coding Experience RequiredBasic KnowledgeBasic KnowledgeBasic Knowledge
Skills You Will Learn15+ Skills Including Core Java, SQL, AWS, ReactJS, etc.Java, AWS, API Testing, TDD, etc.Java, DevOps, AWS, HTML5, CSS3, etc.
Additional BenefitsInterview Preparation
Exclusive Job Portal
200+ Hiring Partners
Structured Guidance
Learn From Experts
Hands-on Training
Caltech CTME Circle Membership
Learn 30+ Tools and Skills
25 CEUs from Caltech CTME
Cost$$$$$$$
Explore ProgramExplore ProgramExplore Program

Conclusion

Type casting is a powerful feature in Java that allows us to convert variables from one data type to another. Implicit type casting, also known as widening conversion, is done automatically by the compiler when there is no loss of data. Explicit type casting in Java, on the other hand, requires manual intervention and is used when there is a possibility of data loss. Understanding type casting is essential for writing efficient and error-free Java programs.

If you are looking to enhance your Java programming skills further, we would highly recommend you to check Simplilearn’s Java Certification Training. This course, in collaboration with Caltech CTME, can help you gain the right software development experience and skills and make you job-ready in no time.

If you have any questions or queries, feel free to post them in the comments section below. Our team will get back to you at the earliest.

FAQs

1. Is type casting in Java safe? 

Yes, type casting in Java is generally safe when done correctly and using the widening type casting, preventing data loss and ensuring proper compatibility between different data types.

2. How can I identify when a variable has been implicitly type casted?

Implicit type casting in variables can be identified when a variable of one data type is automatically converted to another during operations, ensuring compatibility. There will also be a conversion from a lower data type to a higher one.

3. Can I cast between unrelated object types in Java?

No, Java does not allow casting between unrelated object types. It is essential to maintain type compatibility for proper program execution.

4. How does type casting impact Java performance?

Type casting in Java impacts performance by potentially introducing overhead due to data conversion, affecting execution speed and memory usage.

5. Does Java do automatic type casting?

Yes, Java performs automatic type casting, also known as implicit type conversion, when converting data from a lower precision data type to a higher one.

6. What is an example of implicit type casting in Java?

An example of implicit type casting in Java is when you assign an integer value to a variable of a larger data type, like assigning an int to a double. This kind of type casting or type conversion also includes conversion from int to float or long. Generally, any lower data type, when converted into a higher data type, is an example of implicit type casting in Java.

About the Author

Akshay BadkarAkshay Badkar

Akshay is an experienced content marketer, passionate about education and technology. With a love for travel, photography, and cricket, he brings a unique perspective to the edtech industry. Through engaging articles, he shares insights, trends, and inspires readers to embrace transformative edtech.

View More

Find Full Stack Web Developer - MEAN Stack Master's Program in these cities

Mean Stack Developer Course in Atlanta
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.