Java Programs and Spring Boot
Examples
WAP to implement the following new features in Java
import java.util.function.Predicate;
@FunctionalInterface
interface StringChecker {
boolean check(String s);
static void printInfo() {
System.out.println("Static Method in Functional Interface");
}
default void printDefault() {
System.out.println("Default Method in Functional Interface");
}
}
public class JavaFeaturesDemo {
public static void main(String[] args) {
// (a) Functional Interface + (b) Lambda Expression
StringChecker isEmpty = (s) -> s.isEmpty();
System.out.println("Is empty: " + isEmpty.check(""));
// (c) Method Reference
Predicate<String> isEmptyRef = String::isEmpty;
System.out.println("Using Method Reference: " + isEmptyRef.test(""));
// (d) Default and Static Method in Interface
isEmpty.printDefault();
StringChecker.printInfo();
// (e) Inner Class
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
class Outer {
class Inner {
void display() {
System.out.println("This is an Inner Class");
}
}
}
Different types of annotations
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.List;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String value() default "Default";
}
class Demo {
@Deprecated
public void oldMethod() {
System.out.println("Deprecated method");
}
@SuppressWarnings("unchecked")
public void warningMethod() {
List rawList = List.of("Java", "Annotations");
List<String> stringList = rawList;
System.out.println(stringList);
}
@MyAnnotation(value = "Custom Annotation")
public void customAnnotatedMethod() {
System.out.println("Custom annotated method");
}
}
public class AnnotationExample {
public static void main(String[] args) throws Exception {
Demo demo = new Demo();
demo.oldMethod();
demo.warningMethod();
demo.customAnnotatedMethod();
Method method = Demo.class.getMethod("customAnnotatedMethod");
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Annotation Value: " + annotation.value());
}
}
}