Showing posts with label Java Interview Questions. Show all posts
Showing posts with label Java Interview Questions. Show all posts

Monday, September 7, 2026

Top 5 Interview Questions on BlockingQueue in Java


1) What is BlockingQueue ? Under which package of JDK its available ?

Ans- A blocking queue is an interface. BlockingQueue implementations are thread-safe. It helps to handle multi threaded execution , specially its for producer and consumer problem.
The queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. 

A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. 

There are few implementation for this BlockingQueue as below, all these classes available under java.util.concurrent package.
  • ArrayBlockingQueue
  • SyncronousBlockingQueue
  • PriorityBlockingQueue
  • LinkedBlockingQueue
  • DelayQueue

2) What is the use of these methods peek(), poll(), take() and remove() ?

Ans - 
peek() :- This retrieves, but does not remove, the head of this queue,or returns null if this queue is empty. It doesn't throw any exception.

poll() :- This retrieves and removes the head of this queue,or returns null if this queue is empty.It doesn't throw any exception.

take() :- This retrieves and removes the head of this queue, waiting if necessary until an element becomes available. This method waits for certain time , if its interrupted then it throws InterruptedException. 

remove() :- This retrieves and removes the head of this queue. This method differs from poll() only in that it throws an exception (NoSuchElementException ) if this queue is empty.

Apart from the above difference take() method is provided by BlockingQueue i.e. java.util.concurrent.BlockingQueue.take(). Where as other methods provided by Queue i.e.  java.util.Queue.poll(), java.util.Queue.peek(), java.util.Queue.remove()


3) Is this possible to declare BlockingQueue implementation with ZERO/0 size?

Ans- Yes, if its unbounded implementation. But,if its bounded then we have to provide a capacity. The capacity must be greater than ZERO (i.e. capacity > 0).If we create a BlockingQueue with ZERO capacity then this will throw java.lang.IllegalArgumentException.

4) Write a program for demonstrating producer & consumer problem using blocking
 queue.

Ans- Find the answer here.

5) What is the difference between ArrayBlockingQueue and LinkedBlockingQueue ?

Ans- ArrayBlockingQueue is a bounded blocking queue backed by an array of objects. LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. 
Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.Linked nodes are dynamically 
created upon each insertion unless this would bring the queue capacity (Integer.MAX_VALUE). 

5 Common Java Interview Questions About Objects and Object Class

5 Common Java Interview Questions About Objects and Object Class

These are some common questions asked in Java/J2EE interviews. These questions are based on Java objects and their behavior.

Q.1. How can you define an object? How is it related to the real world and how does it behave? With Example.

Ans: This question is often asked in Java interviews for candidates with 1-8 years of experience. As we know, an object is a real-world entity. It has three basic properties i.e. State, Behavior and Identity. Simply we can say that a class is a blueprint for creating objects, and an object is an instance of a class. Anything around you can be represented as an object. But yes, it has the above three properties by which we can define an object.

State: what the object has. Dog has a name, age, color, etc. It is implemented by variables in Java.

Behavior: what the object does. Dog can bark, bite, run, etc. It is implemented by methods in Java.

Identity: what makes the object unique. Identity is what makes one object distinguishable from another object. It does not necessarily mean that every object must have a unique id variable. Different objects can also have the same hash code.

Example - Suppose there are many dogs. But, you can't say that is an object. You need to take one dog which has name - Dick, age - 8, color - white and it can be distinguished from other objects. And now we can say Dick is a dog object. And this Dick can bark, bite and run. These are the behaviors that the object can do, and they are implemented by methods.

Q.2. How many constructors & methods are in Object class?

Ans: The Object class has one constructor and several methods. The exact list depends on the Java version. It is available inside the java.lang package.

Constructor :-

public Object()

Methods :-

clone() - This creates and returns a copy of the object.
equals() - This is used to compare whether some other object is equal to this object or not.
toString() - Converts and returns a string representation of the object.
finalize() - An old mechanism associated with garbage collection. It is deprecated and should not be relied upon for resource cleanup.
getClass() - This returns the runtime class of this object.
hashCode() - Returns a hash code for this object. The hash code is not guaranteed to be unique.
notify() - Wakes up a single thread that is waiting on this object's monitor.
notifyAll() - Wakes up all threads that are waiting on this object's monitor.
wait() - This makes the current thread wait until another thread notifies it.

Q.3. Why are wait() and notify() methods inside Object class instead of Thread class?

Ans: This is a FAQ for any Java interview. The wait() and notify() methods are used in a multi-threaded environment. These methods are inside the Object class because we are doing the monitoring work over an object. Whenever we are calling these methods, we are calling them on an object, not on a thread.

The wait() and notify() methods are used for thread coordination through an object's monitor.

Q.4. How many ways can we create an object in Java?

Ans: There are basic four ways for creating an object in Java as below:-

By using new keyword -

Object obj = new Object();

By using Class.forName() -

Dog dogObj = (Dog) Class.forName("jdeveloperguide.lab.Dog")
        .getDeclaredConstructor()
        .newInstance();

By using deserialization -

ObjectInputStream inStream = new ObjectInputStream(anInputStream);
Dog dogObject = (Dog) inStream.readObject();

By using clone() -

Dog dogObj = new Dog();
Dog dogObj2 = dogObj.clone();

The class must implement the Cloneable interface and provide appropriate cloning support.

Q.5. How does JVM allocate objects in memory? What is heap and stack memory?

Ans: Normally, objects are allocated on heap memory. Heap memory is a dynamic memory area used for objects during runtime.

Each thread has its own stack for method calls and local variables. Objects are generally allocated on the heap, while references and local variables may be stored in the stack depending on the JVM implementation and optimization.

Every thread creates a stack (call stack), and when the thread completes, its stack is no longer needed and its memory can be reclaimed.

Stack operations are generally simpler and faster than heap allocation, but the actual behavior depends on the JVM and its optimizations.

You can share your interview experience with asked questions and answers for publishing on this blog.

Thursday, September 3, 2026

Find Duplicate Strings in a List Using Java | Java Interview Question

In this article, we will see how to find duplicate strings and their counts from an array or a list using Java. This is one of the common programming questions asked in technical interviews.

In this program, we will use both Map and List, so it is also a good example for understanding Java Collections. You can find a few more Java Collection interview questions.

Today, we will see how to find duplicate strings in a list and count how many times each string is repeated.

Logic

The logic is quite simple:

  • First, we create a Map to store the key-value pair. The key will be the array element, and the value will be the number of times that element occurs.

  • Then, we iterate through the array or list and add each element to the Map. If the element is already present in the Map, we increase its count by 1.

  • After completing the iteration, the Map will contain each string along with the number of times it occurs.

  • Finally, we iterate through the Map and check for entries where the count is greater than 1. These are the duplicate or repeated strings.


CountDuplicate.java

package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class CountDuplicate {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>(
Arrays.asList("JDG", "AA", "AA", "JAVA", "JavaScript", "Java", "Stream", "hibernate", "Hibernate"));
System.out.println("Input List = " + list);
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < list.size(); i++) {
if (map.isEmpty()) {
map.put(list.get(i).toUpperCase(), 1);
} else if (map.containsKey(list.get(i).toUpperCase())) {
map.put(list.get(i).toUpperCase(), map.get(list.get(i).toUpperCase()) + 1);
} else {
map.put(list.get(i).toUpperCase(), 1);
}
}
int counter = 0;
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
counter++;
System.out.println("String Found " + entry.getKey() + " with count " + entry.getValue());
}
}
System.out.println("Total Duplicate String - " + counter);
}
}



Output

Input List = [JDG, AA, AA, JAVA, JavaScript, Java, Stream, hibernate, Hibernate]

String Found: AA with count 2
String Found: JAVA with count 2
String Found: HIBERNATE with count 2

Total Duplicate Strings: 3

 

Happy Learning!



Saturday, July 13, 2019

Find Palindrome Strings in an Array Using Java


In this article, we will see how to find all palindrome strings from an array. This is a very frequently asked questions in interview.  Also there is a question to find all palindrome number from an array.  Find few more collection interview question.  

PalindromeStrings.java

package com.techbyteslearn.lab.basic;

/**
 * This program illustrates how to find palindrome strings from an array.
 */
public class PalindromeStrings {

    public static void main(String[] args) {
        String[] stringArray = {
            "eye",
            "jdg",
            "javadevelopersguide",
            "aabaa",
            "hello",
            "pip"
        };

        for (int i = 0; i < stringArray.length; i++) {
            printOnlyPalindrome(stringArray[i]);
        }
    }

    private static void printOnlyPalindrome(String str) {
        String oldString = str;
        StringBuilder builder = new StringBuilder(str);

        if (builder.reverse().toString().equals(oldString)) {
            System.out.println(oldString + " is a Palindrome String.");
        }
    }
}

Output:

eye is a Palindrome String.
aabaa is a Palindrome String.
pip is a Palindrome String.
Happy Learning.

Find All Palindrome Numbers from an Array in Java

In this article, we will see how to find all palindrome from an array. This is a very basic questions in interview, the interviewer will ask the same questions in different way. So, its good to know all possible questions from palindrome. Also there is a question to find all palindrome number from a list.  Find few more collection interview question.  Today we will see how to check a number is palindrome or not. 

FindAllPalindrome.java

package com.techbyteslearn.lab.basic;

public class FindAllPalindrome {
public static void main(String[] args) {
int numberArray[] = { 120, 990, 121, 777, 808, 1280 };
for (int i = 0; i < numberArray.length; i++) {
printOnlyPalindrom(numberArray[i]);
}
}
private static void printOnlyPalindrom(int number) {
int finalNumber = 0;
int oldNumber = number;
// Repeat the loop until the number became zero.
while (number != 0) {
// Get the First Digit (i.e. 1)
int firstDigit = number % 10;
// Get the Result number.
finalNumber = (finalNumber * 10) + firstDigit;
// Now get the remaining digits , after finding the first digit
number = number / 10;
}
// Now compare the finalNumber and oldNumber both are same or not.
if (finalNumber == oldNumber)
System.out.println(finalNumber + " is a Palindrome.");
}
}

Output -

121 is a Palindrome.
777 is a Palindrome.
808 is a Palindrome.

How to Check Whether a Number Is a Palindrome in Java


In this article, we will see how to check if a number is palindrome or not. This is a very basic questions in interview. But, you never know about what kind of question the interviewer will ask. So, better you prepare for every certain questions. Also there is a question to find all palindrome number from a list.  Find few more collection interview question.  Today we will see how to check a number is palindrome or not. 


Palindrome.java

package com.techbyteslearn.lab.basic;

public class Palindrome {

    public static void main(String[] args) {
        int number = 121;
        int temp = number;
        int finalNumber = 0;

        // Repeat the loop until the number becomes zero.
        while (number != 0) {

            // Get the last digit.
            int lastDigit = number % 10;

            // Build the reversed number.
            finalNumber = (finalNumber * 10) + lastDigit;

            // Remove the last digit from the number.
            number = number / 10;
        }

        // Compare the reversed number with the original number.
        if (finalNumber == temp) {
            System.out.println("This number is a Palindrome.");
        } else {
            System.out.println("This number is not a Palindrome.");
        }
    }
}

Output:

This number is a Palindrome.
 
 

One important correction from the original comments: % 10 gets the last digit, not the first digit. Also, number has already become 0 by the time of the final comparison, so comparing with temp is the correct approach.



Happy Learning.

Thursday, July 11, 2019

Find Duplicate Values in a List Using Java

In this article, we will see how to find the duplicate values from an array or list using java.  This is one of important programming questions in technical interview. Each interviewer has different approach to access the candidate. But, the logic and the approach by candidate is really matter. In this program we have used Map and List both, so its a kind of collections interview questions. You can find few more collection interview question.  Today we will see how to find the duplicate values from array. 


The logic is very simple here, see the below.

  • At first we need we need to create a Map to hold the key-value pair. Where key is the array element and value is the counter for number of time the array element repeats.
  • Then we will iterate the array and put into the map as per the above step. If the map contains the element earlier, then we will update the value +1.
  • Finally we will have the map , which holds the array elements with the counter for repentance. 
  • Now, we will iterate the Map , by checking the condition where the counter is more than 1 (i.e. its duplicated or repeated).


DuplicateFinder.java

package com.techbyteslearn.lab.basic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class DuplicateFinder {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>(
                Arrays.asList(4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90));

        System.out.println("Input List Data = " + list);

        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < list.size(); i++) {

            if (map.isEmpty()) {
                map.put(list.get(i), 1);
            } else if (map.containsKey(list.get(i))) {
                map.put(list.get(i), map.get(list.get(i)) + 1);
            } else {
                map.put(list.get(i), 1);
            }
        }

        System.out.println("\nDuplicate values are: ");

        // Iterate the Map and display the duplicate values.
        for (Entry<Integer, Integer> entry : map.entrySet()) {

            if (entry.getValue() > 1) {
                System.out.println(entry.getKey());

                // TODO: We can now put these values into any list.
            }
        }
    }
}

Output:

Input List Data = [4, 3, 5, 25, 25, 25, 13, 5, 22, 4, 90]

Duplicate values are:
4
5
25

Note- One small point: because HashMap does not guarantee iteration order, the order of 4, 5, and 25 in the output can vary.



Happy Learning.

Find the Largest Number in an Array Using Java

In this article, we will see how to find the largest number from an array using java.  This is one of basic questions in technical interviews. Earlier post we had seen how to find the smallest element from array. Now we will see how to find the largest number from integer array using java. 

The logic is very simple here, see the below.

  • At first we need to assume any element as largest value. Example - 0th location.
  • Then iterate over the array and compare with each element , whether its larger than the assumed larger value or not. If array element is larger then assign the array element value to assumed variable. Repeat the entire until end. 


FindLargestNumberInArray.java

package com.techbyteslearn.lab.basic;

public class FindLargestNumberInArray {

    // Find the largest value from an array.
    public static void main(String[] args) {
        int[] arr = {200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150};

        // Assume the largest value is at the 0th index.
        int largest = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= largest) {
                largest = arr[i];
            }
        }

        System.out.println("Largest Number is ::" + largest);
    }
}

Output:

Largest Number is ::200

The original i < arr.length - 1 skips the last element. Using i < arr.length checks the complete array.


Using Java 8

int largest = IntStream.of(arr).boxed().max(Comparator.naturalOrder()).get().intValue() ;


 Happy Learning.

Find the Smallest Number in an Array Using Java


In this article, we will see how to find the smallest number from an array using java.  This is one of basic questions in technical interviews. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find the smallest number from integer array using java. 


The logic is very simple here, see the below.

  • At first we need to assume the first smallest element.
  • Then iterate over the array and compare with each element , whether its smaller than the assumed value or not. If array element is smaller then assign the array element value to assumed variable. Repeat the entire until end. 

FindSmallestNumberInArray.java

package com.techbyteslearn.lab.basic;

public class FindSmallestNumberInArray {

    // Find the smallest value from an array.
    public static void main(String[] args) {
        int[] arr = {200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150};

        // Assign the 0th index as the first smallest number.
        int smallest = arr[0];

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] <= smallest) {
                smallest = arr[i];
            }
        }

        System.out.println("Smallest Element is - " + smallest);
    }
}

Output:

Smallest Element is - 3

The original i < arr.length - 1 skips the last element. Using i < arr.length is the correct condition.



Using Java 8

IntStream.of(arr).boxed().min(Comparator.naturalOrder()).get().intValue();

Wednesday, July 10, 2019

Find One Missing Number from a List Using Java


In this article, we will see how to find the missing number from a list using java.  This is one of important common interview question asked in interview. You can see, how to find all missing numbers from a list. In this program we will use core java or the traditional way using for loop for finding the miss number from a list. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find one missing number using traditional core java style. 


The logic is very simple here, see the below.

  • At first we need to find the MAX number from the list. We need this MAX number because , we need to calculate the SUM of all natural number up to that max number. 
  • Then , we need to calculate the sum of all those natural number.
  • Then we will subtract each element from the given list from sumOfNaturalNumbers.
  • Now, the at the last  the value inside sumOfNaturalNumbers is the missing number.

FindOneMissingNumber.java

package com.techbyteslearn.lab.basic;

import java.util.ArrayList;
import java.util.Arrays;

public class FindOneMissingNumber {

    public static void main(String[] args) {
        ArrayList<Integer> numberList = new ArrayList<>(
                Arrays.asList(10, 3, 2, 4, 5, 6, 7, 9, 8, 14, 1, 11, 13));

        int sumOfNaturalNumbers = getSumUptoMax(findMax(numberList));

        for (int i = 0; i < numberList.size(); i++) {
            /*
             * Subtract each element from the list from sumOfNaturalNumbers.
             * The final value will be the missing number.
             */
            sumOfNaturalNumbers = sumOfNaturalNumbers - numberList.get(i);
        }

        int missingNumber = sumOfNaturalNumbers;
        System.out.println("Missing Number is :: " + missingNumber);
    }

    // Find the sum of all natural numbers up to limitNumber.
    private static int getSumUptoMax(int limitNumber) {
        int sum = 0;

        for (int i = 1; i <= limitNumber; i++) {
            sum = sum + i;
        }

        return sum;
    }

    // Find the greatest value from the list.
    private static int findMax(ArrayList<Integer> numberList) {
        int largest = numberList.get(0);

        for (int i = 1; i < numberList.size(); i++) {
            if (numberList.get(i) > largest) {
                largest = numberList.get(i);
            }
        }

        return largest;
    }
}

Output:

Missing Number is :: 12

 

This approach assumes the list contains the numbers from 1 through the maximum value, with exactly one number missing.


Happy Learning.

Find a Missing Number from a List Using Java 8 Streams

In this article, we will find the missing number from a list of numbers using java 8.  This is one of important questions asked in interview. This program is to find the only one missing number. Check how to find all missing numbers from a list. In this program we will use only java 8 stream to find the missing number. Earlier post we had seen how to use stream to sort the employee. Check more how find one missing number using traditional core java style


FindMissingNumber.java

package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;

public class FindMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 3, 2, 4, 5, 6, 7, 9, 10));
// Get the Max value from the List.
int maxValue = numberList.stream().max(Comparator.naturalOrder()).get().intValue();
// Get sum of all natural numbers - upto the above maxvalue
int sumOfAllNumber = IntStream.range(1, maxValue + 1).sum();
// Get the sum of all number inside List.
int sumofList = numberList.stream().mapToInt(Integer::intValue).sum();
// Now print the missing number.
System.out.println("The Missing Number is:: " + (sumOfAllNumber - sumofList));
}
}

Output - 

The Missing Number is:: 8

Tuesday, July 9, 2019

Comparable vs Comparator in Java: Understanding the Comparable Interface


In this article we will see what is Comparable<T> interface ? How to use this interface with some sample examples ?

The Comparator interface is present inside java.util package. Its comparison function, which imposes a total ordering on some collection of objects. Its mostly used while sorting a collection of objects.  Means, it compares its two arguments for order.  Returns a negative integer,zero, or a positive integer as the first argument is less than, equal to, or greater than the second one.

The Comparators can be passed to a sort method (i.e. Collections.sort or Arrays.sort) to allow precise control over the sorting order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

This interface has one important method (Before JDK 8)  -

int compare(T o1, T o2);



The below Employee class is our POJO , we will use this class to sort the employee list by age and department.

Employee.java

package com.techbyteslearn.lab.basic;

public class Employee {
private String name;
private int age;
private String department;
public Employee(String name, int age, String department) {
super();
this.name = name;
this.age = age;
this.department = department;
}
@Override
public String toString() {
return "\n Employee [name=" + name + ", age=" + age + ", department=" + department + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}

Now, we need to create a comparator to compare two same objects. We can create as many comparators by implementing each field/attributes of the pojo. Its purely business requirement, how you need your sorting functionality. Here we need the sorting based on the employee  age and employee department.

EmployeeAgeComparator.java

package com.techbyteslearn.lab.basic;
import java.util.Comparator;

public class EmployeeAgeComparator implements Comparator<Employee> {
@Override
public int compare(Employee emp1, Employee emp2) {
return emp1.getAge() - emp2.getAge();
}
}


EmployeeDeptComparator.java

package com.techbyteslearn.lab.basic;
import java.util.Comparator;

public class EmployeeDeptComparator implements Comparator<Employee> {
@Override
public int compare(Employee emp1, Employee emp2) {
// Internally for comparing String we need to use compareTo()
return emp1.getDepartment().compareTo(emp2.getDepartment());
}
}

In the above we created two comparator for age and department. Now, we need to action on our comparators. We will call our newly created comparator from main() and see the result. Below EmployeeComparatorExample class show the comparator in action.


EmployeeComparatorExample.java

package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Collections;

public class EmployeeComparatorExample {
public static void main(String[] args) {
Employee e1 = new Employee("Matt Kuban", 32, "IT");
Employee e2 = new Employee("Andrew Smith", 42, "HR");
Employee e3 = new Employee("Butler Jason", 52, "HR");
Employee e4 = new Employee("Miss Linda", 35, "HR");
Employee e5 = new Employee("Bradley Head", 23, "IT");
Employee e6 = new Employee("Peter Parker", 34, "ADMIN");
// Create an arraylist and add all the employee object into that list.
ArrayList<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
employeeList.add(e5);
employeeList.add(e6);
System.out.println("Employee Before Sort ::" + employeeList);
// Using EmployeeAgeComparator - to sort the employee by Age
EmployeeAgeComparator ageComparator = new EmployeeAgeComparator();
Collections.sort(employeeList, ageComparator);
// Using EmployeeDeptComparator - to sort the employee by Department
EmployeeDeptComparator deptComparator = new EmployeeDeptComparator();
Collections.sort(employeeList, deptComparator);
System.out.println("Employee After Sort ::" + employeeList);
}
}

Output :- 

Employee Before Sort ::[
 Employee [name=Matt Kuban, age=32, department=IT],
 Employee [name=Andrew Smith, age=42, department=HR],
 Employee [name=Butler Jason, age=52, department=HR],
 Employee [name=Miss Linda, age=35, department=HR],
 Employee [name=Bradley Head, age=23, department=IT],
 Employee [name=Peter Parker, age=34, department=ADMIN]]

Employee After Sort ::[
 Employee [name=Peter Parker, age=34, department=ADMIN],
 Employee [name=Miss Linda, age=35, department=HR],
 Employee [name=Andrew Smith, age=42, department=HR],
 Employee [name=Butler Jason, age=52, department=HR],
 Employee [name=Bradley Head, age=23, department=IT],
 Employee [name=Matt Kuban, age=32, department=IT]]


JAVA 8 

In JDK 8,  Comparator<T> is functional Interface. Its annotated with @FunctionalInterface and this comparator interface has added few more default & static methods. As its a functional interface therefore its will be used as the assignment target for a lambda expression or method reference.

Below are few examples :-

default Comparator<T> reversed()
default Comparator<T> thenComparing(Comparator<? super T> other)
default <U> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
default <U extends Comparable<? super U>> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor)
default Comparator<T> thenComparingInt(ToIntFunction<? super T> keyExtractor)



Here is the full list of methods added into Comparator<T> . We can use stream api of java 8 with lambda expression to implements comparator interface. We will see in the next subsequent posts on lambda expression and stream api.



Happy Learning.

Monday, July 1, 2019

Producer Consumer Example Using BlockingQueue in Java

Threading is a very tricky and interesting concept in java programming language. There are many problems we face in technology out of which producer-consumer is one. Today we will write a java program for showing producer consumer problem and its solution by using BlockingQueue implementation. 

In this program we will use ArrayBlockingQueue

FoodProducer.java

package com.techbyteslearn.lab.concurrent; import java.util.concurrent.BlockingQueue; public class FoodProducer implements Runnable { private BlockingQueue<String> producerQueue = null; public FoodProducer(BlockingQueue<String> queue) { producerQueue = queue; } @Override public void run() { try { producerQueue.put("Drinks"); Thread.sleep(2000); producerQueue.put("Chocolates"); Thread.sleep(2000); producerQueue.put("Fruits"); Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } }

 

FoodConsumer.java

 

package com.techbyteslearn.lab.concurrent;

import java.util.concurrent.BlockingQueue;

public class FoodConsumer implements Runnable {

    private BlockingQueue<String> consumerQueue = null;

    public FoodConsumer(BlockingQueue<String> consumerQueue) {
        this.consumerQueue = consumerQueue;
    }

    @Override
    public void run() {
        try {
            System.out.println(consumerQueue.take());
            System.out.println(consumerQueue.take());
            System.out.println(consumerQueue.take());

            Thread.sleep(2000);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }
}

 

MainFoodProcess.java

 

package com.techbyteslearn.lab.concurrent; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class MainFoodProcess { public static void main(String[] args) throws InterruptedException { final BlockingQueue<String> queue = new ArrayBlockingQueue<>(2); FoodProducer producer = new FoodProducer(queue); FoodConsumer consumer = new FoodConsumer(queue); new Thread(producer).start(); new Thread(consumer).start(); Thread.sleep(3000); } }

Output:

Drinks 
Chocolates 
Fruits
The important point in this example is that the ArrayBlockingQueue has a capacity of 2, while the producer adds three items. The put() method blocks when the queue is full until the consumer takes an item from the queue.

The output here is that, every time the producer insert element into the Queue the consumer will take that element out of the queue. 

Here we have used the below 2 important methods take() and put(). There are few many method provided by the BlockingQueue implementation. Find more methods on BlockingQueue.

take() - Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
put() - Inserts the specified element into this queue, waiting if necessary for space to become available.


Happy Learning.

Sunday, April 22, 2018

Check NullPointerException in JDK 8 – Use Optional



How to handle NullPointerException or null check in JDK8 ? Checking null in JDK8 using Optional<T>.

NullPointerException is most common exception which each developer need to handle. Its very common while you are playing around many object. Before JDK 8 , it was a tedious task and lots of boilerplate code you need to write to handle this NullPointerException. But, after JDK 8 it Make your code more readable and protect it against null pointer exceptions. This API will help to write cleaner and more readable code , with intelligence to handle null check internally.

Below Example has few demonstration , how to use the Optional<T> api to avoid NullPointerException. You can handle Null check for your object.


Employee.java


package com.techbyteslearn.tutorial.jdk8;

public class Employee {
private String empName;
private int age;
private Address empAddress;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getEmpAddress() {
return empAddress;
}
public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}
}

Address.java
package com.techbyteslearn.tutorial.jdk8;
public class Address {
private String homeUnitNo;
private String streetNo;
private String city;
public String getHomeUnitNo() {
return homeUnitNo;
}
public void setHomeUnitNo(String homeUnitNo) {
this.homeUnitNo = homeUnitNo;
}
public String getStreetNo() {
return streetNo;
}
public void setStreetNo(String streetNo) {
this.streetNo = streetNo;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

NullPointerCheck.java

package com.techbyteslearn.tutorial.jdk8; import java.util.Optional; public class NullPointerCheck { public static void main(String[] args) { String empName = null; /** * Before JDK 8, this will print "Print null". */ if (null != empName) { System.out.println("Print not null"); } else { System.out.println("Print null"); } /** * Before JDK 8, this throws NullPointerException. */ try { if (empName.equals("SomeThing")) { System.out.println("Print SomeThing"); } } catch (Exception e) { e.printStackTrace(); } /** * JDK 8 provides an easy and clean API, i.e. Optional<T>, * for handling this type of scenario. */ Optional<String> optionalString = Optional.ofNullable(empName); if (optionalString.isPresent()) { System.out.println("Employee Name ::" + empName); } /** * How to work with your own objects. */ Employee employee = new Employee(); employee.setEmpName("Peter"); Optional<Employee> optionalEmployee = Optional.ofNullable(employee); if (optionalEmployee.map(Employee::getEmpAddress).isPresent()) { System.out.println(employee.getEmpName() + "- Address is registered"); } else { System.out.println(employee.getEmpName() + "- Address is null"); } Employee employee1 = new Employee(); employee1.setEmpName("Mark Garret"); Address address = new Address(); address.setCity("Sydney"); employee1.setEmpAddress(address); Optional<Employee> optionalEmployeeWithAddress = Optional.ofNullable(employee1); if (optionalEmployeeWithAddress.map(Employee::getEmpAddress).isPresent()) { System.out.println( employee1.getEmpName() + "- Address is " + address.getCity()); } else { System.out.println(employee1.getEmpName() + "- Address is null"); } /** * Use Optional.empty() to represent an empty value. */ Employee empObject = new Employee(); System.out.println( "Returns Optional empty Value ::" + Optional.empty()); /* * Optional.of() does not handle null values. Be careful when using * this method. Use ofNullable() when the value may be null. */ System.out.println( "Returns Optional empty Value ::" + Optional.of(empObject) .map(Employee::getEmpAddress) .isPresent()); } }

Output:

Print null java.lang.NullPointerException at com.javadevelopersguide.tutorial.jdk8.NullPointerCheck.main(NullPointerCheck.java:48) Peter- Address is null Mark Garret- Address is Sydney Returns Optional empty Value ::Optional.empty Returns Optional empty Value ::false

 

Small technical note: Optional.of(empObject) itself is safe here because empObject is not null. The map() operation then produces Optional.empty() because getEmpAddress() returns null.

I have used below methods from Optional<T> :-

empty() - Returns an empty Optional instance


of() - Returns an Optional with the specified present non-null value.


isPresent() - If a value is present, invoke the specified consumer with the value, otherwise do nothing.


map() - If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.


ofNullable() - Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.


There are few more methods are there, you can give a try. Below link will give you a complete information. Read more about the Optional<T> by JDK 8.



Hope it will help you.