Crazy Java features you didn't knew ๐Ÿ’ป

Crazy Java features you didn't knew ๐Ÿ’ป

ยท

2 min read

Java is a robust,machine-independent language that is used by various organizations. As of today, Java is the most widely used language in the world(by the time you are reading this, python could top the chart, with very fierce competition). Over the years(27 to be precise) java has updated into many different versions latest one being JDK21. So here are the features that would enhance your Java programming.

  • Records:

    Records have been around since JDK14, they are an alternative to class. Let me show you,
    class Employee(){

    String name; int salary; int age; Employee(String name,int salary,int age){this.name=name ....//You know the usual stuff}

    }

    Now with a record,
    record Employee(String name,int salary,int age){}

    Voila!. That's it. Done. This automatically sets up encapsulation within Employee, this is a very useful feature, especially while solving DSA problems as you know Java does not support Pair, so instead of going through whole class shenanigans just simply use record. Read more about records

  • Lambda Expressions.
    Consider the same Employee class, Now if I add 3 employees to an ArrayList and ask you to sort it by the salary, how would you do it? Normally one would override the comparator class and then write a function inside it and ... you know the rest. But this makes the code look like it was written in the early 2000s. Now let me give you the magic line
    Collections.sort(list,(a,b)->a.salary-b.salary)

    That's all folks! This here is a lambda expression. The lambda expression (a, b) -> a.salary - b.salary is used to compare two Employee objects, a and b, based on their salary attribute. Lambda expressions were added in Java8 and it significantly changed the experience.

  • public static void main......

    If I ask you to write a java program to print HelloWorld , how would you write it
    class Hello{ public static void main(String[] args){ System.out.println("HelloWorld"); } }
    Now in JDK21 you could simply write
    void main(){System.out.println("HelloWorld");}

    I know I know you'll be like my whole life was a lie, etc., But this totally contradicts object-oriented programming, how would inheritance abstraction and all will be achieved by this... what the ... how the . Mixed feelings? Well this is new and its still not stable , it uses concepts like unnamed classes and instance main methods, but I would suggest you to explore this feature on your own.

ย