JavaRush /Java Blog /Random EN /5 interesting and non-obvious things that will make Java ...
Андрей Пазюк
Level 111
Киев

5 interesting and non-obvious things that will make Java your favorite programming language

Published in the Random EN group
Your path to becoming a true expert in the world of programming is through complete trust in the Java language. It's used by millions of developers around the world, and today we'll show you five interesting and unobvious things that will make Java your favorite programming language. 5 interesting and non-obvious things that will make Java your favorite programming language - 11. Flexibility of interfaces In Java, it is possible to use interfaces as a contract for interaction between classes. But perhaps you didn't know that since Java 8, interfaces can be implemented using default methods. This allows you to add new methods to the interface without breaking the code that already implements it. This is especially useful when developing existing projects, where new functionality can be easily added.
interface Vehicle {
    void start();
    void stop();

    default void honk() {
        System.out.println("Beep beep!");
    }
}

class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car started.");
    }

    @Override
    public void stop() {
        System.out.println("Car stopped.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.start();
        car.stop();
        car.honk(); // Использование метода по умолчанию из интерфейса
    }
}
2. Exception Handling Java has a powerful exception handling system that helps manage errors during program execution. However, you might be surprised to learn that you can create your own exception types to reflect special situations in your code. This allows you to create more detailed and clear error messages, allowing them to be found and fixed faster.
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            // Бросаем исключение CustomException
            throw new CustomException("Something went wrong.");
        } catch (CustomException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}
3. Using Annotations Annotations are special labels that can be applied to classes, methods, or fields in Java. They provide additional information about your code and can be used for automatic documentation generation, static analysis, or even creating custom markers for your code. Annotations can be a very powerful tool for developers who want to reduce code repetition and automate certain aspects of development.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String value() default "";
}

public class Main {
    @MyAnnotation(value = "Example")
    public static void main(String[] args) {
        // Получаем аннотацию и выводим meaning
        MyAnnotation annotation = Main.class.getAnnotation(MyAnnotation.class);
        System.out.println("Annotation value: " + annotation.value());
    }
}
4. Enumerated Types Java has the ability to create enumerated types, which are a set of constant values. They allow you to write clear and safe code because the compiler checks that these types are used correctly at compile time. In addition, enum types can have their own methods and constructors, giving you more flexibility when working with them.
enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

public class Main {
    public static void main(String[] args) {
        Day today = Day.TUESDAY;
        System.out.println("Today is " + today);
    }
}
5. Lambda Expressions The introduction of lambda expressions in Java 8 gave developers the ability to write cleaner and more compact code. Lambda expressions allow you to pass functions as parameters to other functions, making it easier to work with lists, filter, and transform collections. They also improve code readability because functionality can be expressed in a few lines instead of long blocks of code.
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        // Применение лямбда-выражения для удвоения значений списка
        numbers.replaceAll(n -> n * 2);

        System.out.println(numbers); // Выводит: [2, 4, 6]
    }
}
These five interesting and unobvious aspects of the Java language will unlock your potential as a developer and help make it your favorite programming language. Gain knowledge, experiment and create exciting projects with this powerful language! PS The text, code and photos for the article were generated using AI. If you liked this format, then like, write comments and I will post more similar content and of better quality.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION