Posts

Showing posts with the label frequently asked java interview question

Java Interview Prep: Mastering Static and Final Keywords

Image
When preparing for a Java interview, understanding static and final keywords is essential, as they are frequently discussed. Below is an overview of what static and final mean in Java, along with some examples and interview-style questions to help with your preparation. Understanding static and final in Java 1. static Keyword: Definition : The static keyword is used to declare class-level members. When a method or variable is marked as static , it belongs to the class rather than an instance of the class. Usage : Static Variables : These are shared by all instances of the class. There's only one copy of the static variable for all objects. Static Methods : These belong to the class itself, so they can be called without creating an instance of the class. Static methods can only access static members of the class. Static Block : This is used for static initialization of a class. It is executed once when the class is loaded into memory. Example : class Example { static ...

10 Common Java Interview Questions Related to the Stream API

Java interview questions related to streams are often focused on practical usage of the Stream API introduced in Java 8. Some of the most common practical questions include: 1. Filtering a List Problem: Given a list of integers, filter out the even numbers and return a list of odd numbers. Solution: import java.util.Arrays ; import java.util.List ; import java.util.stream.Collectors ; public class Main { public static void main ( String [] args) { List < Integer > numbers = Arrays . asList ( 1 , 2 , 3 , 4 , 5 , 6 ); List < Integer > oddNumbers = numbers .stream() .filter(n -> n % 2 != 0 ) .collect( Collectors . toList ()); } } 2. Mapping a List Problem:  Given a list of strings, convert all strings to uppercase. Solution: import java.util.Arrays ; import java.util.List ; import java.util.stream.Collectors ; public class Main { public static void main ( String [] args) { List < String > words =...

Java 8 Stream - Sort HashMap based on Keys and Values

Image
By default, Java HashMap doesn’t maintain any order. However, if you need to sort the HashMap, we sort the HashMap explicitly based on your requirements. So, in this section, let’s understand how to sort the hashmap according to the keys and values by using Java 8’s Stream API. 1. Sort HashMap by keys in natural order import java.util. *; import java.util.stream.Collectors ; public class Main { public static void main ( String [] args) { Map < Integer , String > map = new HashMap<>(); map .put( 44 , "Java" ); map .put( 66 , "Ada" ); map .put( 29 , "Go" ); map .put( 98 , "Kotlin" ); map .put( 11 , "C" ); map .put( 125 , "Rust" ); Map < Integer , String > sortedMap = map .entrySet() .stream() .sorted( Map . Entry . comparingByKey ()) .collect( Collectors . toMap ( Map . Entry ::get...