Showing posts with label Java Programming. Show all posts
Showing posts with label Java Programming. Show all posts

Monday, September 7, 2026

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.

Why Are Interface Methods Public in Java?

Why Are Interface Methods Public in Java?

Do you know why methods in a Java interface are public?

Consider the following example:

interface IMyInterface {

    public void display();

    public void calculate();
}

// Implementation class
class MyImplClass implements IMyInterface {

    @Override
    public void display() {
        System.out.println("Hi: Override-Display");
    }

    @Override
    public void calculate() {
        System.out.println("Hi: Override-calculate");
    }

    // Class's own method
    public void show() {
        System.out.println("Hi: I am Own Method");
    }

    public static void main(String[] args) {

        IMyInterface f = new MyImplClass();

        f.display();
    }
}

Output

Hi: Override-Display

Why must an interface method be public?

An interface defines a contract that implementing classes agree to provide.

An abstract interface method is implicitly public, so the following declarations are equivalent:

interface IMyInterface { void display(); public void calculate(); }

Both methods are public abstract methods.

When a class implements an interface, it must provide an implementation that is at least as accessible as the interface method.

For example, this is valid:

class MyImplClass implements IMyInterface { public void display() { System.out.println("Display"); } }

But this is not valid:

class MyImplClass implements IMyInterface { private void display() { System.out.println("Display"); } }

The compiler will report an error because a private method has weaker access than the public interface method.

The same applies to protected:

protected void display() { // Invalid }

You cannot reduce the visibility of an interface method when implementing it.

Why is this important?

Consider:

IMyInterface obj = new MyImplClass(); obj.display();

The reference type is the interface. The interface promises that display() is publicly available.

Therefore, the implementation cannot suddenly make that method private or protected.

The interface establishes the public contract, while the implementing class provides the actual implementation.

An important modern Java point

The statement "all methods in an interface are public" is no longer completely accurate.

Since Java 8, interfaces can also contain default and static methods. Since Java 9, interfaces can contain private methods.

For example:

interface IMyInterface { void display(); // public abstract default void print() { System.out.println("Default method"); } static void info() { System.out.println("Static method"); } private void helper() { System.out.println("Private helper"); } }

So the more accurate statement is:

Abstract methods declared in an interface are implicitly public. Interface default and static methods are also public by default, while interfaces can additionally contain private methods for internal implementation.

Key point

An interface defines a contract between the interface and its implementing classes. An implementing class cannot provide a weaker access level for an interface method.

Understanding hashCode() in Java


Understanding hashCode() in Java

The hashCode() method is defined in the Object class and is used to return a hash code value for an object.

It is especially important when working with hash-based collections such as HashMap, HashSet, and Hashtable.

public int hashCode()


General contract of hashCode()

There are a few important rules that should be followed:

If hashCode() is called multiple times on the same object during a Java application execution, it should return the same integer value as long as the information used by equals() has not changed.

If two objects are considered equal according to the equals() method, they must return the same hash code. Two objects that are not equal do not have to return different hash codes. Different objects can have the same hash code. This is called a hash collision.

Having fewer collisions can improve the performance of hash-based collections.

Example

Consider the following class:

public class Employee {

    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Employee)) {
            return false;
        }

        Employee employee = (Employee) obj;

        return id == employee.id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }
}

Here, id is used to determine whether two Employee objects are equal. Therefore, the same id is also used to calculate the hash code.

This is important because:

Employee e1 = new Employee(101, "John");
Employee e2 = new Employee(101, "David");
System.out.println(e1.equals(e2)); // true 
System.out.println(e1.hashCode());
System.out.println(e2.hashCode());



Since both objects have the same id, they are considered equal and must have the same hash code.


Why is hashCode() important?

Hash-based collections use the hash code to efficiently locate objects.


For example:

HashSet<Employee> employees = new HashSet<>(); 

employees.add(new Employee(101, "John"));

employees.add(new Employee(101, "David"));

System.out.println(employees.size());


Because the two objects are considered equal based on id, the HashSet treats them as the same element.


Important point

  1. If you override equals(), you should also override hashCode().
  2. The basic rule to remember is:
  3. If a.equals(b) is true, then a.hashCode() must equal b.hashCode().
  4. However, the reverse is not required:
  5. Same hash code does not mean that two objects are equal.

Find Number of Days Between Two Dates in Java

Find Number of Days Between Two Given Dates in Java

Sometimes we need to find the number of days between two given dates. Earlier, I used Calendar and manually calculated the difference between the dates.

With Java 8 and later, this can be done much more easily using the java.time package.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class FindDays {

    public static void main(String[] args) {

        String str1 = "20/01/2013";
        String str2 = "28/03/2013";

        DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("dd/MM/yyyy");

        LocalDate date1 = LocalDate.parse(str1, formatter);
        LocalDate date2 = LocalDate.parse(str2, formatter);

        long days = ChronoUnit.DAYS.between(date1, date2);

        System.out.println("Final Days.... " + days);
    }
}

Output:

Final Days.... 67

How it works

DateTimeFormatter is used to tell Java the format of the input dates.

LocalDate represents a date without a time or timezone.

ChronoUnit.DAYS.between() calculates the number of days between the two dates.

For example:

20/01/2013 → 28/03/2013 = 67 days

The older Calendar approach can still be found in existing Java applications, but for new development, the java.time API is generally the better choice.


Understanding the super Keyword and Constructors in Java

Understanding the super Keyword and Constructors in Java

When talking about inheritance in Java, it is important to understand that constructors are not inherited by a subclass.

A subclass can, however, invoke a constructor of its super class using the super keyword.

A few points about the super keyword

  1. super is a Java keyword.

  2. It can be used to access members of the super class, such as fields and methods.

  3. It can be used to invoke a super class constructor.

  4. When calling a super class constructor using super(...), it must be the first statement in the subclass constructor.

Example

class SUP {

    public SUP(String s) {
        System.out.println("Hi Super: " + s);
    }
}

// SUB class extending SUP class
class SUB extends SUP {

    public SUB(String p) {

        // Explicitly call the super class constructor
        // super(...) must be the first statement
        super(p);

        System.out.println("Hi SUB: " + p);
    }

    public static void main(String[] args) {
        new SUB("Rahul Sharma");
    }
}

Output

Hi Super: Rahul Sharma
Hi SUB: Rahul Sharma

When the SUB object is created, its constructor first invokes the SUP constructor using super(p). After the super class constructor completes, the remaining statements in the SUB constructor are executed.

What happens if super() is not written?

If the super class has an accessible no-argument constructor, Java automatically inserts a call to super() as the first statement of the subclass constructor, provided you don't explicitly call another super class constructor.

For example:

class SUP {

    public SUP() {
        System.out.println("Hi Super");
    }
}

class SUB extends SUP {

    public SUB() {
        // Compiler automatically inserts super();
        System.out.println("Hi SUB");
    }
}

The output is:

Hi Super
Hi SUB

However, if the super class does not have an accessible no-argument constructor, the subclass must explicitly invoke one of the available super class constructors.

Important point

Constructors are not inherited in Java. They are invoked as part of object construction.

The super keyword allows a subclass to explicitly invoke a super class constructor and access super class members.

Saturday, September 5, 2026

Java: JVM Inside — The Story Behind JVM (Part 2)

In the previous post, we discussed some basic concepts about the JVM and its role in the Java platform. If you haven't read it yet, you can read Java: JVM Inside — The Story Behind the JVM before continuing with this post.

In this post, let's look a little deeper into what happens inside the JVM and some of the important runtime areas used while a Java application is running.

From Java Source Code to Bytecode

Java source code is compiled by the Java compiler (javac) into bytecode. The bytecode is stored in .class files.

A Java application may contain many classes, so multiple .class files can be packaged together into a JAR (Java Archive) file for easier distribution.

The Java application launcher, java, can be used to start a Java application. The JVM loads the required classes and executes the bytecode.

A JVM may interpret bytecode and can also use Just-In-Time (JIT) compilation to compile frequently executed code into native machine code at runtime. This allows the JVM to optimize application execution while the program is running.

There are also other approaches, such as Ahead-of-Time (AOT) compilation, which can compile code ahead of execution for particular environments.

JVM Runtime Areas

The JVM specification defines several runtime data areas. Some are created for each thread, while others are shared by threads. Important areas include:

  1. Program Counter (PC) Register

  2. JVM Stack

  3. Heap

  4. Method Area

  5. Runtime Constant Pool

  6. Native Method Stack

The JVM specification defines these runtime areas as part of the JVM architecture.

Bytecode Verification

Before bytecode is executed, the JVM performs verification as part of the class loading and linking process.

Bytecode verification helps ensure that class files satisfy the structural and type-safety requirements expected by the JVM.

For example, verification helps check that:

  1. Instructions are used correctly.

  2. Type information is used consistently.

  3. Branches and control-flow information are valid.

  4. Access-control rules are respected.

The JVM specification describes verification as part of the linking process.

JVM Stack

Each JVM thread has its own JVM stack.

The JVM stack contains frames, and a new frame is created when a method is invoked. A frame contains information such as local variables, an operand stack, and information used for dynamic linking.

For example:

Thread
  |
  +-- JVM Stack
        |
        +-- Frame for main()
        |
        +-- Frame for methodA()
        |
        +-- Frame for methodB()

When a method completes, its frame is removed from the stack.

The JVM specification defines JVM stacks and frames as important parts of the runtime environment.

Heap

The heap is the runtime data area from which memory for objects and arrays is allocated.

For example:

Employee employee = new Employee();

When the new operation creates an Employee object, the object is allocated in the heap.

Java does not require developers to manually free this object using a free() operation as in languages such as C or C++. Instead, Java uses Garbage Collection (GC) to automatically reclaim heap memory that is no longer reachable by the application.

Garbage collection is one of the important features of the Java runtime.

A simple way to visualize this is:

JVM
 |
 +-- Heap
 |     |
 |     +-- Object 1
 |     +-- Object 2
 |     +-- Array
 |
 +-- JVM Stack
       |
       +-- Local variables
       +-- Object references

It is common to explain that an object reference can be held in a stack frame while the actual object is located in the heap. However, the exact implementation details of references and memory placement are JVM-implementation dependent, so this should be treated as a conceptual model rather than a strict physical-memory rule.

Arrays in Java are objects, so they are also managed as heap objects.

Method Area

The Method Area is a JVM runtime data area that is shared among threads.

It stores per-class structures such as the runtime representation of classes, methods, fields, and other class-related information.

The method area is not simply a place where "all bytecode is stored." Class files are loaded and linked by the JVM, and the JVM maintains the runtime representation required for execution.

The JVM specification defines the Method Area conceptually, while the exact implementation is JVM-specific.

Runtime Constant Pool

Each class or interface has a runtime constant pool associated with it.

It contains information derived from the constant pool in the class file, including constants and symbolic references used by the class.

The runtime constant pool is important for operations such as dynamic linking.

Final Thoughts

The JVM is much more than a simple program that executes .class files.

It provides a complete runtime environment for loading classes, verifying bytecode, managing memory, executing methods, handling threads, performing garbage collection, and optimizing frequently executed code.

Understanding these JVM runtime areas helps Java developers understand what happens behind the scenes when a Java application runs.

Java: JVM Inside — The Story Behind the JVM

The JVM (Java Virtual Machine) is a core component of the Java platform. JVM stands for Java Virtual Machine.

The JVM is software that provides an execution environment for running Java bytecode. It acts as an abstraction layer between Java bytecode and the underlying operating system and hardware.

Java source code is first compiled into bytecode, which is stored in .class files. The JVM then loads and executes this bytecode.

A simple way to understand the process is:

Java Source Code → Java Compiler (javac) → Bytecode → JVM → Operating System / Hardware

The important point is that the same Java bytecode can generally run on different operating systems as long as a compatible JVM implementation is available.

This is one of the key ideas behind Java's well-known WORA (Write Once, Run Anywhere) concept.

For example, the same .class file can be executed using a compatible JVM on different platforms:

                 Java Source File (.java)
                           |
                           |
                     Java Compiler
                       (javac)
                           |
                           |
                    Bytecode (.class)
                           |
              +------------+------------+
              |            |            |
             JVM          JVM          JVM
              |            |            |
           Windows        Linux        macOS

The JVM specification defines how Java class files and bytecode are handled, while JVM implementations provide the actual runtime environment for a particular platform.

Why is JVM important?

The JVM provides several important capabilities, including:

  • Loading and executing Java class files

  • Managing memory and runtime data areas

  • Garbage collection

  • Bytecode verification

  • Exception handling

  • Supporting Java's platform-independent execution model

  • Providing runtime services needed by Java applications

The JVM specification defines areas such as the heap, JVM stacks, method area, runtime constant pool, and native method stacks.

Therefore, the JVM is one of the fundamental components that makes the Java platform portable across different operating systems and hardware environments.


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.

Tuesday, July 9, 2019

Sort Employees by Name and Age Using Java 8

This program for writing a program to sort the employee by name and age using JDK 8. Java 8 introduced many out of box features for developers. The comparator in java 8 is marked as @FunctionalInterface, and it provide a cleaner way to develop your code. We had already discussed how the Comparator<T> interface works before java 8. In this post, we will use the stream API with comparator. 


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 will create an action or main method to use the above POJO class for sorting.

SortEmployeeWithStream.java

package com.techbyteslearn.lab.basic;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Collectors;
public class SortEmployeeWithStream {
public static void main(String[] args) {
Employee1 e1 = new Employee1("Ander Koli", 32, "Sales");
Employee1 e2 = new Employee1("Andrew Smith", 23, "Sales");
Employee1 e3 = new Employee1("David Jone", 52, "Sales");
Employee1 e4 = new Employee1("Cuba Station", 23, "Marketing");
Employee1 e5 = new Employee1("Bradley Head", 23, "Marketing");
Employee1 e6 = new Employee1("Peter Parker", 34, "Sales");
// Create an arraylist and add all the employee object into that list.
ArrayList<Employee1> employeeList = new ArrayList<Employee1>();
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
employeeList.add(e5);
employeeList.add(e6);
System.out.println("Employee list before sorting -\n" + employeeList);
ArrayList<Employee1> sortedList = (ArrayList) employeeList.stream()
.sorted(Comparator.comparing(Employee1::getName).thenComparing(Employee1::getAge))
.collect(Collectors.toList());
System.out.println("Employee list after sorting -\n" + sortedList);
}
}


Output-

Employee list before sorting -
[
 Employee1 [name=Ander Koli, age=32, department=Sales],
 Employee1 [name=Andrew Smith, age=23, department=Sales],
 Employee1 [name=David Jone, age=52, department=Sales],
 Employee1 [name=Cuba Station, age=23, department=Marketing],
 Employee1 [name=Bradley Head, age=23, department=Marketing],
 Employee1 [name=Peter Parker, age=34, department=Sales]]
Employee list after sorting -
[
 Employee1 [name=Ander Koli, age=32, department=Sales],
 Employee1 [name=Andrew Smith, age=23, department=Sales],
 Employee1 [name=Bradley Head, age=23, department=Marketing],
 Employee1 [name=Cuba Station, age=23, department=Marketing],
 Employee1 [name=David Jone, age=52, department=Sales],
 Employee1 [name=Peter Parker, age=34, department=Sales]]

The Comparator.comparing  and thenComparing  two static methods inside Comparator. As we know Comparator is a Functional interface which provides default and static methods along with implementation.  These functional interfaces are giving out of box functionality. See how before java 8 with Comparator interface examples.

Also we can achieve the above sorting by creating multiple different comparators , which we can use when we need. 

We have created two comparator as compareByAge, CompareByDept . Now we can use those comparators at any place we need along with stream. Below sample code snippet shows the usages. Read these reference documents for more about  stream, comparator, functions, jdk 8 features.


Comparator<Employee1> compareByAge = Comparator.comparing(Employee1::getAge);
Comparator<Employee1> compareByDept = Comparator.comparing(Employee1::getDepartment);
ArrayList<Employee1> sortedList = (ArrayList) employeeList.stream()
.sorted(compareByAge.thenComparing(compareByDept)).collect(Collectors.toList());


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.