tl;dr: Generics helps to avoid runtime exceptions such as ClassCastException and making your code more type-safe.
Let us try to answer why we need Genetics in Java?
In the typical project life cycle, around 20% of the total duration is devoted to the development phase and the initial release, with the remaining 80% being the maintenance phase. It's essential to recognize that if the product lacks a robust architecture, there is an increased likelihood that the code will become more error-prone as new features are introduced over time. Regardless of the circumstances, one universal truth remains: bugs are an integral part of the product life cycle.

Much time, effort, and resources are involved to ensure the code to production has the least amount of bugs.
| Stage | Who | Efforts |
|---|---|---|
| Development | Developers | Unit tests, code reviews, best practices. |
| Testing | QA Testers | Functional, integration, and regression testing. |
| Quality Assurance | QA Teams | Test plans, automated testing tools. |
| Project Management | Project Managers | Bug monitoring, critical issue prioritization. |
| DevOps | DevOps Engineers | Continuous Integration and Continuous Delivery (CI/CD) implementation. |
| SRE (Site Reliability Engineering) | SRE Teams | Ensuring system reliability and performance. |
| Information Security | Security Teams | Security audits, vulnerability assessments. |

Still there are some bugs that creep into the production unnoticed by all, and one such category of bugs is called "Runtime Exceptions".
Runtime exceptions are literally called human errors! Something that is the responsibility of the developer to take care of while designing and writing code.
Let's take a simple real-world example.
public class Calculator {
public static void main(String[] args) {
Calculator calculator = new Calculator();
double result1 = calculator.addNumbers(10, 11.2);
System.out.println("Result: " + result1);
double result2 = calculator.addNumbers("10", 11.2);
System.out.println("Result: " + result2);
}
public double addNumbers(Object num1, Object num2) {
double no1 = (double) num1;
double no2 = (double) num2;
return no1 + no2;
}
}
The above Java code illustrates the concept of runtime exceptions. The Calculator class. The method addNumbers(Object num1, Object num2) is designed to work with all kinds of data types.
result1 attempts to add the numbers 10 and 11.2, which is a valid operation. However, result2 tries to add the string "10" and the number 11.2. This action leads to a ClassCastException, a runtime exception.
The issue arises when the code tries to cast the string to a double, which is not allowed, resulting in a runtime error.
This code demonstrates the significance of handling data types correctly in software development to avoid runtime exceptions. Even with thorough testing and development practices, errors like this can occur if data types are not carefully managed.
It is important to make sure that project codes are robust enough to mitigate Runtime exceptions.
Some bugs are easy to spot because they cause issues during compilation. We call them 'compile-time bugs or errors.' When you write Java code using tools like Eclipse, IntelliJ, or others, these IDEs highlight problems for you. You'll see red flags in your Java files, signaling compilation errors that need fixing before your code can be built successfully.
We can see this when we make the addNumbers method signature as addNumbers(Number num1, Number num2)

How to make our code safe from ClassCastException?
Generics enhance code reliability by ensuring type safety and preventing ClassCastException errors. When implementing Generics in your project framework, developers are compelled to work with specific object types. Non-compliance results in compilation errors, making it quite challenging to introduce runtime exceptions.
Now let's re-write the above code with generics.

As you can see, we get two errors in the IDE when you change the code with Generic type argument T and type parameter as Double. Thus, bugs are detected during compilation and do not end up in production.
Reference: https://docs.oracle.com/javase/tutorial/java/generics/index.html
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!