Top 10 Books to Learn Java

For Freshers / Beginners :

1. Head First Java Current Edition : 2nd  by Kathy Sierra

https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208

2. Clean Code by Robert C. Martin

https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

3. Java the Complete Reference Eleventh Edition  by Herbert Schildt

https://www.amazon.com/Java-Complete-Reference-Eleventh/dp/1260440230

4. Java Concurrency in Practice by Brain Goetz

https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601

5.  Effective Java by Joshua Bloch

https://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683


For Experienced Java Professionals:


6. Java A Beginner's Guide Eigth Edition by Herbert Schildt

https://www.amazon.com/Java-Beginners-Eighth-Herbert-Schildt/dp/1260440214

7.  Java Performance Definitive Guide  by Scott Oaks

https://www.amazon.com/Java-Performance-Definitive-Guide-Getting/dp/1449358454

8. Spring in action by Craig Walls 5th edition

https://www.amazon.com/Spring-Action-Craig-Walls/dp/1617294942

9.  Test Driven : TDD and Acceptance TDD for Java Developers 1st Edition

https://www.amazon.com/Test-Driven-Acceptance-Java-Developers/dp/1932394850

10. Mastering Java Machine Learning



https://www.amazon.com/Mastering-Java-Machine-Learning-architectures-ebook/dp/B01KOG6SW8














LeetCode - Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Example:
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

Java Solution:
class MovingAverage {

    /** Initialize your data structure here. */
    private Queue<Integer> q;
    private double sum;
    private int maxSize;
    public MovingAverage(Integer size) {
        q = new LinkedList<Integer>();
        maxSize = size;
        sum = 0;
    }
    
    public double next(int val) {
        if(q.size() != maxSize){
            q.offer(val);
            sum+=val;
            return sum / q.size();
        }else{
            sum-=q.peek(); // subtracting from sum before removing the first element
            q.poll();
            q.offer(val);
            sum+=val;
            return sum / q.size();
        }
    }
}

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */

Java - Concurrency / Threads


What is a Process in Concurrency / Threads ?

A process is a Unit of Execution that has it's own memory space.

When ever we run an application , we are starting a new process . 

Example : Running a Java FX application.
                 Running any Java console applications .  Nothing but we are starting a new process .

Each instance  of Java Virtual machine runs as a process (For most of them).


When ever two applications or process's are running , they have their own memory space or heap .

Applications or process's never share the memory / heap between them.

Thread :

What is a Thread ?

Thread is a Unit of Execution with in a Process . 

A process can have multiple threads .  Default in Java we have at least one thread called main thread.

For UI we have JavaFX application thread.

Our code runs in main thread or JavaFX app thread (UI) or threads that are explicitly provided by us.

Every Java application / process has multiple threads like memory management , Input / Output operations (I/O operations) .  Which we don't create , provided by java itself.

Unlike process's , threads can share files and memory of it's process / application.

In addition to process's memory thread has it's own memory called thread stack which can't be shared to other thread. Only that particular thread can access it's thread stack.


                                           Application runs as a  Process -> Heap Memory

                                                            Thread -> Thread Stack

                                                                          ->  Thread 1
                                                           Process   ->  Thread 2
                                                                           ->   Thread 3


Can't we run our entire application in one single thread as how we are running our application as a single process ?

Consider a scenario that you a fetching some data from an application . Where the application has several databases and also some information that it fetches from internet .

If we execute entire data fetching from all databases and internet in one main thread it will take more time or more latency because it act's in a linear fashion . User's of application may think app is down or got stuck by the time response is provided by main thread.

Using multiple threads , each thread will work on different databases and one thread will fetch data from internet and in the mean while main thread can provide status updates to user.

Finally all information can be collated and end result can be  displayed to User.

Example : you are watching a movie and parallelly downloading a file . Both are two tasks / threads running in parallel.


Java provides thread related classes to achieve concurrency .

Threads execution will depend on JVM and operating system on which they are running.











Java 8 Tutorial and Examples

Java 8 Introduction

Java 8 is the major feature release of  Java Programming language .

Java 8 released in  March 18 , 2014.

Reference :

https://en.wikipedia.org/wiki/Java_version_history

With Java 8 Release . Java provided support for various new features as below.


  • Functional Programming
  • New API's for date time manipulation
  • New Java script engine
  • Streaming API's

Features of Java 8 :


Lambda Expression :

Added Functional processing capability to java. Which means treating functionality as a method argument or treating code as data.

Method References:

Treating functions as parameters .  Referencing functions with their names instead of  invoking or calling them directly.

Nashorn , Javascript Engine :

New java script engine to execute java Script Code.

Date Time API:


New set of packages added that provide additional features and functions.


Stream API:

The Stream API is integrated into the Collections API.

Stream API helps for bulk operations on collections . Like sequential or parallel map-reduce transformations.

Default Method:

Interfaces can have default methods . Default methods can be implemented.

Optional :

This feature is to handle null value properties.

Java FX , Security , Collections many other updates and improvements has been done for new version of Java 8 .

Reference :














Sorting - Introduction


In general in Computers more than 25% of run time is taken for sorting .

Sometimes  the Computing time for sorting is more than 50% for some installations.


- Above details mentioned by Donald  Kuth in The Art Of Computer Programming Vol 3







Top Ten Programming Languages In 2020

1. Python
2. Java
3. JavaScript
4. C and C++
5. Golang

6. R
7. Kotlin
8. C#

 9. Swift

10. PHP

Top 10 most Popular skills of 2020

1.  Python 

2. React (Web)

3. Angular


< 4. Machine Learning

5. Docker


< 6.Django

7. CompTia

8.Amazon AWS

9.Deep Learning


< 10.React Native(mobile)

Top Ten Technologies to Learn In 2020



Artificial Intelligence

5g

Cloud Computing

NLP and Voice Technology


< Block Chain

Internet Of Things

Quantum Computing

RPA

AR and VR 


< Wireless Power Transfer



LeetCode - Fizz Buzz

Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]
Java Solution :
class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> resultList = new ArrayList<String>();
        for(int i = 1 ; i <= n ; i++){
            if(i%3 == 0 && i%5 == 0)
                resultList.add("FizzBuzz");
            else if(i%3 == 0)
                resultList.add("Fizz");
            else if(i%5==0)
                resultList.add("Buzz");
            else
                resultList.add(Integer.toString(i));
        }
            return resultList;
        }
    
}

LeetCode - Contains Duplicate

Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
Java Solution :
class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();
        for(int i : nums){
            if(set.contains(i))
                return true;
            else
                set.add(i);
        }
        return false;
    }
}

LeetCode - Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Java Solution :
class Solution {
    public int trap(int[] height) {
        int[] leftMax = new int[height.length];
        int[] rightMax = new int[height.length];
        int waterCollected = 0;
        if(height == null || height.length == 0)
            return 0;
        // scan from left to right
        leftMax[0] = height[0];
        int max = leftMax[0];
        for(int i =1 ;i < height.length; i++){
            if(height[i] >= max){
                max = height[i];
                leftMax[i] = max;
            } else{
                leftMax[i] = max;
            }
        }
        
        // scan from right to left
        rightMax[height.length-1] = height[height.length-1];
        int mr = rightMax[height.length-1];
        for(int i = height.length-2; i >= 0 ; i--){
            if(height[i] >= mr){
                mr = height[i];
                rightMax[i] = mr;
            } else{
                rightMax[i] = mr;
            }
        }
        
        for(int i = 0 ;i < height.length; i++){
            waterCollected += Math.min(leftMax[i],rightMax[i]) - height[i];
        }
        
        return waterCollected;
    }
}

Design a Tic-tac-toe game Leetcode

Design a Tic-tac-toe game that is played between two players on a n x n grid.
You may assume the following rules:
  1. A move is guaranteed to be valid and is placed on an empty block.
  2. Once a winning condition is reached, no more moves is allowed.
  3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
Example:
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.

TicTacToe toe = new TicTacToe(3);

toe.move(0, 0, 1); -> Returns 0 (no one wins)
|X| | |
| | | |    // Player 1 makes a move at (0, 0).
| | | |

toe.move(0, 2, 2); -> Returns 0 (no one wins)
|X| |O|
| | | |    // Player 2 makes a move at (0, 2).
| | | |

toe.move(2, 2, 1); -> Returns 0 (no one wins)
|X| |O|
| | | |    // Player 1 makes a move at (2, 2).
| | |X|

toe.move(1, 1, 2); -> Returns 0 (no one wins)
|X| |O|
| |O| |    // Player 2 makes a move at (1, 1).
| | |X|

toe.move(2, 0, 1); -> Returns 0 (no one wins)
|X| |O|
| |O| |    // Player 1 makes a move at (2, 0).
|X| |X|

toe.move(1, 0, 2); -> Returns 0 (no one wins)
|X| |O|
|O|O| |    // Player 2 makes a move at (1, 0).
|X| |X|

toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
|X| |O|
|O|O| |    // Player 1 makes a move at (2, 1).
|X|X|X|
Follow up:
Could you do better than O(n2) per move() operation?
Java Solution :
class TicTacToe {
        int[] rowCounter;
        int[] colCounter;
        int diagLeft;
        int diagRight;
        int n;
    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        this.n = n;
         rowCounter = new int[n];
         colCounter = new int[n];
         diagLeft = 0;
         diagRight = 0;
    }
    
    /** Player {player} makes a move at ({row}, {col}).
        @param row The row of the board.
        @param col The column of the board.
        @param player The player, can be either 1 or 2.
        @return The current winning condition, can be either:
                0: No one wins.
                1: Player 1 wins.
                2: Player 2 wins. */
    public int move(int row, int col, int player) {
        int move = (player == 1) ? 1 : -1;
        rowCounter[row] +=move;
        colCounter[col] +=move;
        if(row == col)
            diagLeft +=move;
        if(row == n-col-1)
            diagRight +=move;
        if(rowCounter[row] == n || diagLeft == n || diagRight== n || colCounter[col] == n)
            return 1;
        else if(rowCounter[row] == -n || diagLeft == -n || diagRight== -n || colCounter[col] == -n)return 2;
        else
            return 0; 
    }
}

/**
 * Your TicTacToe object will be instantiated and called as such:
 * TicTacToe obj = new TicTacToe(n);
 * int param_1 = obj.move(row,col,player);
 */

LeetCode - Design Tic-Tac-Toe

Design a Tic-tac-toe game that is played between two players on a n x n grid.
You may assume the following rules:
  1. A move is guaranteed to be valid and is placed on an empty block.
  2. Once a winning condition is reached, no more moves is allowed.
  3. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
Example:
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.

TicTacToe toe = new TicTacToe(3);

toe.move(0, 0, 1); -> Returns 0 (no one wins)
|X| | |
| | | |    // Player 1 makes a move at (0, 0).
| | | |

toe.move(0, 2, 2); -> Returns 0 (no one wins)
|X| |O|
| | | |    // Player 2 makes a move at (0, 2).
| | | |

toe.move(2, 2, 1); -> Returns 0 (no one wins)
|X| |O|
| | | |    // Player 1 makes a move at (2, 2).
| | |X|

toe.move(1, 1, 2); -> Returns 0 (no one wins)
|X| |O|
| |O| |    // Player 2 makes a move at (1, 1).
| | |X|

toe.move(2, 0, 1); -> Returns 0 (no one wins)
|X| |O|
| |O| |    // Player 1 makes a move at (2, 0).
|X| |X|

toe.move(1, 0, 2); -> Returns 0 (no one wins)
|X| |O|
|O|O| |    // Player 2 makes a move at (1, 0).
|X| |X|

toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
|X| |O|
|O|O| |    // Player 1 makes a move at (2, 1).
|X|X|X|
Follow up:
Could you do better than O(n2) per move() operation?
Java Solution :
class TicTacToe {
        int[] rowCounter;
        int[] colCounter;
        int diagLeft;
        int diagRight;
        int n;
    /** Initialize your data structure here. */
    public TicTacToe(int n) {
        this.n = n;
         rowCounter = new int[n];
         colCounter = new int[n];
         diagLeft = 0;
         diagRight = 0;
    }
    
    /** Player {player} makes a move at ({row}, {col}).
        @param row The row of the board.
        @param col The column of the board.
        @param player The player, can be either 1 or 2.
        @return The current winning condition, can be either:
                0: No one wins.
                1: Player 1 wins.
                2: Player 2 wins. */
    public int move(int row, int col, int player) {
        int move = (player == 1) ? 1 : -1;
        rowCounter[row] +=move;
        colCounter[col] +=move;
        if(row == col)
            diagLeft +=move;
        if(row == n-col-1)
            diagRight +=move;
        if(rowCounter[row] == n || diagLeft == n || diagRight== n || colCounter[col] == n)
            return 1;
        else if(rowCounter[row] == -n || diagLeft == -n || diagRight== -n || colCounter[col] == -n)return 2;
        else
            return 0; 
    }
}

/**
 * Your TicTacToe object will be instantiated and called as such:
 * TicTacToe obj = new TicTacToe(n);
 * int param_1 = obj.move(row,col,player);
 */

LeetCode - K Closest Points to Origin

We have a list of points on the plane.  Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.)

Example 1:
Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation: 
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].
Example 2:
Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)

Note:
  1. 1 <= K <= points.length <= 10000
  2. -10000 < points[i][0] < 10000
  3. -10000 < points[i][1] < 10000
Java Solution :
class Solution {
    public int[][] kClosest(int[][] points, int K) {
 PriorityQueue<int[]> maxHeap = new PriorityQueue<>(Comparator.comparing(a -> -a[0] * a[0] - a[1] * a[1]));        
        for(int[] point : points){
            maxHeap.add(point);
            if(maxHeap.size() > K)
                maxHeap.remove();
        }
        
        int[][] result = new int[K][2];
       
        while(K-- > 0){
            result[K] = maxHeap.poll();
        }
        
        return result;
    }
}

LeetCode - Grouped Anagrams

Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note:
  • All inputs will be in lowercase.
  • The order of your output does not matter.
Java Solution :
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> groupedAnagrams = new ArrayList<>();
        HashMap<String , List<String>> map = new HashMap<>();
        
        for(String s : strs){
            char[] charArray = s.toCharArray();
            Arrays.sort(charArray);
            String sortedString = new String(charArray);
            if(!map.containsKey(sortedString)){
                map.put(sortedString,new ArrayList<String>());
            }
            map.get(sortedString).add(s);
        }
         groupedAnagrams.addAll(map.values());
        return groupedAnagrams;
    }
}

LeetCode - Meeting Rooms II

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
Java Solution :
class Solution {
    public int minMeetingRooms(int[][] intervals) {
        Arrays.sort(intervals,(a,b)-> a[0] - b[0]);
        int numOfMeetingRooms = 0;
PriorityQueue<Integer> minHeap = new PriorityQueue<>();        
        for(int[] interval : intervals){
            if(minHeap.isEmpty()){
                minHeap.offer(interval[1]);
                numOfMeetingRooms++;
            }else if(minHeap.peek() <= interval[0]){
                minHeap.poll();
                minHeap.offer(interval[1]);
            }else{
                minHeap.offer(interval[1]);
                numOfMeetingRooms++;
            }
        }
       return numOfMeetingRooms;
    }
}

LeetCode - Merge K Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
Java Solution:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for(ListNode head : lists){
            while(head !=null){
            minHeap.add(head.val);
            head = head.next;
        }
        }
            ListNode dummy = new ListNode(-1);
            ListNode result = dummy;
            while(!minHeap.isEmpty()){
                result.next = new ListNode(minHeap.remove());
                result = result.next;
            }
            return dummy.next;
    }
}

LeetCode - Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000

Output: 1
Example 2:
Input:
11000
11000
00100
00011

Output: 3
Java Solution ;
class Solution {
    public int numIslands(char[][] grid) {
        int numOfIslands = 0;
        for(int i =0; i < grid.length;i++){
            for(int j=0; j < grid[i].length;j++){
                if(grid[i][j] == '1')
                numOfIslands += dfs(grid,i,j);
            }
        }
        return numOfIslands;
    }
    public int dfs (char[][] grid , int i , int j){
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == '0'){
            return 0;
        }
        
        grid[i][j] = '0';
        dfs(grid,i+1,j);
        dfs(grid,i-1,j);
        dfs(grid,i,j+1);
        dfs(grid,i,j-1);
        return 1;
    }
}

LeetCode - Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Java Solution:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode temp = new ListNode(0);
        int carry = 0;
        ListNode headA =l1 , headB = l2 , curr = temp;
     
           while (headA != null || headB !=null){
                int x = (headA != null) ? headA.val : 0;
                int y = (headB != null) ? headB.val : 0;
                int sum = x + y + carry;
                carry = sum / 10;
                curr.next = new ListNode(sum % 10);     
                curr = curr.next;
               if(headA != null) headA = headA.next;
               if(headB != null) headB = headB.next;
           }
            if(carry > 0)
                curr.next = new ListNode(carry);
            return temp.next;
        
    }
}
Time Complexity : O(max(m,n))
Space Complexity : O(max(m,n))+1

LeetCode - Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.
An input string is valid if:
  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
Java Solution :
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for(char c : s.toCharArray()){
            if(c == '{' || c == '['|| c == '('){
                stack.push(c);
            }else if(c == '}' && !stack.isEmpty() && stack.peek()=='{'){
                stack.pop();
            }else if(c == ']' && !stack.isEmpty() && stack.peek()=='['){
                stack.pop();
            }else if(c == ')' && !stack.isEmpty() && stack.peek()=='('){
                stack.pop();
            }else{
                return false;
            }
        }
        return stack.isEmpty();
    }
}

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...