Friday, 4 April 2025

 

throw vs throws in Java (With Real-Life Examples)

Java provides robust exception handling using try, catch, throw, throws, and finally. Among these, throw and throws often confuse beginners. In this post, we'll break down their real-time differences, practical syntax, and usage in real-world Java projects.


🔹 1. Basic Difference

Feature throw throws
Purpose Used to throw an exception manually Declares that a method can throw an exception
Position Used inside a method Declared with method signature
Syntax throw new ExceptionType("msg"); public void method() throws ExceptionType {}
Number Allowed Only one exception object can be thrown Can declare multiple exceptions
Object Required Yes, needs an object of Throwable class No object required

🔹 2. Syntax Examples

// Using throw
public void validateAge(int age) {
    if (age < 18) {
        throw new IllegalArgumentException("Age must be 18 or above");
    }
}
// Using throws
public void readFile(String filePath) throws IOException {
    FileReader fr = new FileReader(filePath); // might throw IOException
}

🔹 3. Real-Time Project Example: Banking System

Let’s assume we are building a banking microservice.

throw Example

public void withdraw(double amount) {
    if (amount > balance) {
        throw new InsufficientFundsException("Insufficient balance");
    }
    balance -= amount;
}
  • Use Case: You manually check a condition and throw an exception to stop the process if it fails.

  • Real-Time Benefit: Helps enforce business rules clearly (like balance checks).

throws Example

public void processLoanApplication(String filePath) throws IOException {
    // Reading a document
    FileInputStream fis = new FileInputStream(filePath);
    // Business logic
}
  • Use Case: You’re dealing with checked exceptions from Java IO or JDBC APIs.

  • Real-Time Benefit: Declares that the caller must handle or propagate it further.


🔹 4. Combined Example

public void applyForLoan(String userId, String documentPath) throws IOException {
    if (!isEligible(userId)) {
        throw new IllegalArgumentException("User not eligible for loan");
    }

    processLoanApplication(documentPath); // throws IOException
}

➕ Explanation:

  • throw is used for business rule failure.

  • throws is used for possible checked exception from external resources (file, DB, etc).


🔹 5. Best Practices

  • Use throw when a method detects an exceptional situation and wants to fail fast.

  • Use throws to delegate responsibility to the caller for handling expected exceptions.

  • Always prefer custom exceptions (like InsufficientFundsException) for clear error handling.


💡 Fun Tip (for Reels or Shorts):

throw is like yelling: 'Hey! Something’s wrong!' 🎯
throws is like politely saying: 'Hey caller, you might want to handle this issue.' 🤝”


🔚 Conclusion

Understanding the difference between throw and throws is crucial for writing clean and effective Java code. Whether you're building microservices, reading files, or validating user input, knowing when to use throw or throws ensures your application handles errors gracefully.

Happy coding! 🚀

 

🚀 Top Tricky HashMap Questions & Answers for MNC Interviews

🌟 1. Can we store a null key in HashMap and ConcurrentHashMap?

✅ Answer:

  • HashMap allows one null key.

  • ConcurrentHashMap ❌ does not allow null keys.

Example:

Map<String, String> map = new HashMap<>();
map.put(null, "value");  // ✅ Works fine

Map<String, String> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put(null, "value");  // ❌ Throws NullPointerException

🌟 2. What happens when two keys have the same hashCode()?

✅ Answer:

This is called a hash collision.

  • Java stores both keys in the same bucket but differentiates them using equals().

  • In Java 7, it used Linked List chaining.

  • In Java 8, if collisions exceed 8, it converts the linked list to a Red-Black Tree to improve O(n)O(log n).


🌟 3. What happens if hashCode() is different but equals() is true?

✅ Answer:

This should never happen because Java assumes:

🚨 If two objects are equal (equals() returns true), they must have the same hashCode().
Otherwise, Java will store them in different buckets, breaking the contract.

Example:

@Override
public int hashCode() { return 123; }  // ❌ Wrong: Every object gets the same hash
@Override
public boolean equals(Object obj) { return true; } // ❌ Bad practice

🔴 This can cause data inconsistency and difficult debugging issues.


🌟 4. What is the worst-case time complexity of HashMap.get()?

✅ Answer:

Scenario Java 7 (O(n)) Java 8 (O(log n))
Best case O(1) (Direct bucket access) O(1)
Worst case O(n) (All elements in same bucket, linked list traversal) O(log n) (Tree traversal in Red-Black Tree)

🚩 Real-world trap: If your hashCode() implementation is bad (returns same value for all keys), performance degrades to O(n).


🌟 5. Can a HashMap have duplicate keys?

✅ Answer:

📝 No. If you insert a duplicate key, it overwrites the existing value.

Map<String, String> map = new HashMap<>();
map.put("fruit", "apple");
map.put("fruit", "banana");
System.out.println(map.get("fruit"));  // Output: banana (replaced apple)

🌟 6. What happens if put() is called during iteration?

✅ Answer:

It throws ConcurrentModificationException.

for (Map.Entry<String, String> entry : map.entrySet()) {
   map.put("newKey", "newValue");  // ❌ ConcurrentModificationException
}

📝 How to avoid?
👉 Use Iterator.remove() instead of map.put() during iteration.
👉 Use ConcurrentHashMap if multi-threading is needed.


🌟 7. What is the default capacity of a HashMap?

✅ Answer:

  • Default capacity: 16

  • Default load factor: 0.75

  • Resize happens when size reaches 16 * 0.75 = 12

📝 How to avoid frequent resizing?
🚀 Initialize HashMap with correct size using:

Map<String, String> map = new HashMap<>(128);

🌟 8. What happens if two threads modify a HashMap at the same time?

✅ Answer:

💀 Data corruption or infinite loop (Java 7)
💀 Lost updates (Java 8)

📝 Solution?
👉 Use ConcurrentHashMap for multi-threading.
👉 Or wrap with Collections.synchronizedMap() (slower).


🌟 9. How does ConcurrentHashMap work internally?

✅ Answer:

👉 Before Java 8: Used segments (mini hash tables)
👉 In Java 8+:

  • No segments

  • Uses bucket-level locking

  • Uses CAS (Compare-And-Swap) for atomic updates

  • Avoids full map locking → much faster


🌟 10. Can we use a mutable object as a HashMap key?

✅ Answer:

🚨 Bad idea! If key’s hashCode() changes, it gets lost in the map.

Example:

class Key {
    int id;
    Key(int id) { this.id = id; }
    @Override
    public int hashCode() { return id; }
}
Map<Key, String> map = new HashMap<>();
Key key = new Key(10);
map.put(key, "value");

key.id = 20;  // ❌ Changing key's hashCode!
System.out.println(map.get(key)); // Output: null ❌ LOST ENTRY!

📝 Solution: Use immutable objects as keys (like String or Integer).



 

🔥 Top 15+ Tricky HashMap Interview Questions (With Smart Answers)

Whether you're preparing for interviews at Amazon, Google, TCS, Infosys, Wipro, or Capgemini, or simply leveling up your Java skills, understanding HashMap internals is a must. Let's explore the trickiest HashMap interview questions—with crisp, smart answers that impress interviewers.


🚀 1. Can HashMap have null keys and null values?

🧠 Trick: Many think null is never allowed.

✅ Answer:

  • Yes, 1 null key is allowed.

  • Multiple null values are allowed.


HashMap<String, String> map = new HashMap<>(); map.put(null, "value"); // ✅ null key map.put("a", null); // ✅ null value

🚀 2. What happens when you insert duplicate keys?

🧠 Trick: Interviewers expect you to explain key replacement.

✅ Answer:
The latest value overrides the old value for the same key.


map.put("fruit", "apple"); map.put("fruit", "mango"); System.out.println(map.get("fruit")); // Output: mango

🚀 3. Is HashMap thread-safe?

🧠 Trick: If you say yes — that’s a red flag.

✅ Answer:
No, it is not thread-safe. Use:

  • Collections.synchronizedMap() (slower, locks whole map)

  • ConcurrentHashMap (preferred in multi-threading)


🚀 4. Can two unequal objects have the same hash code?

🧠 Trick: This is about collision handling.

✅ Answer:
Yes! It's called a hash collision.


System.out.println("FB".hashCode()); // 2236 System.out.println("Ea".hashCode()); // 2236

Java handles collisions using:

  • Linked List (Java 7)

  • Red-Black Tree (Java 8+)


🚀 5. What happens internally when put() is called?

🧠 Trick: They want step-by-step internal flow.

✅ Answer (Java 8):

  1. Compute hash using hashCode()

  2. Map hash to bucket index

  3. Check if key exists using equals()

  4. If exists → replace value

  5. If not → create new Node

  6. If collisions > 8 → convert bucket to Red-Black Tree


🚀 6. What is the load factor?

🧠 Trick: Misunderstanding load factor leads to wrong resizing logic.

✅ Answer:
Load factor = threshold to resize

  • Default = 0.75f

  • Resize happens when:
    current size ≥ capacity * loadFactor


🚀 7. What is rehashing?

🧠 Trick: Interviewers want to test your understanding of resizing.

✅ Answer:
When capacity threshold is crossed, HashMap creates a new array (double size) and repositions all existing keys (rehashing).


🚀 8. Can HashMap key be mutable?

🧠 Trick: Many devs unknowingly use mutable objects as keys.

✅ Answer:
Technically yes, but it's a bad practice.
If a key’s hashCode changes after insertion, you won't be able to retrieve the value.


🚀 9. Difference between HashMap, TreeMap, and LinkedHashMap?

FeatureHashMapTreeMapLinkedHashMap
Ordering❌ No order✅ Sorted✅ Insertion order
Null Key✅ One❌ Not allowed✅ One
Thread-safe❌ No❌ No❌ No

🚀 10. What is treeification in Java 8?

🧠 Trick: This tests Java 8 internal knowledge.

✅ Answer:
If one bucket has more than 8 entries and capacity ≥ 64, Java 8 converts the bucket into a Red-Black Tree → improves lookup to O(log n)


🚀 11. What’s the worst-case time complexity of get() and put()?

ScenarioJava 7Java 8
Best case (no collision)O(1)O(1)
Worst case (collision)O(n)O(log n)

🚀 12. What causes ConcurrentModificationException?

🧠 Trick: Simple-looking question, but many fail it.

✅ Answer:
Modifying a HashMap while iterating it using for-each loop (without Iterator’s remove()).

for (Map.Entry entry : map.entrySet()) { map.put("x", "y"); // ❌ Throws ConcurrentModificationException }

🚀 13. Can initial capacity be set to a large value like Integer.MAX_VALUE?

✅ Answer:
You can, but it’s risky:

  • Might throw OutOfMemoryError

  • Wastes memory if not filled


🚀 14. Why should hashCode() and equals() be overridden for custom keys?

🧠 Trick: Real-world trap question.

✅ Answer:
HashMap uses:

  • hashCode() → to find bucket

  • equals() → to find key in that bucket

If not overridden, keys won’t match, leading to unexpected behavior.


🚀 15. Can a HashMap have two keys with same hash code?

✅ Answer:
Yes. HashMap handles collisions using chaining.


Key1.hashCode() == Key2.hashCode() // true Key1.equals(Key2) // false → both exist in same bucket

 Top 10 Java Interview Questions and Answers for 2025

Preparing for a Java interview in 2025? The Java ecosystem continues to evolve, and companies seek developers with strong problem-solving skills and up-to-date knowledge. Here are the top 10 Java interview questions with answers to help you ace your next interview.


1. What are the main features introduced in Java 17?

Answer: Java 17 (LTS) introduced several key features, including:

  • Sealed Classes

  • Pattern Matching for switch

  • Strongly Encapsulated JDK Internals

  • New macOS Rendering Pipeline

  • Deprecation of Security Manager

Example:

sealed class Vehicle permits Car, Bike {}
final class Car extends Vehicle {}
final class Bike extends Vehicle {}

2. What is the difference between var, final var, and record in Java?

Answer:

  • var is used for local variable type inference.

  • final var ensures that the variable cannot be reassigned.

  • record is a new type for immutable data classes.

Example:

record Person(String name, int age) {}
Person p = new Person("Alice", 30);
System.out.println(p.name()); // Alice

3. How does Java handle memory management?

Answer: Java uses Automatic Garbage Collection (GC) with different collectors like:

  • G1 GC (Default since Java 9)

  • ZGC (Low-latency GC introduced in Java 11)

  • Shenandoah GC (Highly concurrent GC)


4. Explain the difference between ExecutorService and ForkJoinPool.

Answer:

  • ExecutorService is for managing a fixed pool of threads.

  • ForkJoinPool is for parallel processing and divide-and-conquer algorithms.

Example:

ForkJoinPool pool = new ForkJoinPool();

5. What are Virtual Threads in Java?

Answer: Virtual Threads (Project Loom) provide lightweight, scalable concurrency.

Example:

Thread.startVirtualThread(() -> System.out.println("Hello Virtual Threads!"));

6. What is the difference between CompletableFuture and Reactive Streams?

Answer:

  • CompletableFuture handles asynchronous programming.

  • Reactive Streams (Project Reactor) provides backpressure support.


7. How to implement a Kafka consumer in Java?

Answer:

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("my-topic"));

8. What is the difference between HashMap and ConcurrentHashMap?

Answer:

  • HashMap is not thread-safe.

  • ConcurrentHashMap is optimized for concurrent read/write operations.


9. How to optimize performance in Spring Boot applications?

Answer:

  • Use @Transactional to manage DB transactions efficiently.

  • Enable caching with @Cacheable.

  • Use Connection Pooling (HikariCP).


10. What are the best practices for writing clean Java code?

Answer:

  • Follow SOLID principles.

  • Use meaningful variable names.

  • Avoid redundant code (DRY principle).

  • Use logging frameworks (Log4j, SLF4J).


Happy learning....

What is map in java 8

In Java 8, the map method is part of the Stream API, and it is used for transforming each element of a stream using a given function. It applies the provided function to each element in the stream and produces a new stream of the transformed elements. The original stream remains unchanged.

Here’s a basic example using map to convert a stream of strings to uppercase:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "orange");

// Using map to convert each element to uppercase
List<String> uppercasedWords = words.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());

// Print the transformed elements
System.out.println(uppercasedWords);
}
}
  1. words.stream() converts the List of strings (words) into a stream.
  2. .map(String::toUpperCase) applies the toUpperCase method to each element of the stream, transforming each string to its uppercase version.
  3. .collect(Collectors.toList()) collects the transformed elements into a new List.

The result is a new List containing the uppercase versions of the original strings.

You can use map with any function that transforms the elements of the stream. It is a powerful and versatile operation, commonly used for tasks like extracting specific properties from objects, transforming data, or performing calculations on each element of the stream.

see another example of map in java8

  int[] num = {1, 2, 3, 4, 5};

Integer[] result = Arrays.stream(num)
.map(x -> x * 2)
.boxed()
.toArray(Integer[]::new);

System.out.println(Arrays.asList(result));

output- [2, 4, 6, 8, 10]


Happy learning...






 

Friday, 15 September 2023

How to convert Alphanumeric to Numeric String

 

Hi.

have you faced scenarios like you have alphanumeric String and you have requirement to use numeric String to fullfil your requirement, like if need to convert in other data type later.


so here is Magic in below programe:- 


package com.neesri.sorting;


public class AlphanumericToNumeric {


public static void main(String[] args) {

// convert alphanumeric string into numeric string

String str = "a12334tyz78x";

str = str.replaceAll("[^\\d]", "");


System.out.println("Alphanumeric string to Number "+ str);

}

}

======output====


Alphanumeric string to Number 1233478


Happy Learning :) 

How many ways can convert HashMap to List

Hi,

Today we will talk about how we can convert Hashmap into ArrayList.

1. we have converted keys of HashMap into List.

2. we have converted all values of Map into List.

3. we have converted all entries(key  & values) of HashMap into List.

In below i have explained programme stepwise:- 

package com.neesri.sorting;

 

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map.Entry;

import java.util.Set;

 

public class ConvertMapToList {

     // we can convert Hashmap into Arraylist through three ways

     public static void main(String[] args) {

 

           HashMap<String, Integer> hashmapObj = new HashMap<>();

           hashmapObj.put("Zimbabwe", 600);

           hashmapObj.put("India", 700);

           hashmapObj.put("SriLanka", 400);

           hashmapObj.put("Nepal", 800);

 

           // 1-----convert Hashmap Key into List

           // using keyset method retun set view

           Set<String> setViewOfMapKeys = hashmapObj.keySet();

           // convert set into list

           List<String> listObj = new ArrayList<>(setViewOfMapKeys);

 

           System.out.println("Hashmap Keys into list------>");

           for (String printList : listObj) {

                System.out.println(printList);

           }

 

           // 2. Convert Hashmap Values into List

 

           Collection<Integer> values = hashmapObj.values();

           List<Integer> list = new ArrayList<>(values);

           System.out.println("Hashmap values into List----->");

           for (Integer hashmapValuesIntoList : list) {

                System.out.println(hashmapValuesIntoList);

           }

 

           // 3. Convert hashmap all entries into List

 

           Set<Entry<String, Integer>> entriesObjSet = hashmapObj.entrySet();

           List<Entry<String, Integer>> listEntries = new ArrayList<>(entriesObjSet);

 

           // System.out.println("Hashmap all entries into List======>");

           /*

            * for(Object obj:listEntries) {

            *

            * System.out.println(obj); }

            */

           // OR

 

           /*

            * for(Entry<String, Integer> obj:listEntries) {

            *

            * System.out.println(obj); }

            */

 

           // OR

           System.out.println("Printing thorough iterator======>");

           Iterator<Entry<String, Integer>> iterator = listEntries.iterator();

 

           while (iterator.hasNext()) {

                Entry<String, Integer> entry = iterator.next();

 

                System.out.println(entry);

           }

 

     }

 

}

 

==============OUTPUT======

Hashmap Keys into list------>

SriLanka

Zimbabwe

Nepal

India

Hashmap values into List----->

400

600

800

700

Printing thorough iterator======>

SriLanka=400

Zimbabwe=600

Nepal=800

India=700

 

 

Happy Learning :) 

Saturday, 26 August 2023

Tricky question

 

In a social media application, You have a collection of posts, where each post can have multiple comments. 

To retrieve all the comments from all the posts and represents them as a single stream,
Which java Stream operation would you use?

 

The correct answer is flatmap().

So what is flatmap, flatMap() = Flattening + map()

It is an intermediate operation that is always lazy as described in Java Stream API

flattening means,  merging multiple collections/arrays into one.

OR,

Flattening is the process of converting several lists of lists and merge all those lists to create a single list containing all the elements from all the lists.

Flattening Example

Consider the following lists of lists:

Before Flattening: [[1, 2, 3, 4], [7, 8, 9, 0], [5, 6], [12, 18, 19, 20, 17], [22],[23,24,25,26,27]]

After Flattening: [1, 2, 3, 4, 7, 8, 9, 0, 5, 6, 12, 18, 19, 20, 17, 22,23,24,25,26,27]

Syntax

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)


  • R represents the element type of the new stream.
  • mapper is a non-interfering, stateless function to apply to each element which produces a stream of new values.
  • The method returns a new stream of objects of type R.

Similar flatMap() Methods

IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)

Some examples where flatMap can be used are:
Count of words of a text file.
Convert a Nested List into a single List.
Convert a Nested Array into a single Lis

Wednesday, 19 April 2023

How Many ways we can print Array in Java

 

Hi Friends,

Today i am going to show how many ways we can print Array in Java.

As we know following points:- 

Java array is a data structure where we can store the elements of the same data type.

The elements of an array are stored in a contiguous memory location. 

So, we can store a fixed set of elements in an array.

The index of an array starts from 0. 


there are following ways to print array: