in interfaces and methods in Java has added new tools to make coding easier. These tools, called interfaces and methods, help you write cleaner and faster code. This article breaks down the basics of these new features. In java, interfaces and methods is very important topic. Let’s dive into this!
What Are New Interfaces in Java?
An interface is like a list of rules for writing code. Java’s new interfaces help you do things like working with data, handling tasks, and using shorter code.
Types of interfaces and methods in java:
II. New Interfaces in Java
1. Functional Interfaces
Java added functional interfaces in Java 8. These help you write less code and keep it simple. Here are a few important ones:
- Consumer: Takes something and uses it, but doesn’t return anything.
- Supplier: Gives something back but doesn’t need any input.
- Predicate: Checks if something is true or false.
- Function: Takes one thing and gives back another.
These interfaces save you time and make your code easier to read. Run the below code!
import java.util.function.Consumer; import java.util.function.Supplier; import java.util.function.Predicate; import java.util.function.Function; public class FunctionalInterfaceExample { public static void main(String[] args) { // Consumer Example - Takes a value and performs an action Consumer<String> printMessage = message -> System.out.println("Message: " + message); printMessage.accept("Hello, Java!"); // Supplier Example - Supplies a value when called Supplier<Double> randomNumber = () -> Math.random(); System.out.println("Random Number: " + randomNumber.get()); // Predicate Example - Checks a condition and returns true/false Predicate<Integer> isEven = number -> number % 2 == 0; System.out.println("Is 4 even? " + isEven.test(4)); // Function Example - Transforms a value Function<String, Integer> stringLength = String::length; System.out.println("Length of 'Java': " + stringLength.apply("Java")); } }
2. Stream API Interfaces
The Stream
API lets you work with groups of data, like lists. You can filter, sort, or change data with it.
- Stream: Helps work with lists of data.
- IntStream, LongStream, DoubleStream: Special types for numbers. They make your code faster.
With these, your code is cleaner and more flexible. Run the below code!
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamExample { public static void main(String[] args) { // List of integers List<Integer> numbers = Arrays.asList(3, 7, 8, 1, 9, 10, 15, 5, 2); // Example 1: Filtering even numbers List<Integer> evenNumbers = numbers.stream() // Convert list to stream .filter(n -> n % 2 == 0) // Filter even numbers .collect(Collectors.toList()); // Collect result into a list System.out.println("Even numbers: " + evenNumbers); // Example 2: Mapping - square each number List<Integer> squares = numbers.stream() .map(n -> n * n) // Map each element to its square .collect(Collectors.toList()); System.out.println("Squares: " + squares); // Example 3: Reducing - sum of all numbers int sum = numbers.stream() .reduce(0, Integer::sum); // Sum up all elements System.out.println("Sum of all numbers: " + sum); // Example 4: Chaining multiple operations List<Integer> processedNumbers = numbers.stream() .filter(n -> n % 2 != 0) // Filter odd numbers .map(n -> n * n) // Square them .collect(Collectors.toList()); System.out.println("Odd numbers squared: " + processedNumbers); } }
3. CompletableFuture for Async Tasks
Java added tools to handle tasks that don’t run in order. This is called async (or asynchronous) programming.
- CompletableFuture: Handles tasks that don’t have to run one after another.
- CompletionStage: Links tasks together in steps.
These tools help you create programs that run faster and handle many things at once. Run the below code!
// CompletableFuture helps manage asynchronous tasks. // Here’s an example of running a task asynchronously. import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureExample { public static void main(String[] args) throws ExecutionException, InterruptedException { // Running a task asynchronously CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); // Simulating a long task } catch (InterruptedException e) { e.printStackTrace(); } return "Task completed!"; }); // Getting the result System.out.println("Result: " + future.get()); // Will print after task completes } }
4. Optional Interface
The Optional
interface helps you handle values that might be missing. It protects you from errors when a value is not there.
- Optional: Checks if a value is present. If it’s not, you can skip it safely.
Using Optional
prevents errors and keeps your code safe. Run the below code!
// Optional allows handling potential null values safely. // Here’s an example with ifPresentOrElse, or, and stream methods. import java.util.Optional; public class OptionalExample { public static void main(String[] args) { Optional<String> optionalValue = Optional.ofNullable(null); // ifPresentOrElse - Takes action if value is present, otherwise does something else optionalValue.ifPresentOrElse( value -> System.out.println("Value is: " + value), () -> System.out.println("No value present") ); // or - Provides an alternative if value is missing String result = optionalValue.or(() -> Optional.of("Default Value")).get(); System.out.println("Result: " + result); // stream - Turns Optional into a Stream optionalValue.stream().forEach(System.out::println); } }
II. New Methods in Java
Java added some new methods that save time. They’re useful for working with text and collections of data. this methods is very important concept in java.
1. String Methods
Java’s new String
methods make text easier to manage:
isBlank()
: Checks if a text is empty.lines()
: Splits text into lines.repeat(int count)
: Repeats text a set number of times.
These make handling text much simpler. Run the below code!
// Java introduced new methods for working with strings. // Here’s an example using isBlank, lines, and repeat. public class StringMethodsExample { public static void main(String[] args) { String text = " "; // isBlank - Checks if string is empty or only whitespace System.out.println("Is blank? " + text.isBlank()); // true // lines - Splits text into lines String multiLineText = "Java\nPython\nJavaScript"; multiLineText.lines().forEach(System.out::println); // repeat - Repeats the string String repeatedText = "Hi! ".repeat(3); System.out.println(repeatedText); // Hi! Hi! Hi! } }
2. Collection Methods
Java 9 added easy ways to create lists, sets, and maps with List.of()
, Set.of()
, and Map.of()
:
// Java 9 introduced List.of, Set.of, and Map.of for creating collections easily. // Here’s an example. import java.util.List; import java.util.Set; import java.util.Map; public class CollectionFactoryMethodsExample { public static void main(String[] args) { // List.of - Creates an unmodifiable list List<String> languages = List.of("Java", "Python", "C++"); System.out.println("Languages: " + languages); // Set.of - Creates an unmodifiable set Set<Integer> numbers = Set.of(1, 2, 3); System.out.println("Numbers: " + numbers); // Map.of - Creates an unmodifiable map Map<String, Integer> ageMap = Map.of("Alice", 30, "Bob", 25); System.out.println("Age Map: " + ageMap); } }
With these, you can create lists quickly without long code. Run the above code!
3. Stream Methods
Java also added some new stream methods:
takeWhile(Predicate)
: Takes items as long as they match a rule.dropWhile(Predicate)
: Drops items until they match a rule.ofNullable()
: Turns a value or null into a stream.
These let you handle data more smoothly. Run the below code!
// Java added new methods to Stream, like takeWhile, dropWhile, and ofNullable. // Here’s how to use them. import java.util.List; import java.util.stream.Stream; public class StreamNewMethodsExample { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); // takeWhile - Takes items as long as the condition is true numbers.stream().takeWhile(n -> n < 4).forEach(System.out::println); // 1, 2, 3 // dropWhile - Skips items until the condition becomes false numbers.stream().dropWhile(n -> n < 4).forEach(System.out::println); // 4, 5, 6 // ofNullable - Creates a stream from a nullable value Stream<String> stream = Stream.ofNullable(null); System.out.println("Stream is empty: " + stream.count()); // 0 } }
4. Optional Methods
The Optional
class has new methods to make it easier to handle values that might be missing:
ifPresentOrElse()
: Does one thing if a value is there and another if it’s not.or()
: Uses a different value if the current one is missing.stream()
: Turns anOptional
into aStream
.
These methods keep your code flexible and safe. Run the below code!
// Java’s Optional class includes new methods like ifPresentOrElse, or, and stream. // Here’s an example of these in action. import java.util.Optional; public class OptionalNewMethodsExample { public static void main(String[] args) { Optional<String> optionalValue = Optional.ofNullable("Hello"); // ifPresentOrElse - Performs an action if value is present, otherwise does something else optionalValue.ifPresentOrElse( value -> System.out.println("Value: " + value), () -> System.out.println("No value present") ); // or - Provides an alternative if the original value is missing String result = optionalValue.or(() -> Optional.of("Fallback Value")).get(); System.out.println("Result: " + result); // stream - Converts Optional to a Stream optionalValue.stream().forEach(System.out::println); } }
Example Code with New Java Tools
Here’s some simple code that shows these new Java tools in action:
let’s see the java interfaces and methods code:
import java.util.List; import java.util.Optional; public class JavaNewFeaturesDemo { public static void main(String[] args) { Optional<String> optionalValue = Optional.ofNullable("Hello, Java!"); optionalValue.ifPresentOrElse( value -> System.out.println("Value is: " + value), () -> System.out.println("No value") ); List<Integer> numbers = List.of(1, 2, 3, 4, 5); numbers.stream().takeWhile(n -> n <= 3).forEach(System.out::println); String text = "Java\nPython\nJavaScript"; text.lines().forEach(System.out::println); } }
This example shows how Optional
, Stream
, and String
methods work together to make code simple and clear.
Tips for Using These New Features
- Use Optional Wisely: Use
Optional
when you’re not sure if a value will be there. - Create Collections Fast:
List.of()
andSet.of()
make it easy to set up lists and sets. - Use Streams for Clean Code: Streams let you handle data quickly and clearly.
Beginner Project: Simple Task Manager using Java Interfaces and Methods
Project Description:
Create a simple console-based Task Manager that allows the user to add tasks, view tasks, remove tasks, and mark tasks as completed. The program will use Java 8 features such as Optional
, Stream
, and functional interfaces to manage tasks efficiently.
Steps:
- Create a
Task
class to store the task description and completion status. - Use a
List
to store all tasks. - Implement functional interfaces such as
Consumer
to display tasks andPredicate
to check the completion status. - Use
Stream
methods to filter, sort, and process the tasks. - Use
Optional
to handle tasks that may not exist (e.g., task not found).
Let's Try this project! click here
Interview Questions
1. Company: Zoho
Question: How does the use of functional interfaces improve the readability and maintainability of code in Java? Can you give examples of commonly used functional interfaces in Java?
Answer: Functional interfaces like Predicate
, Consumer
, Supplier
, and Function
improve readability by allowing concise lambda expressions, which reduce boilerplate code and promote clean, maintainable design.
2. Company: Infosys
Question: Can you explain how Java Streams differ from traditional loops in terms of performance and readability? What advantages does using Stream methods bring to the code?
Answer: Unlike traditional loops, Streams offer a declarative approach, allowing chaining with filter
, map
, and reduce
. They improve readability and, when suitable, enable parallel processing for performance gains.
3. Company: TCS
Question: How does the Optional
class in Java help avoid NullPointerException
? What are some best practices for using Optional
effectively?
Answer: Optional
prevents NullPointerException
by handling values explicitly, promoting readable, safe code. Use it for return types, avoid it in fields, and rely on ifPresent
or orElse
for null handling.
4. Company: Capgemini
Question: Can you explain the difference between takeWhile()
and dropWhile()
methods in Java Streams? How would you use them in a real-world application?
Answer: takeWhile()
retrieves elements until a condition is false, while dropWhile()
skips elements until the condition is false. For instance, in financial apps, these methods can filter or exclude transactions based on conditions.
5. Company: Zoho
Question: What are the benefits of using the Map.of()
method introduced in Java 9? Can you provide a use case where this method simplifies your code?
Answer: Map.of()
creates immutable maps concisely, ideal for fixed configurations or constant mappings like predefined error codes.
new interface and methods
Question
Your answer:
Correct answer:
Your Answers