Thursday, January 11, 2024

Java Stream API Interview Questions And Answers

In this post Java Stream API Interview Questions and answers are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is Stream API in Java?

    Stream API is added in Java 8 and works very well in conjunction with lambda expressions. You can create a pipeline of stream operations to manipulate data by performing operations like search, filter, sort, count, map etc.

    Read more about Stream API in Java here.

  2. What is stream in Stream API?

    A stream can be visualized as a pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc.), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

    Read more about Stream API in Java here.

  3. Explain stream operations with an example?

    In this example let's take an ArrayList as an input. There are two operations; take only those elements of the list which are greater than 5 and then sort the result. After that print the elements of the list.

    // Creating the list
    List<Integer> numList = Arrays.asList(34, 6, 3, 12, 65, 1, 8);
    numList.stream().filter((n) -> n > 5).sorted().forEach(System.out::println); 
    
    Here ArrayList is the data source for the stream and there are two intermediate operations–
    • filter- Filter condition here is; take only those elements of the list which are greater than 5. Click to read more about filter() method.
    • sorted- sort that filtered output of the last stream. Click to read more about sorted() method.
    Terminal operation here is forEach statement (provided in Java 8) which iterates the sorted result and displays them. Read more about forEach statement in Java 8 here.

  4. How many types of Stream operations are there?

    Stream operations are divided into intermediate and terminal operations, and are combined to form stream pipelines.

    • Intermediate operations return a new stream. They are always lazy; executing an intermediate operation does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
    • Terminal operations such as Stream.forEach or IntStream.sum, may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
    See some Stream API examples here.

  5. What are Stateless and Stateful operations in Java stream?

    Intermediate operations are further divided into stateless and stateful operations.

    • Stateless operations, such as filter() and map(), retain no state from previously seen element when processing a new element, each element can be processed independently of operations on other elements.
    • Stateful operations, such as distinct() and sorted(), may incorporate state from previously seen elements when processing new elements. Stateful operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
    See some Stream API examples here.

  6. What is Parallel Stream in Java Stream API?

    You can execute streams in serial or in parallel. When a stream executes in parallel, the Java runtime partitions the stream into multiple sub-streams.

    As example- Collection has methods Collection.stream() and Collection.parallelStream(), which produce sequential and parallel streams respectively.

    Read more about parallel stream here.

  7. What is the benefit of using parallel stream?

    When parallel stream is used the Java runtime partitions the stream into multiple sub-streams. This parallel execution of data, with each sub-stream running in a separate thread, will result in increase in performance.

    Read more about parallel stream here.

  8. Can you use streams with primitives?

    Streams work only on object references. They can’t work on primitive types so you have two options to use primitives.

    • You can wrap primitive types into a wrapper object. As example Stream<Integer>, Stream<Long> or Stream<Double>.
    • Second and better option is to use primitive specializations of Stream like IntStream, LongStream, and DoubleStream that can store primitive values.
    • As example- IntStream is = IntStream.of(3, 4, 5, 6);

    Read more about Primitive type streams in Java here.

  9. How can you transform Stream to primitive type Stream?

    Stream interface provides methods mapToInt, mapToDouble and mapToLong that can be used to transform stream of objects to a stream of primitive types.

    As example- If you have a list of employee objects and you want to get the maximum salary. In that case you can take the salary field and use mapToInt method to get a stream of primitive types. Then you can use max method on that primmitive type stream.

    OptionalInt maxSalary = empList.parallelStream().mapToInt(e -> e.getSalary()).max();
    
    Read more about Primitive type streams in Java Stream API here.

  10. What are Reduction Operations in Java Stream API?

    Stream API contains many terminal operations (such as average, sum, min, max, and count) that return one value by combining the contents of a stream. These operations are called reduction operations because these operations reduce the stream to a single non-stream value.

    Read more about Reduction Operations in Java Stream API here.

  11. What are Map operation in Java Stream API?

    Map operations are used to do the element mapping from one stream to another. Map operation will return a stream consisting of the results of applying the given function to the elements of this stream. So, whatever function is provided is applied on all the elements of the stream.

    Since new stream is returned map operation is an intermediate operation.

    Read more about Map operation in Java Stream API here.

  12. What is a mutable reduction operation?

    A mutable reduction operation can be defined as an operation that accumulates input elements into a mutable result container, such as a Collection or StringBuilder.

    Read more about Reduction operation in Java Stream API here.

  13. What is a collect method in Java stream?

    Using collect method you can store the result of the stream operation into a collection. This is a terminal operation.

    As example- If you have employee objects and you want a list having names of all the employees you can use the toList method of the Collectors class.

    List<String> nameList = empList.stream().map(Employee::getName).collect(Collectors.toList());
    
    Read more about Collecting in Java Stream API here.

  14. What is flatMap() method in Java?

    In mapping operation the given function is applied to all the elements of the stream. Where as flattening a structure, means bringing all the nested structures at the same level.

    As example if you have a list of Strings, list<String> like - [[“a”, “b”, “c”], [“c”, “d”], [“c”, “e”, “f”]] then flattening it will bring everything to the same level and the structure you will have be like this-

    [“a”, “b”, “c”, “c”, “d”, “c”, “e”, “f”]
    

    flatMap() method means you are bringing both of them together, function will be applied to all the elements of the stream and then it will be flatten to have a single level structure.

    Read more about FlatMap in Java here.

  15. What is a Spliterator in Java?

    Spliterators, like iterators, are for traversing the elements of a source. Spliterator can split the source and iterate the splitted parts in parallel. That way a huge data source can be divided into small sized units that can be traversed and processed in parallel.

    You can also use spliterator even if you are not using parallel execution.

    Read more about Spliterator in Java here.

Related Topics

  1. Java Lambda Expressions Interview Questions And Answers
  2. Java Concurrency Interview Questions And Answers
  3. Java Multithreading Interview Questions And Answers
  4. Java Collections Interview Questions And Answers
  5. Java Exception Handling Interview Questions And Answers
  6. Java String Interview Questions And Answers
  7. Java OOP Interview Questions And Answers
  8. Core Java Basics Interview Questions And Answers

Wednesday, January 10, 2024

Angular ngClass Directive With Examples

Using Angular ngClass directive you can dynamically add or remove CSS classes for a DOM element.

With ngClass the CSS classes can be provided in one of the following ways-

  1. string- The CSS classes listed in the string (space delimited) are added.
     <some-element [ngClass]="'first second'">...</some-element>
    
  2. Array- The CSS classes declared as Array elements are added.
    <some-element [ngClass]="['first', 'second']">...</some-element>
    
  3. Object- As a key, value pair where keys are CSS classes and values are conditions. CSS classes get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.
    <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
    

Angular ngClass directive example

Here is a simple example showing usage of ngClass. First add a CSS class.

app.component.css

.text-border {
  color: white;
  border: 1px dashed black;
  background-color: blue;
}

Then in the template you can add <div> elements, one with value as true (so that CSS class is added) and one with value as false (so that CSS class is removed).

<div class="container">
  <div [ngClass]="{'text-border': false}">
    This text has no border
  </div>
  <div [ngClass]="{'text-border': true}">
    This text has border
  </div>
</div>
ngClass Directive

But you will see the real power of ngClass, just like with ngStyle directive, when the CSS class assignment happens dynamically.

Angular ngClass directive dynamic class assignment

In this example we’ll simulate a message for network transfer. There is a button “show status” that shows the current status of the network transfer. After few clicks if network transfer is still not done message is displayed in red color.

CSS used

.text-border {
  color: white;
  border: 1px dashed black;
  background-color: red;
}

Component class

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  temp = [];
  onButtonClick(){
    this.temp.push('Still transferring packet');
  }
}

Whenever button is clicked on the UI, onButtonClick() function is called which adds one more message to the array.

Template

<div class="container">
  <button class="btn btn-primary" (click)="onButtonClick()">
    Show Status
  </button>
  <div *ngFor="let t of temp; let i = index">
    <span [ngClass]="{'text-border' : i > 5}">{{t}}</span>
  </div>
</div>

In the template ngFor directive is used to iterate through the array of messages. Using ngClass directive CSS class ‘text-border’ is added dynamically when the iteration index is greater than 5.

Angular ngClass Directive

That's all for this topic Angular ngClass Directive With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Angular ngSwitch Directive With Examples
  2. Angular ngStyle Directive With Examples
  3. Angular ngIf Directive With Examples
  4. Angular @Component Decorator
  5. How to Install Node.js and NPM in Windows

You may also like-

  1. Angular First App - Hello world Example
  2. Passing Query Parameters in Angular Routing
  3. How to Create a Custom Observable in Angular
  4. Radio Button in Angular Form Example
  5. Unmodifiable or Immutable List in Java
  6. Initializer Block in Java
  7. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  8. Python Program to Display Armstrong Numbers

Tuesday, January 9, 2024

How HashMap Works Internally in Java

In this Java tutorial you'll learn how HashMap works internally in Java, which is also a favorite Java Collections interview question. Note that code snippets used here are from JDK 17.

There are four things you should know about HashMap before going into internal working of HashMap in Java-

  • HashMap works on the principal of hashing.
  • Map.Entry interface- This interface gives a map entry (key-value pair). HashMap in Java stores both key and value object, in bucket, as an object of Node class which implements this nested interface Map.Entry. Read more about Map.Entry interface here.
  • hashCode()- HashMap provides put(key, value) method for storing and get(key) method for retrieving values from HashMap. When put() method is used to store (Key, Value) pair, HashMap implementation calls hashcode on Key object to calculate a hash that is used to find a bucket where Entry object will be stored.
    When get() method is used to retrieve value, again key object (passed with the get() method) is used to calculate a hash which is then used to find a bucket where that particular key is stored.
  • equals()- equals() method is used to compare objects for equality. In case of HashMap key object is used for comparison, also using equals() method Map knows how to handle hashing collision (hashing collision means more than one key having the same hash value, thus assigned to the same bucket). In that case objects are stored in a linked list, refer figure for more clarity.
    Where hashCode() method helps in finding the bucket where that key is stored, equals() method helps in finding the right key as there may be more than one key-value pair stored in a single bucket.

** Bucket term used here is actually an index of array, that array is called table in HashMap implementation. Thus table[0] is referred as bucket0, table[1] as bucket1 and so on.


How elements are stored internally in Java HashMap

HassMap class in Java internally uses an array called table of type Node to store the elements which is defined in the HashMap class as-

transient Node<K,V>[] table;
Node is defined as a static class with in a Hashmap.
static class Node<K,V> implements Map.Entry<K,V> {
  final int hash;
  final K key;
  V value;
  Node<K,V> next;
  ..
  ..  
}

As you can see for each element four things are stored in the following fields-

  • hash- For storing Hashcode calculated using the key.
  • key- For holding key of the element.
  • value- For storing value of the element.
  • next- To store reference to the next node when a bucket has more than one element and a linkedlist is formed with in a bucket to store elements.

Following image shows how Node(key-value pair) objects are stored internally in table array of the HashMap class.

HashMap internal implementation in Java

Importance of hashCode() and equals() method in HashMap

How important it is to have a proper hash code and equals method can be seen through the help of the following program, explanation of this example will also help in understanding the working of HashMap's put()method (next section).

public class HashMapTest {
  public static void main(String[] args) {
    Map <Key, String> cityMap = new HashMap<Key, String>();
    cityMap.put(new Key(1, "NY"),"New York City" );
    cityMap.put(new Key(2, "ND"), "New Delhi");
    cityMap.put(new Key(3, "NW"), "Newark");
    cityMap.put(new Key(4, "NP"), "Newport");

    System.out.println("size before iteration " + cityMap.size());
    Iterator <Key> itr = cityMap.keySet().iterator();
    while (itr.hasNext()){
      System.out.println(cityMap.get(itr.next()));     
    }
    System.out.println("size after iteration " + cityMap.size());    
  }
}

// This class' object is used as key
// in the HashMap
class Key{
  int index;
  String Name;
  Key(int index, String Name){
    this.index = index;
    this.Name = Name;
  }
 
  @Override
  // A very bad implementation of hashcode
  // done here for illustrative purpose only 
  public int hashCode(){
    return 5;
  }
 
  @Override
  // A very bad implementation of equals
  // done here for illustrative purpose only 
  public boolean equals(Object obj){
    return true;
  }
}

Output

size before iteration 1
Newport
size after iteration 1

Refer Overriding hashCode() and equals() method in Java to know more about hashCode() and equals() methods.

How put() method of Java HashMap works internally

Lets get through the above example to see what is happening, this will also help in understanding how put() method of HashMap works internally.

Notice that I am inserting 4 values in the HashMap, still in the output it says size is 1 and iterating the map gives me the last inserted entry. Why is that? Answer lies in, how hashCode() and equals() method are implemented for the key Class. Have a look at the hashCode() method of the class Key which always returns "5" and the equals() method which is always returning "true".

When a value is put into HashMap it calculates a hash using key object and for that it uses the hashCode() method of the key object class (or its parent class). Based on the calculated hash value HashMap implementation decides which bucket should store the particular Entry object.

In my code the hashCode() method of the key class always returns "5". This effectively means, calculated hash value, is same for all the entries inserted in the HashMap. Thus all the entries are stored in the same bucket.

HashMap implementation uses equals() method to see if the key is equal to any of the already inserted keys (Recall that there may be more than one entry in the same bucket). Note that, with in a bucket key-value pair entries (Entry objects) are stored in a linked-list (Refer figure for more clarity). In case hash is same, but equals() returns false (which essentially means more than one key having the same hash or hash collision) Entry objects are stored, with in the same bucket, in a linked-list.

In my code, I am always returning true for equals() method so the HashMap implementation "thinks" that the keys are equal and overwrites the value. So, in a way using hashCode() and equals() I have "tricked" HashMap implementation to think that all the keys (even though different) are same, thus overwriting the values.

In a nutshell there are three steps in the internal implementation of HashMap put() method-

  • Using hashCode() method, hash value will be calculated. In which bucket particular entry will be stored is ascertained using that hash.
  • equals() method is used to find if such a key already exists in that bucket, if not found then a new node is created with the map entry and stored within the same bucket. A linked-list is used to store those nodes.
  • If equals() method returns true, it means that the key already exists in the bucket. In that case, the new value will overwrite the old value for the matched key.

How Java HashMap get() method works internally

As we already know how Entry objects are stored in a bucket and what happens in the case of Hash Collision it is easy to understand what happens when key object is passed in the get() method of the HashMap to retrieve a value.

Using the key (passed in the get() method) hash value will be calculated to determine the bucket where that Entry object is stored, in case there are more than one Entry object with in the same bucket (stored as a linked-list) equals() method will be used to find out the correct key. As soon as the matching key is found get() method will return the value object stored in the Entry object.

When null Key is inserted in a HashMap

HashMap in Java also allows null as key, though there can only be one null key in HashMap. While storing the Entry object HashMap implementation checks if the key is null, in case key is null, it is always mapped to bucket 0, as hash is not calculated for null keys.

HashMap implementation changes in Java 8

Though HashMap implementation in Java provides constant time performance O(1) for get() and put() methods but that is in the ideal case when the Hash function distributes the objects evenly among the buckets.

But the performance may worsen in the case hashCode() used is not proper and there are lots of hash collisions. As we know now that in case of hash collision entry objects are stored as a node in a linked-list and equals() method is used to compare keys. That comparison to find the correct key with in a linked-list is a linear operation so in a worst case scenario the complexity becomes O(n).

To address this issue in Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached. Which means HashMap starts with storing Entry objects in linked list but after the number of items in a hash becomes larger than a certain threshold, the hash changes from using a linked list to a balanced tree, this improves the worst case performance from O(n) to O(log n).

Points to note-

  • HashMap works on the principal of hashing.
  • HashMap in Java uses the hashCode() method to calculate a hash value. Hash value is calculated using the key object. This hash value is used to find the correct bucket where Entry object will be stored.
  • HashMap uses the equals() method to find the correct key whose value is to be retrieved in case of get() and to find if that key already exists or not in case of put().
  • With in the internal implementation of HashMap hashing collision means more than one key having the same hash value, in that case Entry objects are stored as a linked-list with in a same bucket.
  • With in a bucket values are stored as Entry objects which contain both key and value.
  • In Java 8 hash elements use balanced trees instead of linked lists after a certain threshold is reached while storing values. This improves the worst case performance from O(n) to O(log n).

That's all for this topic How HashMap Works Internally in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How LinkedList Class Works Internally in Java
  3. How HashSet Works Internally in Java
  4. How to Loop Through a Map in Java
  5. ConcurrentHashMap in Java With Examples

You may also like-

  1. strictfp in Java
  2. Constructor Chaining in Java
  3. Interface Static Methods in Java
  4. Method reference in Java 8
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Try-With-Resources in Java With Examples
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Count Number of Times Each Character Appears in a String Java Program

Monday, January 8, 2024

Benefits, Disadvantages And Limitations of Autowiring in Spring

Though autowiring in Spring makes life easy by wiring the dependencies automatically thus requiring less code to write but at the same time there are few limitations and disadvantages of autowiring in Spring too and that is the topic of this post.

Benefits of autowiring

  1. Using autowiring means you don't need to explicitly wire the bean properties, Spring will do it automatically. So autowiring requires less configuration code.
  2. Provides several modes for autowiring like byName, byType, constructor. So you have the flexibility to choose how you want to autowire the dependencies.

Disadvantages of autowiring in Spring

  1. Explicit wiring has an advantage that you can explicitly wire the bean you want but Autowiring is not that exact. For example, if you are using constructor autowiring and there is not exactly one bean of the constructor argument type in the container then Spring won't be able to determine which of those beans has to be wired. In case of ambiguity Spring autowiring won't try to guess instead it throws an exception.
  2. Wiring information may not be available to tools that may generate documentation from a Spring container.
  3. Within the container there may be multiple bean definitions matching the type specified by the setter method or constructor argument to be autowired. Within the container there may be multiple bean definitions matching the type specified by the setter method or constructor argument to be autowired. In that case Spring won't be able to decide which bean to use for autowiring. If no unique bean definition is available, an exception is thrown.

Limitations of autowiring

  1. Explicit dependencies in property and constructor-arg settings always override autowiring.
  2. You cannot autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). This limitation in autowiring is by-design.

Reference- https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html

That's all for this topic Benefits, Disadvantages And Limitations of Autowiring in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Autowiring in Spring Using XML Configuration
  2. Spring Component Scan to Automatically Discover Beans
  3. Excluding Bean From Autowiring in Spring
  4. @Resource Annotation in Spring Autowiring
  5. How to Inject Null And Empty String Values in Spring

You may also like-

  1. Bean Definition Inheritance in Spring
  2. Spring JdbcTemplate Select Query Example
  3. BeanFactoryAware Interface in Spring Framework
  4. How to Create Password Protected Zip File in Java
  5. static Block in Java
  6. Transient Keyword in Java With Examples
  7. Volatile Keyword in Java With Examples
  8. Difference Between CountDownLatch And CyclicBarrier in Java

Sunday, January 7, 2024

Java Basics Tutorial

Java, one of the most popular programming language, was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It was publicly released in 1995.

Java is an object oriented, high level language but what sets it apart is that Java is platform independent and it can run on a variety of platforms.

This Java beginners tutorial helps in understanding the basic concepts of Java programming language.

Java Getting Started

  1. How to Install Java in Ubuntu
  2. First Java Program - Hello World Java Program
  3. Primitive Data Types in Java
  4. Java Variable Types With Examples
  5. Literals in Java
  6. What Are JVM, JRE And JDK in Java
  7. Java is a Strongly Typed Language

Operators in Java

  1. Arithmetic And Unary Operators in Java
  2. Equality And Relational Operators in Java
  3. Conditional Operators in Java With Examples
  4. Ternary Operator in Java With Examples
  5. instanceof Operator in Java With Examples
  6. Difference Between equals() Method And equality Operator == in Java

Conditional Statements & Loops in Java

  1. if else Statement in Java With Examples
  2. Switch Case Statement in Java With Examples
  3. Switch Expressions in Java 12
  4. Java for Loop With Examples
  5. Java while Loop With Examples
  6. Java do-while Loop With Examples
  7. break Statement in Java With Examples
  8. continue Statement in Java With Examples
  9. return Statement in Java With Examples

Java Class And Object

  1. Class in Java
  2. Object in Java
  3. Object Creation Using new Operator in Java
  4. Object class in Java
  5. Type Wrapper Classes in Java
  6. Java Abstract Class and Abstract Method
  7. Java Nested Class And Inner Class
  8. Java Object Cloning - clone() Method
  9. Shallow Copy And Deep Copy in Java Object Cloning

Java Constructor

  1. Constructor in Java
  2. Constructor Chaining in Java
  3. Constructor Overloading in Java
  4. Initializer Block in Java

Java Basics

  1. Access Modifiers in Java - Public, Private, Protected and Default
  2. Package in Java
  3. Java Automatic Numeric Type Promotion
  4. Why Class Name And File Name Should be Same in Java
  5. Why main Method static in Java
  6. Java Pass by Value or Pass by Reference
  7. Java - Could not find or load main class error Fix
  8. this Keyword in Java With Examples
  9. super Keyword in Java With Examples
  10. final Keyword in Java With Examples
  11. strictfp in Java
  12. finalize() Method in Java
  13. Type Casting in Java With Conversion Examples
  14. Why no Multiple Inheritance in Java

static in Java

  1. static Keyword in Java With Examples
  2. static Method Overloading or Overriding in Java
  3. static Import in Java With Examples
  4. static Reference to The Non-static Method or Field Error
  5. static Block in Java

Array in Java

  1. Array in Java With Examples

Java Math

  1. BigDecimal in Java With Examples
  2. BigInteger in Java With Examples

OOPS Concepts

  1. Encapsulation in Java
  2. Polymorphism in Java
  3. Abstraction in Java
  4. Inheritance in Java
  5. Difference Between Encapsulation And Abstraction in Java
  6. Method Overloading in Java
  7. Method Overriding in Java
  8. Association, Aggregation And Composition in Java

Interface in Java

  1. Interface in Java With Examples
  2. Marker Interface in Java
  3. Difference Between Abstract Class And Interface in Java
  4. Interface Default Methods in Java
  5. Interface Static Methods in Java
  6. Private Methods in Java Interface

String in Java

  1. String in Java Tutorial
  2. String Pool in Java
  3. Why Java String is Immutable
  4. Compact Strings in Java
  5. Check String Null or Empty in Java
  6. String Comparison in Java - compareTo(), equals()
  7. Java String charAt() Method With Examples
  8. Java String substring() Method - Getting Substring
  9. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  10. Java trim(), strip() - Removing Spaces From String
  11. Java split() Method - Splitting a String
  12. Java join() Method - Joining Strings
  13. intern() Method in Java String
  14. matches() method in Java String
  15. StringJoiner Class in Java With Examples
  16. StringBuffer Class in Java With Examples
  17. StringBuilder Class in Java With Examples
  18. String Vs StringBuffer Vs StringBuilder in Java
  19. Is String Thread Safe in Java
  20. How to Create Immutable Class in Java

Java Exception handling

  1. Java Exception Handling Tutorial
  2. try-catch Block in Java Exception Handling
  3. finally Block in Java Exception Handling
  4. Multiple Catch Blocks in Java Exception Handling
  5. Nested Try Statements in Java Exception Handling
  6. throw Statement in Java Exception Handling
  7. throws Keyword in Java Exception Handling
  8. Exception Propagation in Java Exception Handling
  9. Java Exception Handling And Method Overriding
  10. Difference Between Checked And Unchecked Exceptions in Java
  11. Difference Between throw And throws in Java
  12. final Vs finally Vs finalize in Java
  13. Creating Custom Exception Class in Java
  14. Multi-Catch Statement in Java Exception Handling
  15. Try-With-Resources in Java With Examples
  16. Best Practices For Exception Handling in Java
  17. java.lang.ClassNotFoundException - Resolving ClassNotFoundException in Java
  18. java.lang.ClassCastException - Resolving ClassCastException in Java
  19. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  20. Difference Between StackOverflowError and OutOfMemoryError in Java

Java Advanced Topics

Java Collection Framework

List
  1. ArrayList in Java With Examples
  2. How ArrayList Works Internally in Java
  3. Unmodifiable or Immutable List in Java
  4. How to Loop or Iterate an Arraylist in Java
  5. ListIterator in Java
  6. How to Join Lists in Java
  7. How to Remove Elements From an ArrayList in Java
  8. How to Remove Duplicate Elements From an ArrayList in Java
  9. How to Sort ArrayList in Java
  10. How to Sort ArrayList of Custom Objects in Java
  11. How to Sort an ArrayList in Descending Order in Java
  12. How and Why to Synchronize ArrayList in Java
  13. How to Convert ArrayList to Array in Java
  14. How to Convert Array to ArrayList in Java
  15. How LinkedList Class Works Internally in Java
  16. Difference Between ArrayList And LinkedList in Java
  17. Difference Between ArrayList And Vector in Java
  18. Difference Between Array And ArrayList in Java
  19. Difference Between ArrayList And CopyOnWriteArrayList in Java
Map
  1. HashMap in Java With Examples
  2. How HashMap Works Internally in Java
  3. Map.Entry Interface in Java
  4. Unmodifiable or Immutable Map in Java
  5. How to Loop Through a Map in Java
  6. How to Sort a HashMap in Java
  7. How to Remove Entry From HashMap in Java
  8. LinkedHashMap in Java With Examples
  9. TreeMap in Java With Examples
  10. Difference Between HashMap And Hashtable in Java
  11. HashMap Vs LinkedHashMap Vs TreeMap in Java
  12. Difference Between HashMap And ConcurrentHashMap in Java
  13. Java Map compute() With Examples
  14. Java Map computeIfPresent() With Examples
  15. Java Map computeIfAbsent() With Examples
  16. Java Map containsKey() - Check if Key Exists in Map
  17. Java Map containsValue() - Check if Value Exists in Map
  18. Java Map getOrDefault() Method With Examples
  19. Java Map merge() With Examples
  20. Java Map putIfAbsent() With Examples
  21. Java Map replace() With Examples
  22. Java Map size() With Examples
Set
  1. HashSet in Java With Examples
  2. How HashSet Works Internally in Java
  3. Unmodifiable or Immutable Set in Java
  4. How to Loop Through HashSet in Java
  5. LinkedHashSet in Java With Examples
  6. TreeSet in Java With Examples
  7. EnumSet in Java With Examples
  8. How to Sort HashSet in Java
  9. HashSet Vs LinkedHashSet Vs TreeSet in Java
  10. How to Sort Elements in Different Order in TreeSet
General
  1. equals() And hashCode() Methods in Java
  2. Fail-Fast Vs Fail-Safe Iterator in Java
  3. Difference Between Comparable and Comparator in Java
  4. removeIf() Method in Java Collection With Examples
Java Collections Interview Questions
  1. Java Collections Interview Questions And Answers

Java Concurrent utilities

Synchronization utilities
  1. Java CountDownLatch With Examples
  2. Java CyclicBarrier With Examples
  3. Difference Between CountDownLatch And CyclicBarrier in Java
  4. Java Phaser With Examples
  5. Java Exchanger With Examples
  6. Java Semaphore With Examples
Locks
  1. Java ReentrantLock With Examples
  2. Difference Between ReentrantLock And Synchronized in Java
  3. Java ReentrantReadWriteLock With Examples
  4. Java StampedLock With Examples
Concurrent Collections
  1. ConcurrentHashMap in Java With Examples
  2. Difference Between HashMap And ConcurrentHashMap in Java
  3. CopyOnWriteArrayList in Java With Examples
  4. Difference Between ArrayList And CopyOnWriteArrayList in Java
  5. CopyOnWriteArraySet in Java With Examples
  6. ConcurrentSkipListMap in Java With Examples
  7. ConcurrentSkipListSet in Java With Examples
  8. ConcurrentLinkedQueue in Java With Examples
  9. ConcurrentLinkedDeque in Java With Examples
BlockingQueue
  1. Java BlockingQueue With Examples
  2. Java ArrayBlockingQueue With Examples
  3. Java LinkedBlockingQueue With Examples
  4. Java PriorityBlockingQueue With Examples
  5. Java SynchronousQueue With Examples
  6. Java DelayQueue With Examples
  7. Java LinkedTransferQueue With Examples
BlockingDeque
  1. Java BlockingDeque With Examples
  2. Java LinkedBlockingDeque With Examples
Executors
  1. Callable and Future in Java With Examples
  2. Difference Between Runnable And Callable in Java
  3. Executor And ExecutorService in Java With Examples
  4. Java ThreadPoolExecutor - Thread Pooling With ExecutorService
  5. Java ScheduledThreadPoolExecutor - Task Scheduling in Java
  6. CompletableFuture in Java With Examples
Atomic variables
  1. AtomicInteger in Java With Examples
  2. AtomicLong in Java With Examples
Concurrency concepts
  1. Lock Striping in Java Concurrency
  2. Non-Blocking Algorithms
  3. Busy Spinning in Multi-Threading
  4. Blocking Methods in Java Concurrency
Java Concurrency Interview Questions
  1. Java Concurrency Interview Questions And Answers

Reflection API in Java

  1. Java Reflection API Tutorial
  2. Reflection in Java - Getting Class Information
  3. Reflection in Java - Getting Field Information
  4. Reflection in Java - Getting Method Information
  5. Reflection in Java - Getting Constructor Information
  6. Reflection in Java - Array
  7. Generating Getters And Setters Using Reflection - Java Program
  8. Invoking Getters And Setters Using Reflection - Java Program
  9. Invoke Method at Runtime Using Java Reflection API

Java-JDBC

  1. JDBC Tutorial - Java JDBC Overview
  2. Types of JDBC Drivers
  3. Java JDBC Steps to Connect to DB
  4. Connection Interface in Java-JDBC
  5. Statement Interface in Java-JDBC
  6. ResultSet Interface in Java-JDBC
  7. PreparedStatement Interface in Java-JDBC
  8. CallableStatement Interface in Java-JDBC
  9. DataSource in Java-JDBC
  10. DatabaseMetaData Interface in Java-JDBC
  11. Transaction Management in Java-JDBC
  12. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  13. How to Get The Inserted ID (Generated ID) in JDBC

Serialization in Java

  1. Serialization and Deserialization in Java
  2. Transient Keyword in Java With Examples
  3. Externalizable Interface in Java
  4. SerialVersionUID And Versioning in Java Serialization
  5. Serialization Proxy Pattern in Java

Java Multi-Threading

  1. Java Multithreading Tutorial
  2. Creating a Thread in Java
  3. Thread States (Thread Life Cycle) in Java Multi-Threading
  4. Thread Priority in Java Multi-Threading
  5. Difference Between Thread And Process in Java
  6. Main Thread in Java
  7. Can we Start The Same Thread Twice in Java
  8. What if run() Method Called Directly Instead of start() Method - Java Multi-Threading
  9. Synchronization in Java - Synchronized Method And Block
  10. Static Synchronization in Java Multi-Threading
  11. Race Condition in Java Multi-Threading
  12. Deadlock in Java Multi-Threading
  13. Thread Starvation in Java Multi-Threading
  14. Livelock in Java Multi-Threading
  15. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  16. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  17. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  18. isAlive() And join() Methods in Java Multi-Threading
  19. Difference Between yield And sleep in Java Multi-Threading
  20. Difference Between sleep And wait in Java Multi-Threading
  21. Java ThreadLocal Class With Examples
  22. Volatile Keyword in Java With Examples
  23. Virtual Threads in Java
  24. String And Thread-Safety in Java
Java Multi-Threading Interview Questions
  1. Java Multithreading Interview Questions And Answers

Java 5 Features

  1. Varargs (Variable-length Arguments) in Java
  2. Enum Type in Java
  3. AutoBoxing And UnBoxing in Java
  4. Covariant Return Type in Java

Generics in Java

  1. Generics in Java
  2. Generic Class, Interface And Generic Method in Java
  3. Bounded Type Parameter in Java Generics
  4. Wildcard in Java Generics
  5. Type Erasure in Java Generics

Java 8 Features

  1. Interface Default Methods in Java 8
  2. Interface Static Methods in Java 8
  3. New Date And Time API in Java 8
  4. Optional Class in Java With Examples
  5. Effectively Final in Java 8
  6. forEach Statement in Java 8
  7. PermGen Space Removal in Java 8
  8. StringJoiner Class in Java 8

Lambda Expressions - Java 8

  1. Lambda Expressions in Java 8
  2. Lambda Expression Examples in Java
  3. Functional Interfaces in Java
  4. @FunctionalInterface Annotation in Java
  5. Pre-defined Functional Interfaces in Java
  6. Java Lambda Expression as Method Parameter
  7. Java Lambda Expression And Variable Scope
  8. Exception Handling in Java Lambda Expressions
  9. Method Reference in Java
  10. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  11. How to Resolve Local Variable Defined in an Enclosing Scope Must be Final or Effectively Final Error

Stream API - Java 8

  1. Java Stream API Tutorial
  2. Java Stream API Examples
  3. Primitive Type Streams in Java Stream API
  4. Parallel Stream in Java Stream API
  5. Reduction Operations in Java Stream API
  6. Map Operation in Java Stream API
  7. collect() Method And Collectors Class in Java Stream API
  8. Java Stream - allMatch() With Examples
  9. Java Stream - anyMatch() With Examples
  10. Java Stream - boxed() With Examples
  11. Java Stream - concat() With Examples
  12. Java Stream - count() With Examples
  13. Java Stream - Collectors.groupingBy() With Examples
  14. Java Stream - Collectors.joining() With Examples
  15. Java Stream - Collectors.partitioningBy() With Examples
  16. Java Stream - Collectors.summingInt(), summingLong(), summingDouble()
  17. Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble()
  18. Java Stream - Collectors.teeing() With Examples
  19. Java Stream - distinct() With Examples
  20. Java Stream - filter() With Examples
  21. Java Stream - findAny() With Examples
  22. Java Stream - findFirst() With Examples
  23. Java Stream - flatMap() With Examples
  24. Java Stream - limit() With Examples
  25. Java Stream - max() With Examples
  26. Java Stream - min() With Examples
  27. Java Stream - noneMatch() With Examples
  28. Java Stream - peek() With Examples
  29. Java Stream - skip() With Examples
  30. Java Stream - sorted() With Examples
  31. Java Stream - Convert Stream to List
  32. Java Stream - Convert Stream to Set
  33. Java Stream - Convert Stream to Map
  34. Java Stream - Convert Stream to Array
  35. Spliterator in Java

Java 9 Features

  1. JShell in Java With Examples
  2. Private Methods in Java Interface

Java 10 Features

  1. Var type in Java - Local Variable Type Inference

Java 16 Features

  1. Java Record Class With Examples

Java 17 Features

  1. Java Sealed Classes and Interfaces

Eclipse IDE

  1. How to Pass Command Line Arguments in Eclipse
  2. Creating a Maven Project in Eclipse
  3. Adding Tomcat Server to Eclipse

Java Internals

  1. Just In Time Compiler (JIT) in Java
  2. JVM Run-Time Data Areas - Java Memory Allocation
  3. Heap Memory Allocation in Java
  4. Garbage Collection in Java
  5. PermGen Space Removal in Java 8

Java IO

  1. Byte Streams in Java IO
  2. Character Streams in Java IO
  3. Buffered Streams in Java IO
  4. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  5. Java BufferedReader Class With Examples
  6. Java BufferedWriter Class With Examples
  7. Fix Scanner.nextLine() Skipping Input After Another next Methods