Mac keyboard shortcuts cheatsheet


Mac keyboard shortcuts cheatsheet

Sleep, log out, and shut down shortcuts


Power buttonPress to turn on your Mac or wake your Mac from sleep.
Press and hold for 1.5 seconds while your Mac is awake to display a dialog asking if you want to sleep, restart, or shut down. If you don’t want to wait 1.5 seconds, press Control–Power button or Control–Media Eject  .*
Press and hold for 5 seconds to force your Mac to turn off.
Control–Command–Power buttonForce your Mac to restart.*
Control–Shift–Power button or
Control–Shift–Media Eject 
Put your displays to sleep.*
Control–Command–Media Eject Quit all apps, then restart your Mac. If any open documents have unsaved changes, you’ll be asked whether you want to save them.*
Control–Option–Command–Power button or
Control–Option–Command–Media Eject 
Quit all apps, then shut down your Mac. If any open documents have unsaved changes, you’ll be asked whether you want to save them.*
Shift-Command-QLog out of your macOS user account. You’ll be asked to confirm.
Option-Shift-Command-QLog out of your macOS user account immediately, without being asked to confirm.

Cut, copy, paste, and other common shortcuts

Command-XCut the selected item and copy it to the Clipboard.
Command-CCopy the selected item to the Clipboard. This also works for files in the Finder.
Command-VPaste the contents of the Clipboard into the current document or app. This also works for files in the Finder.
Command-ZUndo the previous command. You can then press Command-Shift-Z to Redo, reversing the undo command. In some apps, you can undo and redo multiple commands.
Command-ASelect All items.
Command-FFind items in a document or open a Find window.
Command-GFind Again: Find the next occurrence of the item previously found. To find the previous occurrence, press Command-Shift-G.
Command-HHide the windows of the front app. To view the front app but hide all other apps, press Command-Option-H.
Command-MMinimize the front window to the Dock. To minimize all windows of the front app, press Command-Option-M.
Command-NNew: Open a new document or window.
Command-OOpen the selected item, or open a dialog to select a file to open.
Command-PPrint the current document.
Command-SSave the current document.
Command-WClose the front window. To close all windows of the app, press Command-Option-W.
Command-QQuit the app.
Option-Command-EscForce Quit: Choose an app to force quit. Or press Command-Shift-Option-Esc and hold for 3 seconds to force just the front app to quit.
Command–Space barSpotlight: Show or hide the Spotlight search field. To perform a Spotlight search from a Finder window, press Command–Option–Space bar. If you use multiple input sources to type in different languages, these shortcuts change input sources instead of showing Spotlight.
Space barQuick Look: Use Quick Look to preview the selected item.
Command-TabSwitch apps: Switch to the next most recently used app among your open apps.
Shift-Command-Tilde (~)Switch windows: Switch to the next most recently used window of the front app.
Shift-Command-3Screenshot: Take a screenshot of the entire screen. Learn more screenshot shortcuts.
Command-Comma (,)Preferences: Open preferences for the front app.

Finder shortcuts

Command-DDuplicate the selected files.
Command-EEject the selected disk or volume.
Command-FStart a Spotlight search in the Finder window.
Command-IShow the Get Info window for a selected file.
Shift-Command-COpen the Computer window.
Shift-Command-DOpen the desktop folder.
Shift-Command-FOpen the All My Files window.
Shift-Command-GOpen a Go to Folder window.
Shift-Command-HOpen the Home folder of the current macOS user account.
Shift-Command-IOpen iCloud Drive.
Shift-Command-KOpen the Network window.
Option-Command-LOpen the Downloads folder.
Shift-Command-OOpen the Documents folder.
Shift-Command-ROpen the AirDrop window.
Shift-Command-TAdd selected Finder item to the Dock (OS X Mountain Lion or earlier)
Control-Shift-Command-TAdd selected Finder item to the Dock (OS X Mavericks or later)
Shift-Command-UOpen the Utilities folder.
Option-Command-DShow or hide the Dock. This often works even when you’re not in the Finder.
Control-Command-TAdd the selected item to the sidebar (OS X Mavericks or later).
Option-Command-PHide or show the path bar in Finder windows.
Option-Command-SHide or show the Sidebar in Finder windows.
Command–Slash (/)Hide or show the status bar in Finder windows.
Command-JShow View Options.
Command-KOpen the Connect to Server window.
Command-LMake an alias of the selected item.
Command-NOpen a new Finder window.
Shift-Command-NCreate a new folder.
Option-Command-NCreate a new Smart Folder.
Command-RShow the original file for the selected alias.
Command-TShow or hide the tab bar when a single tab is open in the current Finder window.
Shift-Command-TShow or hide a Finder tab.
Option-Command-TShow or hide the toolbar when a single tab is open in the current Finder window.
Option-Command-VMove: Move the files in the Clipboard from their original location to the current location.
Option-Command-YView a Quick Look slideshow of the selected files.
Command-YUse Quick Look to preview the selected files.
Command-1View the items in the Finder window as icons.
Command-2View the items in a Finder window as a list.
Command-3View the items in a Finder window in columns.
Command-4View the items in a Finder window with Cover Flow.
Command–Left Bracket ([)Go to the previous folder.
Command–Right Bracket (])Go to the next folder.
Command–Up ArrowOpen the folder that contains the current folder.
Command–Control–Up ArrowOpen the folder that contains the current folder in a new window.
Command–Down ArrowOpen the selected item.
Command–Mission ControlShow the desktop. This works even when you’re not in the Finder.
Command–Brightness UpTurn Target Display Mode on or off.
Command–Brightness DownTurn display mirroring on or off when your Mac is connected to more than one display.
Right ArrowOpen the selected folder. This works only when in list view.
Left ArrowClose the selected folder. This works only when in list view.
Option–double-clickOpen a folder in a separate window and close the current window.
Command–double-clickOpen a folder in a separate tab or window.
Command-DeleteMove the selected item to the Trash.
Shift-Command-DeleteEmpty the Trash.
Option-Shift-Command-DeleteEmpty the Trash without confirmation dialog.
Command-YUse Quick Look to preview the files.
Option–Brightness UpOpen Displays preferences. This works with either Brightness key.
Option–Mission ControlOpen Mission Control preferences.
Option–Volume UpOpen Sound preferences. This works with any of the volume keys.
Command key while draggingMove the dragged item to another volume or location. The pointer changes while you drag the item.
Option key while draggingCopy the dragged item. The pointer changes while you drag the item.
Option-Command while draggingMake an alias of the dragged item. The pointer changes while you drag the item.
Option-click a disclosure triangleOpen all folders within the selected folder. This works only when in list view.
Command-click a window titleSee the folders that contain the current folder.

Document shortcuts


Command-BBoldface the selected text, or turn boldfacing on or off.
Command-IItalicize the selected text, or turn italics on or off.
Command-UUnderline the selected text, or turn underlining on or off.
Command-TShow or hide the Fonts window.
Command-DSelect the Desktop folder from within an Open dialog or Save dialog.
Control-Command-DShow or hide the definition of the selected word.
Shift-Command-Colon (:)Display the Spelling and Grammar window.
Command-Semicolon (;)Find misspelled words in the document.
Option-DeleteDelete the word to the left of the insertion point.
Control-HDelete the character to the left of the insertion point. Or use Delete.
Control-DDelete the character to the right of the insertion point. Or use Fn-Delete.
Fn-DeleteForward delete on keyboards that don’t have a Forward Delete   key. Or use Control-D.
Control-KDelete the text between the insertion point and the end of the line or paragraph.
Command-DeleteSelect Delete or Don’t Save in a dialog that contains a Delete or Don’t Save button.
Fn–Up ArrowPage Up: Scroll up one page.
Fn–Down ArrowPage Down: Scroll down one page.
Fn–Left ArrowHome: Scroll to the beginning of a document.
Fn–Right ArrowEnd: Scroll to the end of a document.
Command–Up ArrowMove the insertion point to the beginning of the document.
Command–Down ArrowMove the insertion point to the end of the document.
Command–Left ArrowMove the insertion point to the beginning of the current line.
Command–Right ArrowMove the insertion point to the end of the current line.
Option–Left ArrowMove the insertion point to the beginning of the previous word.
Option–Right ArrowMove the insertion point to the end of the next word.
Shift–Command–Up ArrowSelect the text between the insertion point and the beginning of the document.
Shift–Command–Down ArrowSelect the text between the insertion point and the end of the document.
Shift–Command–Left ArrowSelect the text between the insertion point and the beginning of the current line.
Shift–Command–Right ArrowSelect the text between the insertion point and the end of the current line.
Shift–Up ArrowExtend text selection to the nearest character at the same horizontal location on the line above.
Shift–Down ArrowExtend text selection to the nearest character at the same horizontal location on the line below.
Shift–Left ArrowExtend text selection one character to the left.
Shift–Right ArrowExtend text selection one character to the right.
Option–Shift–Up ArrowExtend text selection to the beginning of the current paragraph, then to the beginning of the following paragraph if pressed again.
Option–Shift–Down ArrowExtend text selection to the end of the current paragraph, then to the end of the following paragraph if pressed again.
Option–Shift–Left ArrowExtend text selection to the beginning of the current word, then to the beginning of the following word if pressed again.
Option–Shift–Right ArrowExtend text selection to the end of the current word, then to the end of the following word if pressed again.
Control-AMove to the beginning of the line or paragraph.
Control-EMove to the end of a line or paragraph.
Control-FMove one character forward.
Control-BMove one character backward.
Control-LCenter the cursor or selection in the visible area.
Control-PMove up one line.
Control-NMove down one line.
Control-OInsert a new line after the insertion point.
Control-TSwap the character behind the insertion point with the character in front of the insertion point.
Command–Left Curly Bracket ({)Left align.
Command–Right Curly Bracket (})Right align.
Shift–Command–Vertical bar (|)Center align.
Option-Command-FGo to the search field.
Option-Command-TShow or hide a toolbar in the app.
Option-Command-CCopy Style: Copy the formatting settings of the selected item to the Clipboard.
Option-Command-VPaste Style: Apply the copied style to the selected item.
Option-Shift-Command-VPaste and Match Style: Apply the style of the surrounding content to the item pasted within that content.
Option-Command-IShow or hide the inspector window.
Shift-Command-PPage setup: Display a window for selecting document settings.
Shift-Command-SDisplay the Save As dialog, or duplicate the current document.
Minus sign (-)
Decrease the size of the selected item.
Plus sign (+)
Increase the size of the selected item. Command–Equal sign (=) performs the same function.
Question mark (?)
Open the Help menu.

Lombok Cheatsheet


Lombok Cheatsheet

Lombok @Getter and @Setter Annotations

You can annotate any field with @Getter and/or @Setter, to let lombok generate the default getter/setter automatically.

@Getter @Setterpublic class PersonLombok { String firstName; String lastName; LocalDate dateOfBirth;}

Lazy Getter

In @Getter  When lazy set to true, it is possible to delay the initialization of the value until the getter method is called first.

package sample.lombok;import lombok.Getter;public class Main {    public static void main(String[] args) {        Main m = new Main();        System.out.println("Main instance is created");        m.getLazy();    }    @Getter    private final String notLazy = createValue("not lazy");    @Getter(lazy=true)    private final String lazy = createValue("lazy");    private String createValue(String name) {        System.out.println("createValue(" + name + ")");        return null;    }}

For more detail info learn Lombok from here:

Java Lombok Tutorial

Constructor Annotations

@NoArgsConstructorYou can automatically generate the default constructor by giving it to the class.

import lombok.NoArgsConstructor;@ NoArgsConstructor public  class Person1 {    private  long id;    private String name;    private  int age;}

@AllArgsConstructorBy assigning a class to a class, you can automatically generate a constructor with arguments to set values for all members.

import lombok.AllArgsConstructor;@ AllArgsConstructor public  class Person2 {    private  long id;    private String name;    private  int age;}

@RequiredArgsConstructorBy assigning a class to a class, you can automatically generate a constructor with arguments to set the value to a required member (final member).

import lombok.RequiredArgsConstructor;@ RequiredArgsConstructor public  class Person4 {    private  final  long id;    private String name;    private  int age;}

Lombok @EqualsAndHashCode Annotation

Giving the class an @EqualsAndHashCode annotation properly overrides the equals and hashCode methods of the target class depending on the members in the class.@EqualsAndHashCode without specifying a parameter will generate processing of equals, hashCode using all members in the class

@EqualsAndHashCode public class PersonLombok {	String firstName;	String lastName;	LocalDate dateOfBirth;}

Lombok @ToString Annotation

@ToString annotation provides a toString() implementation. Let’s see this:

By default, it’ll print your class name, along with each field, in order, separated by commas

@ToStringpublic class PersonLombok {	String firstName;	String lastName;	LocalDate dateOfBirth;}

Lombok @Data Annotation

By annotating the class with @Data , you get the same effect as setting all the following annotations.

  • @ToString
  • @Getter
  • @Setter
  • @RequiredArgsConstructor
  • @EqualsAndHashCode
import lombok.Data;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entity@Datapublic class Todo {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    private String summary;    private String description;}

Project Lombok @Log Annotation

You put the variant of @Log on your class (whichever one applies to the logging system you use); you then have a static final log field, initialized to the name of your class, which you can then use to write log statements.

@Log: creates

private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());

@Log4j: creates

private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class);

@Log4j2: creates

private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);

@Slf4j: Creates

private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);

Lombok @Synchronized Annotations

@Synchronized is a safer variant of the synchronized method modifier. Like synchronized, the annotation can be used on static and instance methods only. It operates similarly to the synchronized keyword, but it locks on different objects. The keyword locks on this, but the annotation locks on a field named $lock, which is private.
If the field does not exist, it is created for you. If you annotate a static method, the annotation locks on a static field named $LOCK instead.

import lombok.Synchronized;public class SynchronizedExample {  private final Object readLock = new Object();   @Synchronized  public static void hello() {    System.out.println("world");  }    @Synchronized  public int answerToLife() {    return 42;  }  @Synchronized("readLock")  public void foo() {    System.out.println("bar");  }}

Lombok @Builder annotation

Lombok provides an annotation for implementing the Builder pattern on your classes. 

@Builder can be placed on a class, or on a constructor, or on a method. While the “on a class” and “on a constructor” 

@Getter@EqualsAndHashCode@AllArgsConstructor@Builderpublic class Person {  private final String firstname;  private final String lastname;  private final String email;}

Lombok @SneakyThrows Annotation

@SneakyThrows can be used to sneakily throw checked exceptions without actually declaring this in your method’s throws clause. 

import lombok.SneakyThrows;public class SneakyClone implements Cloneable {    @SneakyThrows    @Override    protected Object clone() {        return super.clone();    }}

What happened behind:

public class SneakyClone implements Cloneable {    @Override    protected Object clone() {        try {            return super.clone();        } catch (final java.lang.Throwable $ex) {            throw lombok.Lombok.sneakyThrow($ex);        }    }}

Lombok @NonNull Annotation

You can use @NonNull on the parameter of a method or constructor to have lombok generate a null-check statement for you.

class User {    @Getter @Setter @NonNull private String name;}

The above annotated code is equivalent to the following java code –

class User {    @Getter @Setter @NonNull private String name;    @NonNull    public String getName() {        return name;    }    public void setName(@NonNull final String name) {        if(name == null) throw new NullPointerException("name"); = name;    }}

YAML Cheatsheet

YAML Cheatsheet



Grammar Rules

  • Case Sensitive
  • Use indentation to represent hierarchy
  • Tabs are not allowed when indenting, only spaces are allowed.
  • The number of indented spaces is not important, as long as the same level of elements is left-justified
  • # Represents the comment, from this character until the end of the line, will be ignored by the parser.

All YAML files can optionally begin with — and end with  This is part of the YAML format and indicates the start and end of a document.

Special Characters

'? ' : Key indicator.': ' : Value indicator.'- ' : Nested series entry indicator.', ' : Separate in-line branch entries.'[]' : Surround in-line series branch.'{}' : Surround in-line keyed branch.
'&' : Anchor property.'*' : Alias indicator.

Data Structure

  • Scalars: Individual, undividable values
  • Hashes: A collection of key-value pairs, also known as a mapping/object/dictionary
  • Sequences: A set of ordered values, also known as a array/list (list)

For more info learn YAML from here:YAML Tutorial


The scalar quantity is the most basic and indivisible value.

Boolean_type_1: yesBoolean_type_2: Truenull_type_2: nullnull_type_3: ~number_type_1: 123number_type_2: 1.23string_type_2: 'hello'string_type_3: "hello"date: 2020-02-28	# date type#The time is in ISO8601 format.iso8601: 2001-12-14t21:59:43.10-05:00  # Enforcing stringsdate_as_string: !str 2020-02-28   # date type


A set of ordered values, also known as a sequence/list/array (list)

# sequencearray:   - 12   - 3.34   - 'abc'   - true   - null

Nested sequence

- - Cat - Dog - Goldfish


A collection of key-value pairs, also known as a mapping/hashes/dictionary


animal: pets

Nested hash

hash: subkey:   subsubkey1: 5   subsubkey2: 6 another:   somethingelse: 'Important!'

Composite structure

Objects and arrays can be combined to form a composite structure.

languages: - Ruby - Perl - Python websites: YAML:  Ruby:  Python:  Perl:

Multiple Documents

YAML uses three dashes — to separate directives from document content. This also serves to signal the start of a document if no directives are present. Three dots ( “…”) indicate the end of a document without starting a new one, for use in communication channels.

# YAML---document: this is doc 1---document: this is doc 2...

String in YAML

1. Block Notation: Newlines become spaces and extra newlines after the block are removed

---# Note: it has 1 new line after the stringcontent:    Arbitrary free text    over multiple lines stopping    after indentation changes......

Equivalent JSON

{ "content": "Arbitrary free text over multiple lines stopping after indentation changes..."}

2. Literal Block Scalar: a Literal Block Scalar | will include the newlines and any trailing spaces. but removes extra

newlines after the block.

---# After string we have 2 spaces and 2 new linescontent1: | Arbitrary free text over "multiple lines" stopping after indentation changes...  ...

Equivalent JSON

{ "content1": "Arbitrary free textnover "multiple lines" stoppingnafter indentation changes...  n"}

3. + indicator with Literal Block Scalar: keep extra newlines after block

---# After string we have 2 new linesplain: |+ This unquoted scalar spans many lines....

Equivalent JSON

{ "plain": "This unquoted scalarnspans many lines.nnn"}

4. – indicator with Literal Block Scalar: – means that the newline at the end of the string is removed.

---# After string we have 2 new linesplain: |- This unquoted scalar spans many lines....

Equivalent JSON

{ "plain": "This unquoted scalarnspans many lines."}

5. Folded Block Scalar(>):

will fold newlines to spaces and but removes extra newlines after the block.

---folded_newlines: > this is really a single line of text despite appearances...

Equivalent JSON

{ "fold_newlines": "this is really a single line of text despite appearancesn"}

YAML References

Anchors &and aliases *can be used for reference.

---values:- &ref Something to reuse- *ref	# Reused content

Merging Keys 

 &Used to create an anchor point ( defaults<<that merges into the current data and is *used to refer to the anchor point.

defaults: &defaults   adapter: postgres   host: localhostdevelopment:   database: myapp_development   <<: *defaultstest:   database: myapp_test   <<: *defaults

Ancor point for current data

- &us USA - UK - INDIA - CHINA - *us

Complex Mapping:

---? - key:  - value# Note: key and value can be multiple, complex structures

Mapping between Sequences

? - Detroit Tigers  - Chicago cubs:  - 2001-07-23? [ New York Yankees,    Atlanta Braves ]: [ 2001-07-02, 2001-08-12,    2001-08-14 ]

Corresponding JSON

{"["Detroit Tigers", "Chicago cubs"]": ["2001-07-23"],"["New York Yankees", "Atlanta Braves"]": [   "2001-07-02",   "2001-08-12",   "2001-08-14" ]}


parent: &defaults  a: 2  b: 3child:  <<: *defaults  b: 4

Reference link

Frequently DS and Algo interview Puzzles

  1. Multiply two integers without using multiplication, division and bitwise operators, and no loops
  2. Write your own Power without using multiplication(*) and division(/) operators
  3. Measure one liter using two vessels and infinite water supply
  4. Generate integer from 1 to 7 with equal probability
  5. Detect opposite signs
  6. How to swap two numbers without using a temporary variable?
  7. Check if binary representation of a number is a palindrome
  8. A binary representation of a given number
  9. Find whether a no is the power of two
  10. Write a program to add one to a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc are not allowed.

Frequently Asked Dynamic Programming(DP) Interview Questions and Answers

  1. Longest Increasing Subsequence
  2. Longest Common Subsequence
  3. Edit Distance
  4. Min Cost Path
  5. Coin Change
  6. 0-1 Knapsack Problem
  7. Egg Dropping Puzzle
  8. Longest Palindromic Subsequence
  9. Cutting a Rod
  10. Maximum Sum Increasing Subsequence
  11. Longest Bitonic Subsequence
  12. Mobile Numeric Keypad Problem
  13. Word Wrap Problem
  14. Minimum number of jumps to reach end
  15. Box Stacking Problem
  16. Subset Sum Problem
  17. Maximum sum rectangle in a 2D matrix
  18. Maximum profit by buying and selling a share at most twice
  19. Count ways to reach the n’th stair
  20. Boolean Parenthesization Problem

Frequently Asked Graph Interview Questions and Answers

  1. Breadth First Traversal for a Graph
  2. Depth First Traversal for a Graph
  3. Kahn’s Algorithm for Topological Sorting
  4. Detect Cycle in a Graph
  5. Count the number of nodes at given level in a tree using BFS
  6. Detect cycle in a direct graph using colors
  7. Detect Cycle in a Directed Graph
  8. Detect Cycle in  an Undirected Graph
  9. Minimum cost to connect all cities
  10. Dijkstra’s shortest path algorithm
  11. Strongly Connected Components
  12. Transitive closure of a graph
  13. Find the number of islands
  14. Length of shortest chain to reach the target word
  15. Print all paths from a given source to destination
  16. Find minimum cost to reach the destination using the train
  17. Travelling Salesman Problem
  18. Optimal read list for a given number of days
  19. Print all jumping numbers smaller than or equal to a given value
  20. Minimum Time to rot all oranges
  21. Construct binary palindrome by repeated appending and trimming
  22. Find same contents in a list of contacts
  23. Check whether a given graph is Bipartite or not
  24. Euler Circuit in a Directed Graph

Frequently Asked Hashing Interview Questions and Answers

    1. Largest subarray with equal number of 0s and 1s
    2. Palindrome Substring Queries
    3. Find smallest range containing elements from k lists
    4. Print all subarrays with 0 sum
    5. Length of the largest subarray with contiguous elements
    6. Find if there is a subarray with 0 sum
    7. Find the largest subarray with 0 sum
    8. Longest Consecutive Subsequence
    9. Find Itinerary from a given list of tickets
    10. Anagrams: Given an array of strings, return all groups of strings that are anagrams. Represent a group by a list of integers representing the index in the original list. Look at the sample case for clarification.
    11. Window String: Given a string S and a string T, find the minimum window in S which will contain all the characters in T in linear time complexity. Note that when the count of a character C in T is N, then the count of C in minimum window in S should be at least N.

Frequently Asked BST Interview Questions and Answers


  1. Binary Tree to Binary Search Tree Conversion
  2. Transform a BST to greater sum tree
  3. K’th smallest element in BST using O(1) Extra Space
  4. Find if there is a triplet in a Balanced BST that adds to zero
  5. Count pairs from two BSTs whose sum is equal to a given value x
  6. Sorted Array to Balanced BST
  7. Check for Identical BSTs without building the trees
  8. Find the distance between two nodes of a Binary Search Tree
  9. Lowest Common Ancestor in a Binary Search Tree
  10. Find median of BST in O(n) time and O(1) space

Frequently Asked Tree Interview Questions and Answers

  1. Level Order Tree Traversal
  2. Print a Binary Tree in Vertical Order
  3. Iterative Postorder Traversal
  4. Boundary Traversal of the binary tree
  5. Lowest Common Ancestor in a Binary Tree
  6. Find the distance between two nodes of a Binary Tree
  7. Diameter of a Binary Tree
  8. Print nodes at k distance from the root
  9. Vertical Sum in a given Binary Tree
  10. Print Left View of a Binary Tree
  11. Find the maximum path sum between two leaves of a binary tree
  12. Diagonal Sum of a Binary Tree
  13. Convert a normal BST to Balanced BST
  14. Convert a given Binary Tree to Doubly Linked List
  15. Construct Tree from given Inorder and Preorder traversal
  16. Tree Isomorphism Problem
  17. Diagonal Sum of a Binary Tree
  18. Bottom View of a Binary Tree
  19. Print Nodes in Top View of Binary Tree

Frequently Asked Queue Interview Questions and Answers

Q: Implement Stack using Queues


Implement the following operations of a stack using queues.

  • push(x) — Push element x onto stack.
  • pop() — Removes the element on top of the stack.
  • top() — Get the top element.
  • empty() — Return whether the stack is empty.

Q: Maximums in Sliding Windows


Given an array of numbers and a sliding window size, how to get the maximal numbers in all sliding windows?

Q: LRU Cache Implementation


Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) – Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) – Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Frequently Asked Stack Interview Questions

Q: Stack with Function min()


Design a stack that supports getMin() in O(1) time and O(1) extra space

Q: Implement two stacks in an array


Create a data structure twoStacks that represents two stacks. Implementation of twoStacks should use only one array, i.e., both stacks should use the same array for storing elements. Following functions must be supported by twoStacks.

push1(int x) –> pushes x to first stack

push2(int x) –> pushes x to second stack

pop1() –> pops an element from first stack and return the popped element

pop2() –> pops an element from second stack and return the popped element

Implementation of twoStack should be space efficient.

Q: Push and Pop Sequences of Stacks


Given two integer sequences, one of which is the push sequence of a stack, please check whether the other sequence is a corresponding pop sequence or not.

Q: Infix to Postfix Conversion using Stack


Given an expression (a+(b-c)/d) convert this expression into postfix expression

Q: The Stock Span Problem


We are given a list of prices of a stock for N number of days. We need to find stock span for each day. Span is defined as number of consecutive days before the given day where the price of stock was less than or equal to price at given day. For example, {100, 60,70,65, 80, 85} span for each day will be {1, 1, 2, 1, 4, 5}.

Q: Next Greater Element


Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1.

Q: Check for balanced parentheses in an expression


Given an expression string exp , write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. For example, the program should print true for exp = “[()]{}{[()()]()}” and false for exp = “[(])”

Q: Celebrity problem


You have a room with n people. A celebrity walks in. Everyone knows the celebrity, the celebrity knows no one. Non-celebrities may/may not know anyone in the room. Give an algorithm to find the celebrity. Discuss the complexity.

Q: Expression Evaluation


Evaluate an expression represented by a String. Expression can contain parentheses, you can assume parentheses are well-matched. For simplicity, you can assume only binary operations allowed are +, -, *, and /.

Q: Implement Queue using Stacks


We are given a stack data structure with push and pop operations, the task is to implement a queue using instances of stack data structure and operations on them.

Q: Design a stack with operations on middle element


How to implement a stack which will support following operations in O(1) time complexity?

1) push() which adds an element to the top of stack.

2) pop() which removes an element from top of stack.

3) findMiddle() which will return middle element of the stack.

4) deleteMiddle() which will delete the middle element.

Push and pop are standard stack operations.

Frequently Asked Linked List Interview Questions

We have carefully observed all Multi National Companies Interviews. We have chosen Commonly Asked Linked List Interview Questions  for you.

Q: Check if singly linked list is palindrome.


Given a singly linked list, determine if its a palindrome. Return 1 or 0 denoting if its a palindrome or not, respectively.

For example: 1->2->1 O/P: 11->2->3O/P: 0

Q: Remove duplicates from the Linked list.


Given an unsorted linked list, and without using a temporary buffer, write a method that will delete any duplicates from the linked list.

For example:  Linked List :1->2->3->4->2->4->1->5->5->NULLO/P:1->2->3->4->5->NULLLinked List: 2->1->4->2->5->3->3->5->NULLO/P: 2->1->4->5->3

Q: Find n’th node from end of the linked list.


Given a linked list and a position from the end . Find the node at that position.

For example: Linked List: 1->2->5->3->7->12->4->9->5->NULLPosition-3O/p: 4( 3rd element from the last of the linked list.)

Q: Merge 2 sorted linked list.


Given 2 linked list  sorted in increasing order. Write a function that merge the 2 linked list together into one linked list which in also inceasing.

For Example-Merge 1->1->3->6->8->9->NULL and 1->2->5->5->7->8->NULLO/p- 1->1->2->3->5->5->6->7->8->9->NULL

Q: Reverse the linked list in groups of given size.


Given a linked list and a number k. Write a function to reverse every k node in the linked list.

For Example- 1->2->3->4->5->6->7->8->9->NULLK=4O/P:4->3->2->1->8->7->6->5->9->NULL

Q: Write a function to get the intersection point of two Linked Lists (Y Shape)


There are 2 linked list which are forming Y shape in between . Write a function to get the intersection point of the 2 lists.

Q: Reverse the nodes of singly linked list.


Given a linked list write a function that reverse the nodes of the linked list.

For example- 1->2->3->4->5->NULLO/p:  5->4->3->2->1->NULL

Q: Delete N nodes after M nodes of a linked list.


Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.

For Example-M=3, N=2Linked list: 1->2->3->4->5->6->7->8->9->NULLO/P: 1->2->3->6->7->8->NULLM=1, N=1Linked List 1->2->3->4->5->6->7->8->9->NULLO/P: 1->3->5->7->9->NULL

Q: Add 2 numbers represented by linked lists.


Given 2 numbers represented by 2 linked list. Write a function that return a list as sum of the 2 numbers.

For example- List1: 2->4->9 ->NULL // represents number 946List 2: 8->5->-0->9->NULL // represents number 9058O/P: 4->0->0->0->1->NULL // represents number 10004

List 1: 5->6->1 // represents number 165
List 2: 3->4->5 // represents number 543
O/P: 8->0->7//represents 708

Q: Swap the elements of the linked list in pair.


Given a linked list, write a function to swap elements in pair.

For example- Linked list: 1->2->3->4->5->6->-7->NULLO/P: 2->1->4->3->6->5->7->NULLLinked list: 1->2->3->4->5->6->NULLO/P: 2->1->4->3->6->5->NULL

Q: Merge sort for the linked lists.


Merge sort in preferred in sorting the linked list because random access is not allowed in the linked list.

For Example- Linked list: 4->3->6->5->10->3->12->9->NULLO/P: 3->3->4->5->6->9->10->12->NULL

Q: Rearrange a linked list in Zig – Zag fashion.


Given a linked list, rearrange it such that converted list should be of the form a < b > c < d > e < f … where a, b, c… are consecutive data node of linked list.

For Example- Linked list: 11->14->19->7->10O/P: 11->19->7->14->10Linked list: 1->2->3->4O/P: 1->3->2->4

Q: Find pairs with given sum in doubly linked list.


Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in doubly linked list whose sum is equal to given value x, without using any extra space ?

Input : head : 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9        x = 7Output: (6, 1), (5,2)

Q: Sort a linked list of 0s, 1s and 2s


Given a linked list of 0s, 1s and 2s, sort it.

Q: Flattening a Linked List


Given a linked list, in addition to the next pointer, each node has a child pointer that can point to a separate list. With the head node, flatten the list to a single-level linked list.

For instance, the above linked list should be flattened to 1→2->3→4->5->6->7->8->9. The idea is to flatten the linked list by level. Note: this question was asked by Facebook a month ago.

Q: Clone a linked list with next and random pointer


You are given a Double Link List with one pointer of each node pointing to the next node just like in a single link list. The second pointer however CAN point to any node in the list and not just the previous node. Now write a program in O(n) time to duplicate this list. That is, write a program which will create a copy of this list.

Q: Find loop in linked list and remove the loop


Write a function detectAndRemoveLoop() that checks whether a given Linked List contains loop and if loop is present then removes the loop and returns true. And if the list doesn’t contain loop then returns false. Below diagram shows a linked list with a loop.

0--->1---->2---->3---->4---->5---->6                  ▲                 |                  |                 ▼                 11<—-22<—-12<—-9<—-8

Q: Count rotations in sorted and rotated linked list


Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the value of k.

Q: Union and intersection of 2 linked list


iven two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. Order of elments in output lists doesn’t matter.


Input:   List1: 10->15->4->20   lsit2:  8->4->2->10Output:   Intersection List: 4->10   Union List: 2->8->20->4->15->10

Q: Segregate even and odd nodes in a Linked List


Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.


Input: 17->15->8->12->10->5->4->1->7->6->NULLOutput: 8->12->10->4->6->17->15->5->1->7->NULL

Input: 8->12->10->5->4->1->6->NULL
Output: 8->12->10->4->6->5->1->NULL

Cron Cheatsheet

Q: Add Your Heading Text Here

Cron Cheatsheet

Cron Syntax

# ┌───────────── minute (0 - 59)# │ ┌───────────── hour (0 - 23)# │ │ ┌───────────── day of month (1 - 31)# │ │ │ ┌───────────── month (1 - 12)# │ │ │ │ ┌───────────── day of week (0 - 6) # │ │ │ │ │# │ │ │ │ │# │ │ │ │ │# * * * * *  command to execute

Day of week 0-6 means Sunday to Saturday; 7 is also Sunday on some systems

Special Characters(*,, /, ,)

*any value( for ex for hour any value b/w 0 to 23)
,value list separator ( For example 3,5,12)
range of values (for example 5-12)
/step values . ( */10 in minutes  means it will run every 10 minutes)

Run every minute

Min  Hour Day  Mon  Weekday*    *    *    *    *  command to be executed┬    ┬    ┬    ┬    ┬│    │    │    │    └─  Run every day of the week│    │    │    └──────  Run every month of the year│    │    └───────────  Run every day of the month│    └────────────────  Run hour of the day└─────────────────────  Run every minute of the hour

You can use this format also:

0-59 0-23 0-31 0-12 0-7 command to be executed

Numeric values

Use numeric values instead of asterisks to match specific minutes, hours, days and months.

Min  Hour Day  Mon  Weekday0    20    *    *    0  command to be executed┬    ┬    ┬    ┬    ┬│    │    │    │    └─  Run at Sunday│    │    │    └──────  Run every month of the year│    │    └───────────  Run every day of the month│    └────────────────  Run at 8PM└─────────────────────  Run at 0th minute

It will Run at 8PM on every Sunday

Ranges of values

Use start-end to define a range of matching values.

Min  Hour Day  Mon  Weekday*    *    *    *    1-5  command to be executed┬    ┬    ┬    ┬    ┬│    │    │    │    └─  Run on Monday to friday│    │    │    └──────  Run every month of the year│    │    └───────────  Run every day of the month│    └────────────────  Run every hour of day└─────────────────────  Run at 0th minute

This job will run every minute on workdays(Monday to Friday)


Use {v1},{v2},…,{vn} to list multiple values.

Min  Hour Day  Mon  Weekday0 5,10,15 *    *    *  command to be executed┬    ┬    ┬    ┬    ┬│    │    │    │    └─  Run every day of the week│    │    │    └──────  Run every month of the year│    │    └───────────  Run every day of the month│    └────────────────  Run at 5AM,10AM,3PM└─────────────────────  Run every minute of the hour

Ii will Run at 5AM, 10PM and 3PM every day

Ranges with a step

Use {start}-{end}/{step} or */{step} to define a range with a step.

Min  Hour Day  Mon  Weekday*/15 *    *    *    *  command to be executed┬    ┬    ┬    ┬    ┬│    │    │    │    └─  Run every day of the week│    │    │    └──────  Run every month of the year│    │    └───────────  Run every day of the month│    └────────────────  Run every hour of the day└─────────────────────  Run every 15 minutes

This job will run Run every 15 minutes.

Cron special keyword

@yearly0 0 1 1 *
@daily0 0 * * *
@hourly0 * * * *
@rebootRun at startup.

Crontab Commands

  • crontab -e Edit or create a crontab file if doesn’t already exist.
  • crontab -l To Display the crontab file.
  • crontab -r To Remove the crontab file.
  • crontab -v To Display the last time you edited your crontab file. (This option is only available on a few systems.)


Run every hour on April 1st
0 7-59/5 06 * * *This runs at 6:07, 6:012, 6:17, 6:22, 6:27, and so on until 6:57
0 */2 * * *every 2 hours
0 0 * * 0every Sunday midnight
0 0 * * * every day midnight

Java 1 Features

Release Date: January 23, 1996

This was the initial release and was originally called Oak. This had very unstable APIs and one java web browser named WebRunner.

The first stable version, JDK 1.0.2, was called Java 1.

On February 19, 1997, JDK 1.1 was released having a list of big features such as:

  • AWT event model
  • Inner classes
  • JavaBeans
  • JDBC
  • RMI
  • Reflection which supported Introspection only, no modification at runtime was possible.
  • JIT (Just In Time) compiler for Windows


Java 2 Features | New Feature in Java

This release was called “Playground”.

This was a major release in terms of a number of classes added (almost tripled the size). “J2SE” term was introduced to distinguish the code platform from J2EE and J2ME. Included features were:

  • strictfp keyword
  • Swing graphical API
  • Sun’s JVM was equipped with a JIT compiler for the first time
  • Java plug-in
  • Collections framework

Java 3 Features | New Feature in Java

Codename Kestrel. Features added: 

  • HotSpot JVM included (the HotSpot JVM was first released in April 1999 for the J2SE 1.2 JVM)
  • RMI was modified to support optional compatibility with CORBA
  • Java Naming and Directory Interface (JNDI) included in core libraries (previously available as an extension)
  • Java Platform Debugger Architecture (JPDA)
  • JavaSound
  • Synthetic proxy classes

Java 4 Features | New Feature in Java

JDK 1.4 is one of the major versions released in February 2002. The work started on the name of “Project Merlin” and includes the developments to support XML processing, java.nio package addition, Security restrictions, Logging API, JDBC 3.0 API, Assertions, Chained exceptions, Regular expressions and Drag and Drop. Two of these features, Assertions and Regular expressions are discussed here and the remaining are illustrated in the respective topics.

  • Language changes
    • assert keyword (specified in JSR 41)
  • Library improvements
    • Regular expressions modeled after Perl regular expressions
    • Exception chaining allows an exception to encapsulate original lower-level exception
    • Internet Protocol version 6 (IPv6) support
    • Non-blocking IO (named New Input/Output, NIO) (specified in JSR 51)
    • Logging API (specified in JSR 47)
    • An image I/O API for reading and writing images in formats like JPEG and PNG
    • Integrated XML parser and XSLT processor (JAXP) (specified in JSR 5 and JSR 63)
    • Integrated security and cryptography extensions (JCE, JSSE, JAAS)
    • Java Web Start included (Java Web Start was first released in March 2001 for J2SE 1.3) (specified in JSR 56)
    • Preferences API (java.util.prefs)

Java 5 Features | New Feature in Java

Tiger(Java 5) added a number of significant new language features:

  • Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion) (specified by JSR 14)
  • Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities (specified by JSR 175)
  • Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer) (specified by JSR 201)
  • Enumerations: the enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.); previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern) (specified by JSR 201)
  • Varargs: the last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String… lines)); in the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type
  • Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes (specified by JSR 201)
  • Improved semantics of execution for multi-threaded Java programs; the new Java memory model addresses issues of complexity, effectiveness, and performance of previous specifications[18]
  • Static imports

There were also the following improvements to the standard libraries:

  • Automatic stub generation for RMI objects
  • Swing: New skinnable look and feel, called synth
  • The concurrency utilities in package java.util.concurrent
  • Scanner class for parsing data from various input streams and buffers.


  • For-each loop (Java 5)
  • Varargs (Java 5)
  • Static Import (Java 5)
  • Autoboxing and Unboxing (Java 5)
  • Enum (Java 5)
  • Covariant Return Type (Java 5)
  • Annotation (Java 5)
  • Generics (Java 5)


Java 7 Features | New Feature in Java

There are a number of features in Java 7 that will please developers. Things such as strings in switch statements, multi-catch exception handling, try-with-resources statements, the new FileSystem API, extensions of the JVM, support for dynamically-typed languages, the fork and join framework for task parallelism, and a few others will certainly be embraced by the community.

  • String in the switch statement (Java 7)
  • Binary Literals (Java 7)
  • The try-with-resources (Java 7)
  • Caching Multiple Exceptions by single catch (Java 7)
  • Underscores in Numeric Literals (Java 7)
  • Diamond Operator
  • New file system API (NIO 2.0)
  • Fork and Join
  • Supporting dynamism


Java 6 Features | New Feature in Java

Following are the new features in SE 6.

  1. Changes in I/O
    This is a new feature added in Java SE 6, which has the ability to read text from a terminal without having it echo on the screen through
  2. Collections Framework Enhancement
    In Collection framework, we are able to improve the performance hashing function that is used by java.util.HashMap. It provides some new Collection interfaces also.
  3. Changes in jar and zip
    Jar and zip support has been enhanced in JDK 6. In this, two new compressed streams have been added. These are and
  4. Java Web Start Enhancements in version 6
    The cache format of Java Web Start and Plug-In has been fully changed. All dialogs have been redesigned and consolidated between Java Web Start and Plug-In to be more user-friendly.
  5. JMX API Enhancements
    Enhancement has been made to the JMX API in Java SE 6 like JMX API now completely supports Generics, MXBeans have been added and much more?
  6. Java Platform Debugger Architecture Enhancements
    JVMDI has been deleted in JAVA SE 6 and JPDA has been added. Some new Methods are included like boolean boolean canGetInstanceInfo() and much more?
  7. Java SE 6 Monitoring and Management Enhancements
    API provided by JAVA SE allows you to monitor and manage the JVM in the package JAVA SE 6 includes some enhancement to this API.
  8. New Package java.util.spi in JDK 6
    A new package Java.util.spi has been included in JAVA SE 6.
  9. Networking features and enhancements in Java SE version 6.0
    This feature includes enhancement in networkInterface, support for Internationalized Domain Names, HTTP Negotiate Authentication and much more?
  10. Enhancements in java.lang.Class and java.lang.reflect
    Some new Methods are included in java.lang.Class like : getInterfaces(), getClasses(), getConsturctors(), getMethod(String, Class?) and much more?.
  11. Enhancement in RMI for JDKTM 6
    java.rmi.MarshalledObject now support generics
  12. JAVA SE 6 Security Enhancements
    JAVA SE 6 has added support for some security functionality: the XML Digital signature API and implementation, Smart Card I/O API. And much more?
  13. Serialization Changes and Enhancements in JAVA SE Development Kit 6
    The new method ObjectStreamClass.lookupAny now used to obtain an ObjectStreamClass instance for a non-serializable Class
  14. JavaTM Virtual Machine Technology
    DTrace support has included in Java SE 6 HotSpot VM. The hotspot provider makes available probes that can be used to track the lifespan of the VM, thread start and stop events
  15. Scripting for the Java Platform
    By using this Features developers integrate Java technology and scripting languages by defining a standard framework and application programming interface (API)
  16. Leveraging Security in the Native Platform Using Java SE 6 Technology
    The JAVA SE 6 provide a large set of security APIs. These Security APIs span a wide range of areas, including cryptography public key infrastructure, secure communication, authentication, and access control.
  17. JAX-Web Services 2.0 With the Java SE 6 Platform
    Most exciting new features of the JAVA SE 6 is support for the Java API for XML Web Services (JAX-WS), version 2.0.

Factory Design Pattern in Java | Design Pattern Tutorials

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

interface ImageReader {    DecodedImage getDecodeImage();}class DecodedImage {    private String image;    public DecodedImage(String image) {        this.image = image;    }    @Override    public String toString() {        return image + ": is decoded";    }}class GifReader implements ImageReader {    private DecodedImage decodedImage;    public GifReader(String image) {        this.decodedImage = new DecodedImage(image);    }    @Override    public DecodedImage getDecodeImage() {        return decodedImage;    }}class JpegReader implements ImageReader {    private DecodedImage decodedImage;    public JpegReader(String image) {        decodedImage = new DecodedImage(image);    }    @Override    public DecodedImage getDecodeImage() {        return decodedImage;    }}public class FactoryMethodDemo {    public static void main(String[] args) {        DecodedImage decodedImage;        ImageReader reader = null;        String image = args[0];        String format = image.substring(image.indexOf('.') + 1, (image.length()));        if (format.equals("gif")) {            reader = new GifReader(image);        }        if (format.equals("jpeg")) {            reader = new JpegReader(image);        }        assert reader != null;        decodedImage = reader.getDecodeImage();        System.out.println(decodedImage);    }}

What is the difference between scaling horizontally vs scaling vertically? | SCALE UP VS SCALE OUT

Scaling vertically or scaling up is an old school of thought where we increase the processing power or memory of the hardware to scale up the performance. Here the issue is the cost for getting higher and higher configuration systems increases exponentially and there is always a limit to it.

Scale vertically means add more resources to the existing servers. This is done to increase RAM capacity or disk capacity. Hence the ability of the improved node to handle existing load is increased, but the load itself is unchanged.

In comparison with this, scaling out or horizontal scaling is, basically adding more and more nodes to handle the requests. This is basically distributing the load/requests to different resources to handle. There are different ways/levels of distribution that can be employed based on the scalability needs. 

To scale horizontally means add more servers. A decision to scale horizontally is made for example, to increase I/O concurrency or reduce the load on existing nodes. 


[Solved] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.8.1:jar (attach-javadoc) on project postman-web: MavenReportException: Error while creating archive: Unable to find javadoc command: The environment variable JAVA_HOME is not correctly set. -> [Help 1]


[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.8.1:jar (attach-javadoc) on project postman-web: MavenReportException: Error while creating archive: Unable to find javadoc command: The environment variable JAVA_HOME is not correctly set. -> [Help 1]


Current Java Doc Plugin:

<plugin>    <!-- JavaDoc Plugin to generate a JAR containing documentation from the project. -->    <groupId>org.apache.maven.plugins</groupId>    <artifactId>maven-javadoc-plugin</artifactId>    <version>2.8.1</version>    <executions>     <execution>      <id>attach-javadoc</id>      <goals>       <goal>jar</goal>      </goals>     </execution>    </executions></plugin>

Excepted Java Doc Plugin: Add configuration in java doc plugin

    <configuration>          <javadocExecutable>${java.home}/../bin/javadoc</javadocExecutable>    </configuration>


<plugin>    <!-- JavaDoc Plugin to generate a JAR containing documentation from the project. -->    <groupId>org.apache.maven.plugins</groupId>    <artifactId>maven-javadoc-plugin</artifactId>    <version>2.8.1</version>    <configuration>          <javadocExecutable>${java.home}/../bin/javadoc</javadocExecutable>        </configuration>    <executions>     <execution>      <id>attach-javadoc</id>      <goals>       <goal>jar</goal>      </goals>     </execution>    </executions>   </plugin>


What are Overused or abused programming techniques?

1.Comments in Code:

I just wish the University Professors would understand they don’t need to teach their students to write 10 lines of comments saying the following code is a for loop, iterating from 1 to a number of x. I can see that in the code!

Teach them to write self-documenting code first then appropriate commenting on what cannot be adequately self-documenting second. The software world would be a better place.
Teaching them to replace comments with the code would be a good start.

I shudder when I see a try catch that does nothing and is designed to handle dumb logic. In general try catches are overused, however in some cases are very useful.

2. The singleton design pattern: 

Sure, it’s a useful pattern but every time a new programmer learns about this pattern he starts trying to apply it to every single class he creates.

3. try catch Block: 
The evilest thing to protect dumb programming. putting everything in a try catch and doing nothing with the catch

        try        {            int total = 1;            int avg = 0;            var answer = total/avg;        }        catch (Exception)        {        }


  1. Using the compiler as a debugger.
  2. Ignoring compiler warnings or turning them off completely.
  3. Global variables.

5. Factory pattern

The Factory pattern is the most overused and abused design pattern.

I have come across numerous cases where a Factory class is coded when a simple constructor would be adequate.


Java 9 Features | New Feature in Java

Oracle has released Java 9 with a rich set of new features. It includes various upgrades to the Java programming, JVM, Tools, and libraries.

Java 9 Features

102: Process API Updates
110: HTTP 2 Client
143: Improve Contended Locking
158: Unified JVM Logging
165: Compiler Control
193: Variable Handles
197: Segmented Code Cache
199: Smart Java Compilation, Phase Two
200: The Modular JDK
201: Modular Source Code
211: Elide Deprecation Warnings on Import Statements
212: Resolve Lint and Doclint Warnings
213: Milling Project Coin
214: Remove GC Combinations Deprecated in JDK 8
215: Tiered Attribution for javac
216: Process Import Statements Correctly
217: Annotations Pipeline 2.0
219: Datagram Transport Layer Security (DTLS)
220: Modular Run-Time Images
221: Simplified Doclet API
222: jshell: The Java Shell (Read-Eval-Print Loop)
223: New Version-String Scheme
224: HTML5 Javadoc
225: Javadoc Search
226: UTF-8 Property Files
227: Unicode 7.0
228: Add More Diagnostic Commands
229: Create PKCS12 Keystores by Default
231: Remove Launch-Time JRE Version Selection
232: Improve Secure Application Performance
233: Generate Run-Time Compiler Tests Automatically
235: Test Class-File Attributes Generated by javac
236: Parser API for Nashorn
237: Linux/AArch64 Port
238: Multi-Release JAR Files
240: Remove the JVM TI hprof Agent
241: Remove the jhat Tool
243: Java-Level JVM Compiler Interface
244: TLS Application-Layer Protocol Negotiation Extension
245: Validate JVM Command-Line Flag Arguments
246: Leverage CPU Instructions for GHASH and RSA
247: Compile for Older Platform Versions
248: Make G1 the Default Garbage Collector
249: OCSP Stapling for TLS
250: Store Interned Strings in CDS Archives
251: Multi-Resolution Images
252: Use CLDR Locale Data by Default
253: Prepare JavaFX UI Controls & CSS APIs for Modularization
254: Compact Strings
255: Merge Selected Xerces 2.11.0 Updates into JAXP
256: BeanInfo Annotations
257: Update JavaFX/Media to Newer Version of GStreamer
258: HarfBuzz Font-Layout Engine
259: Stack-Walking API
260: Encapsulate Most Internal APIs
261: Module System
262: TIFF Image I/O
263: HiDPI Graphics on Windows and Linux
264: Platform Logging API and Service
265: Marlin Graphics Renderer
266: More Concurrency Updates
267: Unicode 8.0
268: XML Catalogs
269: Convenience Factory Methods for Collections
270: Reserved Stack Areas for Critical Sections
271: Unified GC Logging
272: Platform-Specific Desktop Features
273: DRBG-Based SecureRandom Implementations
274: Enhanced Method Handles
275: Modular Java Application Packaging
276: Dynamic Linking of Language-Defined Object Models
277: Enhanced Deprecation
278: Additional Tests for Humongous Objects in G1
279: Improve Test-Failure Troubleshooting
280: Indify String Concatenation
281: HotSpot C++ Unit-Test Framework
282: jlink: The Java Linker
283: Enable GTK 3 on Linux
284: New HotSpot Build System
285: Spin-Wait Hints
287: SHA-3 Hash Algorithms
288: Disable SHA-1 Certificates
289: Deprecate the Applet API
290: Filter Incoming Serialization Data
291: Deprecate the Concurrent Mark Sweep (CMS) Garbage Collector
292: Implement Selected ECMAScript 6 Features in Nashorn
294: Linux/s390x Port
295: Ahead-of-Time Compilation
297: Unified arm32/arm64 Port
298: Remove Demos and Samples
299: Reorganize Documentation