DEV Community

DEV Community

Emil Ossola

Posted on Jun 1, 2023

How to Avoid Unchecked Casts in Java Programs

Unchecked cast refers to the process of converting a variable of one data type to another data type without checks by the Java compiler.

This operation is unchecked because the compiler does not verify if the operation is valid or safe. Unchecked casts can lead to runtime errors, such as ClassCastException, when the program tries to assign an object to a variable of an incompatible type.

Hence, it is important to avoid unchecked casts in Java programs to prevent potential errors and ensure the program's reliability.

Image description

Consequences of Unchecked Casts

In Java programs, unchecked casts can lead to several issues. The most common problem is a ClassCastException at runtime, which occurs when we try to cast an object to a wrong type. This can cause the program to crash or behave unexpectedly.

Unchecked casts also violate the type safety of the Java language, which can lead to bugs that are difficult to detect and debug. Additionally, unchecked casts can make the code less readable and maintainable, as they hide the true type of objects and dependencies between components.

Therefore, it is important to avoid unchecked casts and use other mechanisms, such as generics or polymorphism, to ensure type safety and code quality in Java programs.

Image description

How Unchecked Casts Occur

Unchecked casts in Java programs occur when an object of one type is assigned to a reference of another type without proper type checking. This can happen when a programmer assumes that a reference to a superclass is actually a reference to its subclass and tries to cast it into that subclass. If the assumption is incorrect, the cast will result in a ClassCastException at runtime.

Unchecked casts can also occur when dealing with raw types, which are generic types without any type parameters specified. In such cases, the compiler cannot perform type checking and the programmer must ensure that the proper type conversions are made. Failing to do so can result in unchecked casts and potential runtime errors.

Why unchecked casts are problematic

In Java, unchecked casts allow a programmer to cast any object reference to any other reference type without providing any type information at compile-time. While this flexibility may seem useful, it can lead to serious run-time errors. If the object being casted is not actually of the type specified, a ClassCastException will occur at run-time.

Unchecked casts can cause difficult-to-debug errors in large and complex codebases, as it may not be immediately clear where the error originated. Additionally, unchecked casts can undermine Java's type system, creating code that is harder to read, maintain, and reason about. As a result, avoiding unchecked casts should be a priority when writing Java programs.

Examples of Unchecked Casts in Java

Unchecked casts are a common source of Java program errors. Here are some examples of unchecked casts:

This cast statement above can result in a class cast exception if the object referred to by obj is not a List.

In this case, the cast could fail at runtime if the array contains objects of a type other than String.

Finally, this cast could fail if the object referred to by obj is not a Map.

Using Generics to Avoid Unchecked Casts in Java

In Java, Generics is a powerful feature that allows you to write classes and methods that are parameterized by one or more types. Generics are a way of making your code more type-safe and reusable. With generics, you can define classes and methods that work on a variety of types, without having to write separate code for each type.

Using generics in Java programs has several advantages. It enables type safety at compile-time, which can prevent ClassCastException errors at runtime. With generics, the compiler can detect type mismatches and prevent them from happening, which leads to more robust and reliable code. It also allows for code reuse without sacrificing type safety and improve performance by avoiding unnecessary casting and allowing for more efficient code generation.

Generics allow Java developers to create classes and methods that can work with different data types. For example, a List can be defined to hold any type of object using generics. Here's an example:

In this example, we create a List that holds String objects. We can add String objects to the list and iterate over them using a for-each loop. The use of generics allows us to ensure type safety and avoid unchecked casts. Another example is the Map interface, which can be used to map keys to values of any data type using generics.

Using the instanceof operator to Avoid Unchecked Casts in Java

The instanceof operator is a built-in operator in Java that is used to check whether an object is an instance of a particular class or interface. The operator returns a boolean value - true if the object is an instance of the specified class or interface, and false otherwise.

The instanceof operator is defined as follows:

where object is the object that is being checked, and class/interface is the class or interface that is being tested against.

The instanceof operator can be useful in situations where we need to perform different operations based on the type of an object. It provides a way to check the type of an object at runtime, which can help prevent errors that can occur when performing unchecked casts.

Here are some examples of using the instanceof operator:

In this example, we use the instanceof operator to check whether the object obj is an instance of the String class. If it is, we perform an explicit cast to convert the object to a String and call the toUpperCase() method on it.

In this example, we use the instanceof operator to check whether the List object passed as a parameter is an instance of the ArrayList or LinkedList classes. If it is, we perform an explicit cast to convert the List to the appropriate class and perform different operations on it depending on its type.

Overall, using the instanceof operator can help us write more robust and flexible code. However, it should be used judiciously as it can also make code harder to read and understand.

Using Polymorphism to Avoid Unchecked Casts in Java

Polymorphism is a fundamental concept in object-oriented programming. It refers to the ability of an object or method to take on multiple forms. It allows us to write code that can work with objects of different classes as long as they inherit from a common superclass or implement a common interface. This helps to reduce code duplication and makes our programs more modular and extensible.

Some of the advantages of using polymorphism are:

  • Code reusability: We can write code that can work with multiple objects without having to rewrite it for each specific class.
  • Flexibility: Polymorphism allows us to write code that can adapt to different types of objects at runtime.
  • Ease of maintenance: By using polymorphism, changes made to a superclass or interface are automatically propagated to all its subclasses.

Here are a few examples of how you can use polymorphism to avoid unchecked casts in Java:

Example 1: Shape Hierarchy

In this example, the abstract class Shape defines the common behavior draw(), which is implemented by the concrete classes Circle and Rectangle. By using the Shape reference type, we can invoke the draw() method on different objects without the need for unchecked casts.

Example 2: Polymorphic Method Parameter

In this example, the makeAnimalSound() method accepts an Animal parameter. We can pass different Animal objects, such as Dog or Cat, without the need for unchecked casts. The appropriate implementation of the makeSound() method will be invoked based on the dynamic type of the object.

By utilizing polymorphism in these examples, we achieve type safety and avoid unchecked casts, allowing for cleaner and more flexible code.

Tips to Avoid Unchecked Casts in Java Programs

Unchecked casts in Java programs can introduce runtime errors and compromise type safety. Fortunately, there are several techniques and best practices you can employ to avoid unchecked casts and ensure a more robust codebase. Here are some effective tips to help you write Java programs that are type-safe and free from unchecked cast exceptions.

  • Use generic classes, interfaces, and methods to ensure that your code handles compatible types without relying on casting.
  • Embrace polymorphism by utilizing abstract classes and interfaces, define common behavior and interact with objects through their common type.
  • Check the type of an object using the instanceof operator. This allows you to verify that an object is of the expected type before proceeding with the cast.
  • Favor composition over inheritance, where classes contain references to other classes as instance variables.
  • Familiarize yourself with design patterns that promote type safety and avoid unchecked casts. Patterns such as Factory Method, Builder, and Strategy provide alternative approaches to object creation and behavior, often eliminating the need for explicit casting.
  • Clearly define the contracts and preconditions for your methods. A well-defined contract helps ensure that the method is called with appropriate types, improving overall code safety.
  • Refactor your code and improve its overall design. Look for opportunities to apply the aforementioned tips, such as utilizing generics, polymorphism, or design patterns.

Unchecked casts in Java programs can introduce runtime errors and undermine type safety. By adopting practices like using generics, leveraging polymorphism, checking types with instanceof, favoring composition over inheritance, reviewing design patterns, employing design by contract, and improving code design, you can avoid unchecked casts and enhance the robustness of your Java programs. Prioritizing type safety will result in more reliable code and a smoother development process.

Lightly IDE as a Programming Learning Platform

So, you want to learn a new programming language? Don't worry, it's not like climbing Mount Everest. With Lightly IDE, you'll feel like a coding pro in no time. With Lightly IDE , you don't need to be a coding wizard to start programming.

Uploading image

One of its standout features is its intuitive design, which makes it easy to use even if you're a technologically challenged unicorn. With just a few clicks, you can become a programming wizard in Lightly IDE. It's like magic, but with less wands and more code.

If you're looking to dip your toes into the world of programming or just want to pretend like you know what you're doing, Lightly IDE's online Java compiler is the perfect place to start. It's like a playground for programming geniuses in the making! Even if you're a total newbie, this platform will make you feel like a coding superstar in no time.

Read more: How to Avoid Unchecked Casts in Java Programs

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

innazh profile image

Superset embedded dashboard setup: templ components, golang backend

Inna - May 15

ayofar profile image

Beginner here

ayofar - May 15

kiolk profile image

Developer diary #10. Lost contributions

Kiolk - May 15

iambstha profile image

@Controller vs. @RestController

Bishal Shrestha - May 15

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Generics unchecked assignment

Report post to moderator

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Java 8 Features - Complete Tutorial

Lambda Expressions

  • Lambda Expression in Java
  • Java - Lambda Expressions Parameters
  • Java Lambda Expression with Collections
  • Java - Lambda Expression Variable Capturing with Examples
  • How to Create Thread using Lambda Expressions in Java?
  • Serialization of Lambda Expression in Java
  • Block Lambda Expressions in Java
  • Match Lambdas to Interfaces in Java
  • Converting ArrayList to HashMap in Java 8 using a Lambda Expression
  • Check if a String Contains Only Alphabets in Java Using Lambda Expression
  • Remove elements from a List that satisfy given predicate in Java

Functional Interfaces

  • Functional Interfaces in Java
  • Java 8 | Consumer Interface in Java with Examples
  • Java 8 | BiConsumer Interface in Java with Examples
  • Java 8 Predicate with Examples
  • Function Interface in Java with Examples
  • Supplier Interface in Java with Examples

Method Reference

  • Method References in Java with examples
  • Converting ArrayList to HashMap using Method Reference in Java 8
  • Java 8 Stream Tutorial
  • Difference Between Streams and Collections in Java
  • Implement Filter Function using Reduce in Java 8 Streams
  • Java Stream API – Filters
  • Parallel vs Sequential Stream in Java
  • Functional Programming in Java 8+ using the Stream API with Example
  • Intermediate Methods of Stream in Java
  • Difference Between map() And flatMap() In Java Stream
  • Array to Stream in Java
  • 10 Ways to Create a Stream in Java

Java Stream Programs

  • Program to convert a Map to a Stream in Java
  • Program to convert Boxed Array to Stream in Java
  • Program to convert Primitive Array to Stream in Java
  • Program to convert a Set to Stream in Java using Generics
  • Program to Convert List to Stream in Java
  • Program to Convert Stream to an Array in Java
  • How to get Slice of a Stream in Java
  • Flattening Nested Collections in Java
  • How to convert a Stream into a Map in Java
  • Find the first element of a Stream in Java

Java Stream Methods

  • Stream forEach() method in Java with examples
  • Stream forEachOrdered() method in Java with examples
  • foreach() loop vs Stream foreach() vs Parallel Stream foreach()
  • Stream of() method in Java
  • Java Stream findAny() with examples
  • Stream anyMatch() in Java with examples
  • Stream allMatch() in Java with examples
  • Stream filter() in Java with examples
  • Stream sorted (Comparator comparator) method in Java
  • Stream sorted() in Java

Comparable and Comparator

  • Comparable vs Comparator in Java
  • Comparator Interface in Java with Examples
  • Why to Use Comparator Interface Rather than Comparable Interface in Java?
  • Sort an Array of Triplet using Java Comparable and Comparator
  • Java Program to Sort LinkedList using Comparable
  • How to Sort HashSet Elements using Comparable Interface in Java?
  • Sort LinkedHashMap by Values using Comparable Interface in Java
  • Sort LinkedHashMap by Keys using Comparable Interface in Java
  • How to Sort LinkedHashSet Elements using Comparable Interface in Java?

Optional Class

Java 8 optional class.

  • Optional ofNullable() method in Java with examples
  • Optional orElse() method in Java with examples
  • Optional ifPresentOrElse() method in Java with examples
  • Optional orElseGet() method in Java with examples
  • Optional filter() method in Java with examples
  • Optional empty() method in Java with examples
  • Optional hashCode() method in Java with examples
  • Optional toString() method in Java with examples
  • Optional equals() method in Java with Examples

Date/Time API

  • New Date-Time API in Java 8
  • java.time.LocalDate Class in Java
  • java.time.LocalTime Class in Java
  • java.time.LocalDateTime Class in Java
  • java.time.MonthDay Class in Java
  • java.time.OffsetTime Class in Java
  • java.time.OffsetDateTime Class in Java
  • java.time.Clock Class in Java
  • java.time.ZonedDateTime Class in Java
  • java.time.ZoneId Class in Java

Every Java Programmer is familiar with NullPointerException . It can crash your code. And it is very hard to avoid it without using too many null checks. So, to overcome this, Java 8 has introduced a new class Optional in java.util package . It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.

To avoid abnormal termination, we use the Optional class. In the following example, we are using Optional. So, our program can execute without crashing.

The above program using Optional Class

Optional is a container object which may or may not contain a non-null value. You must import java.util package to use this class. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() which returns a default value if the value is not present, and ifPresent() which executes a block of code if the value is present. This is a value-based class, i.e their instances are : 

  • Final and immutable (though may contain references to mutable objects).
  • Considered equal solely based on equals(), not based on reference equality(==).
  • Do not have accessible constructors.

Static Methods: Static methods are the methods in Java that can be called without creating an object of the class. They are referenced by the class name itself or reference to the object of that class. 

Syntax : 

Important Points: Since Static methods belong to the class, they can be called to without creating the object of the class. Below given are some important points regarding Static Methods : 

  • Static method(s) are associated with the class in which they reside i.e. they can be called even without creating an instance of the class.
  • They are designed with the aim to be shared among all objects created from the same class.
  • Static methods can not be overridden. But can be overloaded since they are resolved using static binding by the compiler at compile time.

The following table shows the list of Static Methods provided by Optional Class : 

unchecked assignment 'java.util.optional'

Instance Methods: Instance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class within which it is defined. 

Important Points: Instance Methods can be called within the same class in which they reside or from the different classes defined either in the same package or other packages depending on the access type provided to the desired instance method. Below given are some important points regarding Instance Methods : 

  • Instance method(s) belong to the Object of the class, not to the class i.e. they can be called after creating the Object of the class.
  • Every individual object created from the class has its own copy of the instance method(s) of that class.
  • They can be overridden since they are resolved using dynamic binding at run time.

The following table shows the list of Instance Methods provided by the Optional Class : 

unchecked assignment 'java.util.optional'

Concrete Methods: A concrete method means, the method has a complete definition but can be overridden in the inherited class. If we make this method final , then it can not be overridden. Declaring method or class “final” means its implementation is complete. It is compulsory to override abstract methods. Concrete Methods can be overridden in the inherited classes if they are not final. The following table shows the list of Concrete Methods provided by the Optional Class :

unchecked assignment 'java.util.optional'

Below given are some examples :

Example 1 :  

Example 2 :  

Please Login to comment...

Improve your coding skills with practice.

 alt=

What kind of Experience do you want to share?

  • No Frames
  • All Classes

Uses of Class java.util.Optional

Uses of optional in java.util, uses of optional in java.util.stream.

Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2024, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .

Scripting on this page tracks web page traffic, but does not change the content in any way.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unchecked assignment: 'java.util.List' to 'java.util.List<ua.lv.hoy.entity.Customer>' #184

@ghost

ghost commented Feb 8, 2018

The text was updated successfully, but these errors were encountered:

@halyafg

halyafg commented Feb 10, 2018

Sorry, something went wrong.

ghost commented Feb 26, 2018

Halyafg commented feb 27, 2018.

@halyafg

No branches or pull requests

@halyafg

IMAGES

  1. Checked and Unchecked Exception in Java

    unchecked assignment 'java.util.optional'

  2. Checked and Unchecked Exceptions in Java

    unchecked assignment 'java.util.optional'

  3. API java.util.Optional

    unchecked assignment 'java.util.optional'

  4. Java 8 Optional Class

    unchecked assignment 'java.util.optional'

  5. Checked vs Unchecked Exceptions in Java

    unchecked assignment 'java.util.optional'

  6. Checked and Unchecked Exceptions in Java

    unchecked assignment 'java.util.optional'

VIDEO

  1. Demo qua Assignment Java 3

  2. Checked Exception & Unchecked Exception

  3. #40 Working with Unchecked Exception in Java using Eclipse

  4. Checked and Unchecked Exceptions in Java Part 2

  5. Optional assignment for extra point (mfu)

  6. How to handle Checked vs Unchecked Exceptions in Java #java #javaprogramming

COMMENTS

  1. java

    And this line: Map<Integer, String> map = a.getMap(); gets you a warning now: "Unchecked assignment: 'java.util.Map to java.util.Map<java.lang.Integer, java.lang.String>'. Even though the signature of getMap is totally independent of T, and the code is unambiguous regarding the types the Map contains. I know that I can get rid of the warning by ...

  2. generics

    2. I'm using the following code to find a one-dimensional list of unique objects in an n-dimensional list (credits to someone on StackOverflow a while ago for the approach): public static <T> List<T> getUniqueObjectsInArray (List<T> array) { Integer dimension = getDimensions (array); return getUniqueObjectsInArray (array, dimension); } private ...

  3. Java Warning "unchecked conversion"

    5.2. Checking Type Conversion Before Using the Raw Type Collection. The warning message " unchecked conversion " implies that we should check the conversion before the assignment. To check the type conversion, we can go through the raw type collection and cast every element to our parameterized type.

  4. Optional (Java SE 17 & JDK 17)

    Type Parameters: T - the type of value. public final class Optional<T> extends Object. A container object which may or may not contain a non- null value. If a value is present, isPresent() returns true. If no value is present, the object is considered empty and isPresent() returns false . Additional methods that depend on the presence or ...

  5. Optional (Java Platform SE 8 )

    Class Optional<T>. A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent ...

  6. Uses of Class java.util.Optional (Java SE 17 & JDK 17)

    Uses of Class java.util.Optional. Provides classes that are fundamental to the design of the Java programming language. Classes and interfaces to represent nominal descriptors for run-time entities such as classes or method handles, and classfile entities such as constant pool entries or invokedynamic call sites.

  7. Java Warning "Unchecked Cast"

    The "unchecked cast" is a compile-time warning . Simply put, we'll see this warning when casting a raw type to a parameterized type without type checking. An example can explain it straightforwardly. Let's say we have a simple method to return a raw type Map: public class UncheckedCast {. public static Map getRawMap() {.

  8. Taming a Silly Generic Warning

    Unchecked assignment: java.util.List to java.util.List<String> Unfortunately, there's no way to fix that problem. I've tried adding <String>before the dot and after, but neither works.

  9. How to Avoid Unchecked Casts in Java Programs

    Unchecked cast refers to the process of converting a variable of one data type to another data type without checks by the Java compiler. This operation is unchecked because the compiler does not verify if the operation is valid or safe. Unchecked casts can lead to runtime errors, such as ClassCastException, when the program tries to assign an ...

  10. Generics unchecked assignment (Java in General forum at Coderanch)

    Optional 'thank-you' note: Send. I'm starting to apply generics to some code. In this example: ... The most generic way of using generics is. This causes "Unchecked assignment: 'java.util.Set' to 'java.util.Collection <? extends java.lang.Object>'". Can this warning be resolved without modifying the classroom class? Rob Spoor. Sheriff Posts ...

  11. Java 8 Optional Class

    So, to overcome this, Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.

  12. Checked and Unchecked Exceptions in Java

    Some common checked exceptions in Java are IOException, SQLException and ParseException. The Exception class is the superclass of checked exceptions, so we can create a custom checked exception by extending Exception: public IncorrectFileNameException(String errorMessage) {. super (errorMessage); 3.

  13. java

    MacBook:Homework Brienna$ javac Orders.java -Xlint:unchecked Orders.java:152: warning: [unchecked] unchecked cast orders = (ArrayList<Vehicle>) in.readObject(); ^ required: ArrayList<Vehicle> found: Object 1 warning I always try to improve my code instead of ignoring or suppressing warnings. In this case, I have come up with a solution, but I'm ...

  14. Uses of Class java.util.Optional (Java Platform SE 8 )

    java.util.Optional. Packages that use Optional ; Package Description; java.util: Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).

  15. java

    Java Generics, how to avoid unchecked assignment warning when using class hierarchy? Intellij is giving me the warning below. Not sure how to resolve it, or even if I need to resolve it. The warning details says it only applies to JDK 5, and I am using 6. I am wondering if I need to respond to this, and if so, how? Method call causing warning

  16. How to Avoid Unchecked Casts in Java Programs

    Jun 1, 2023. Unchecked cast refers to the process of converting a variable of one data type to another data type without checks by the Java compiler. This operation is unchecked because the ...

  17. How do I address unchecked cast warnings?

    An unchecked cast warning in Java occurs when the compiler cannot verify that a cast is safe at compile time. This can happen when you are casting an object to a type that is not a supertype or subtype of the object's actual type. To address an unchecked cast warning, you can either suppress the warning using the @SuppressWarnings("unchecked ...

  18. Question regarding "Unchecked call" warning. : r/learnjava

    Warning:(20, 39) Unchecked assignment: 'java.util.List' to 'java.util.List<com.flowplanner.persistence.Transaction>'. Reason: 'new CsvToBeanBuilder(fr).withType(Transaction.class).build()' has raw type, so result of parse is erased. The code in question is intended to import a simple CSV to java beans. The pojo field names map perfectly to the ...

  19. Avoid unchecked assignment in a map with multiple value types?

    Of course that's an unchecked assignment. You seem to be implementing a heterogeneous map. Java (and any other strongly-typed language) has no way to express the value type of your map in a statically-type-safe way. That is because the element types are only known at runtime.

  20. android

    That's because you're doing an unchecked cast. Actually, you're doing both a checked and an unchecked cast there. (List) filterResults.values is a checked cast. This means that the Java compiler will insert a checkcast instruction into the bytecode to ensure that filterResults.values (an Object) really is an instance of List.

  21. Unchecked assignment: 'java.util.List' to 'java.util.List<ua.lv.hoy

    Saved searches Use saved searches to filter your results more quickly