Important Points about Switch Statement

1. In switch case , we can only use integer or character data type. Other types are not allowed.


switch(char or int) {}

Not allowed:


2. An expression provided in the switch should result in a constant value otherwise it would not be valid.

Valid expressions for switch: Constant expressions allowed

switch(6 - 2 + 283)switch(6*2+6%4)

Invalid switch expressions for switch: Variable expression not allowed


3. Duplicate cases are not allowed.

 For instance below switch statement in c is illegal:

switch (expression)   { 
case 5: //... break;
case 2+3: //... break;

4. Order of case statements don’t matters

#include <iostream>using namespace std;int main(){    int age = 3;    switch (age) {      default: cout <<"You're not 1,2,3 or 4!n";      case 1:  cout <<"You're one.n";            break;      case 4:  cout <<"You're three or four.n";  break;      case 3:  cout <<"You're three.n";          break;      case 2:  cout <<"You're two.n";            break;    }}


You're three.

5. default statement is optional.Even if switch statement do not have a default statement, it would run without any problem.

This will run without any problems

switch (age) {  case 1:  printf("You're one.");            break;  case 2:  printf("You're two.");            break;  case 3:  printf("You're three.");  case 4:  printf("You're three or four.");  break;}

6. The variable expression are also not allowed in cases.
case i+4: is not allowed in switch, but it is valid on if-else statement.

7. The statements written above cases are never executed.

switch (age) {
age = age + 10 // This statement will never get executed case 1: printf("You're one."); break; case 2: printf("You're two."); break; case 3: printf("You're three."); case 4: printf("You're three or four."); break;}

8. If we will not use break keyword then all consecutive case statements will get executed.


#include <iostream>using namespace std;int main(){   int val=3;   switch(val) {      case 1: cout<<"Case1 "<<endl;      case 2: cout<<"Case2 "<<endl;      case 3: cout<<"Case3 "<<endl;      case 4: cout<<"Case4 "<<endl;      default: cout<<"Default "<<endl;    }   return 0;}


Case3 Case4 Default 

9. Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable.

Switch Statement in C++ with example

Switch Statement
Switch Statement

Switch Statement is used when we have multiple conditions and we need to perform different actions based on the conditions. 

Switch is similar to ifelse statements but limited to constant expressions.

Q: What is a constant expression in C++?
Q: What is a constant expression in C++?

Ans: When only constants are present in the expression then that expression is called constant expression.

In C++ constant expression can contain only integers and characters.

An output of the constant expression can be:

  1. An integer constant Ex: 1, 556, 988
  2. A character constant Ex: ‘A’ , ‘a’


It’s most typical syntax is:

switch (expression){  case constant expression 1:     group-of-statements-1;     break;  case constant expression 2:     group-of-statements-2;     break;  .  .  .  default:     default-group-of-statements}

Switch and if else
Switch and if else

Both of the following code have the same behavior, demonstrating the if-else equivalent of a switch statement:

switch exampleif-else equivalent
switch (x) {  case 1:    cout << "x is 1";    break;  case 2:    cout << "x is 2";    break;  default:    cout << "value of x unknown";  }
if (x == 1) {  cout << "x is 1";}else if (x == 2) {  cout << "x is 2";}else {  cout << "value of x unknown";}

Example of Switch Case
Example of Switch Case

#include<iostream>using namespace std;int main () {   char grade = 'A';   switch(grade) {      case 'A' :         cout << "Excellent!" << endl;          break;      case 'B' :      case 'C' :         cout << "Well done" << endl;         break;      case 'D' :         cout << "You passed" << endl;         break;      case 'F' :         cout << "Better try again" << endl;         break;      default :         cout << "Invalid grade" << endl;   }   cout << "Your grade is " << grade << endl;   return 0;}


ExcellentYour grade is A

Important Notes
Important Notes

1. break keyword is used to come out switch statement.

2. If we will not use break keyword then all consecutive case statements will get executed.


#include<iostream>using namespace std;int main(){   int val=3;   switch(val) {      case 1: cout<<"Case1 "<<endl;      case 2: cout<<"Case2 "<<endl;      case 3: cout<<"Case3 "<<endl;      case 4: cout<<"Case4 "<<endl;      default: cout<<"Default "<<endl;    }   return 0;}


Case3 Case4 Default 

[Solved]: Error installing Sense Plugin for Kibana

Problem Statement:./kibana plugin --install elastic/sense on the bin directory inside kibana folder, and I get :

ERROR  unknown command plugin  Usage: bin/kibana [command=serve] [options]  Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.  Commands:    serve  [options]  Run the kibana server    help  <command>   Get the help for a specific command  "serve" Options:    -h, --help                 output usage information    -e, --elasticsearch <uri>  Elasticsearch instance    -c, --config <path>        Path to the config file, can be changed with the CONFIG_PATH environment variable as well. Use mulitple --config args to include multiple config files.    -p, --port <port>          The port to bind to    -q, --quiet                Prevent all logging except errors    -Q, --silent               Prevent all logging    --verbose                  Turns on verbose logging    -H, --host <host>          The host to bind to    -l, --log-file <path>      The file to log to    --plugin-dir <path>        A path to scan for plugins, this can be specified multiple times to specify multiple directories    --plugin-path <path>       A path to a plugin which should be included by the server, this can be specified multiple times to specify multiple paths    --plugins <path>           an alias for --plugin-dir


Sense was renamed to Console and it is already available on Kibana 5.*. In Kibana, just click on Dev Tools:

enter image description here

How to find a substring in a string in bash?

METHOD 1:  wildcards)

You can use Marcus’s answer (* wildcards) outside a case statement, too, if you use double brackets:

string='My long string'if [[ $string = *"My long"* ]]; then  echo "It's there!"fi


It's there!

Note that spaces in the needle string need to be placed between double quotes, and the *wildcards should be outside.

METHOD 2:  regex approach

string='My long string' if [[ $string =~ "My long" ]] then echo "It's there!" fi


It's there!

Method 3:  case statement

case $(pwd) in  *path) echo "ends with path";;  path*) echo "starts with path";;  *path*) echo "contains path";;  *) echo "this is the default";;esac

How do I split a string on a delimiter in Bash?

You can set the internal field separator (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to IFS only takes place to that single command’s environment (to read ). It then parses the input according to the IFS variable value into an array, which we can then iterate over.

IN=";"IFS=';' read -ra ADDR <<< "$IN"for i in "${ADDR[@]}"; do    echo "$i"done


How to iterate over associative arrays in Bash?

Method 1:

The keys are accessed using an exclamation point: ${!array[@]}, the values are accessed using ${array[@]}.

You can iterate over the key/value pairs like this:

for i in "${!array[@]}"do  echo "key  : $i"  echo "value: ${array[$i]}"done

Note the use of quotes around the variable in the for statement (plus the use of @ instead of *). This is necessary in case any keys include spaces.

Method 2:

There’s nothing too surprising about associative arrays in bash, they are as you probably expect:

declare -A aaaa[hello]=worldaa[ab]=cd

The -A option declares aa to be an associative array. Assignments are then made by putting the “key” inside the square brackets rather than an array index. You can also assign multiple items at once:

declare -A aaaa=([hello]=world [ab]=cd)

Retrieving values is also as expected:

if [[ ${aa[hello]} == world ]]; then    echo equalfibb=${aa[hello]}

How do I find the version of bash I am running?

1. If you’re running within a bash shell, then the $BASH_VERSION environment variable should be set:

$ echo $BASH_VERSION4.2.10(1)-release

To extract the first part:

$ echo ${BASH_VERSION%%[^0-9.]*}4.2.10

2. To print out the version information for bash, use bash --version.

GNU bash, version 4.2.10(1)-release (i686-pc-linux-gnu)Copyright (C) 2011 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <>This is free software; you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.


How to Change Font Size in Eclipse IDE?

On Mac/Linux:

  1. Eclipse toolbar Eclipse → Preferences OR Command + , (comma)
  2. General  Appearance  Colors and Fonts  Basic  Text Font 
  3. edit and Apply


  1. On the Eclipse toolbar, select Window  Preferences.
  2. General  Appearance  Colors and Fonts  Basic  Text Font):

you can use this also:


Garbage Collector in Java | How Garbage Collection Works ?

Garbage Collection does exactly what it’s more fancier name “Automatic dynamic memory management” suggests. Dynamic memory is hard to manage and GC attempts to do that automatically and relieves the coder from the hard task.

GC basically attempts to take care of two basic scenarios remove garbage and avoid dangling pointers. They are very inter-related but are different scenarios

Garbage Collect

Consider a typical object reference graph. In the graph, every rectangle is an object and the arrows denote object references. So A is an object which references B. For a program to be able to use an object it should be in one of these reference chains. The reference chain starts from what is called Root and is typically references held in registers, on the stack as a local variable or global variables.


Let’s assume that due to some operation, A relinquishes the reference to B and the graph becomes something like this…


Now B and hence C is not reachable from any valid root in the program and hence have become Garbage (unreachable). The programmer must ensure to follow all reference and free (de-allocate them). One of the duties of a GC system is to automate this process by tracking down (using various algorithms) such objects and reclaim the memory used by them automatically. So in a GC system when the reference is broken it will figure out that B and hence C is not reachable and will de-allocate them.

Hanging/dangling reference

Let’s consider another object graph which is similar to the one above but in addition to A, another object A’ also has a reference to B (or in other words B is shared between them)


Even here after some operation object A doesn’t need a reference to B. The programmer does what he thinks is right and de-allocates B and C


However, A’ still has a reference to B and hence that reference is now hanging or in more specific term pointing to invalid memory and would typically return an unpredictable result when accessed. The key here is the unpredictable behavior. It is not necessary that program will crash. Unless the memory location in B is re-used it will seem to have valid data and de-references from A’ will work fine. So the failure will come up in unexpected ways and totally un-related places in the program and will make locating the root cause extremely hard.

GC helps by automatically taking care of both of the above scenarios and ensuring that the system doesn’t land up in either of them.


Mark and Sweep Garbage Collection Algorithm

The algorithm

At the top level the algorithm in C like Pseudocode looks as follows

void GC(){    HaltAllProcessing();    ObjectCollection roots = GetRoots();    for(int i = 0; i < roots.Count(); ++i)        Mark(roots[i]);    Sweep();}


The Mark procedure is recursive and acts as follows

void Mark(Object* pObj){    if (!Marked(pObj)) // Marked returns the marked flag from object header    {        MarkBit(pObj); // Marks the flag in obj header        // Get list of references that the current object has        // and recursively mark them as well        ObjectCollection children = pObj->GetChildren();        for(int i = 0; i < children.Count(); ++i)        {            Mark(children[i]); // recursively call mark        }	    }}

This is a recursive algorithm with heavy dose of simplification used and we will re-visit this in later posts on with actual implementation implications.

The recursion termination criteria is

  1. Either a node doesn’t have any children (leaf node)
  2. If it is already marked which ensures that we do not land in infinite recursion for circular references

At the end of this marking phase every object that can be reached using a reference from the roots would have been visited and it’s marked bit set.


Sweep starts by iterating through the entire memory and frees memory blocks that are not marked. It also clears the Mark bit so that subsequent GC passes can correctly mark/unmark them (resets the memory to pre-mark state).

void Sweep(){    Object *pHeap = pHeapStart;    while(pHeap < pHeapEnd)    {        if (!Marked(pHeap))            Free(pHeap); // put it to the free object list        else            UnMarkBit(pHeap);        pHeap = GetNext(pHeap);    }}

There are a bunch of assumptions here which has to be met. Some of them are that the

  1. Entire heap can be iterated over
  2. Both free memory blocks and allocated objects have the same sort of header that can be queried with Marked
  3. You can find the next memory block when given one block (GetNext implemented)
  4. There is some sort of free memory pool which tracks the list of free memory and you can add a block to it by calling Free(Object *)



What are the Benefits of Elasticsearch? | Elasticsearch Tutorial

Elasticsearch Benefits

1. Fast

By using distributed inverted indices, Elasticsearch quickly finds the best matches for your full-text searches from even very large data sets.

2. Easy-to-use APIs

Elasticsearch offers simple REST-based APIs, a simple HTTP interface, and uses schema-free JSON documents making it easy to index, search, and query your data.

3. Complimentary Tooling and Plug-ins

Elasticsearch comes integrated with Kibana, a popular visualization and reporting tool. It also offers built-in integration with Logstash to easily transform source data using pre-defined templates and load it data into your index. In addition, you can use a number of open-source Elasticsearch plug-ins such as language analyzers and suggesters to readily add rich functionality to your applications.

4. Near Real-time Index Updates

Elasticsearch index updates such as adding a new document to the index usually take one second or less before the updated data is available for search. This lets you use Elasticsearch for near real-time use cases such as application monitoring and anomaly detection.

5. Support for your Favorite Development Language

A variety of open source clients are available for Elasticsearch developers. Supported languages include Java, Python, PHP, JavaScript, Node.js, Ruby, and many others.

6. An Open-source

7. Build Charts and Dashboards within no time

8. Supports Distributed, Sharding, Replication, Clustering and Multi-Node Architecture

9. Supports both Structured and UN-Structured Data

10. Schema Free


Terminologies of Elasticsearch | Elasticsearch Tutorial

Cluster: A cluster is a collection of nodes that shares data.

Node: A node is a single server that is part of the cluster, stores the data, and participates in the cluster’s indexing and search capabilities.

Index: An index is a collection of documents with similar characteristics. An index is more equivalent to a schema in RDBMS.

Type: There can be multiple types within an index. For example, an e-commerce application can have used products in one type and new products in another type of the same index. One index can have multiple types of multiple tables in one database.

Document: A document is a basic unit of information that can be indexed. It is like a row in a table.

Shards and Replicas: Elastic Search indexes are divided into multiple pieces called shards, which allows the index to scale horizontally. Elastic Search also allows us to make copies of index shards, which are called replicas.


14 Rules for Faster-Loading Web Sites by Quora Founder Charlie Cheever

Steve Souders’ 14 rules are…

  • Make Fewer HTTP Requests
  • Use a Content Delivery Network
  • Add an Expires Header
  • Gzip Components
  • Put Stylesheets at the Top
  • Put Scripts at the Bottom
  • Avoid CSS Expressions
  • Make JavaScript and CSS External
  • Reduce DNS Lookups
  • Minify JavaScript
  • Avoid Redirects
  • Remove Duplicate Scripts
  • Configure ETags
  • Make AJAX Cacheable


Elasticsearch Pros and Cons | Advantages and Disadvantages of Elasticsearch

Advantages(Pros) of Elasticsearch:

BUILT ON TOP OF LUCENE – Being built on top of Lucene, it offers the most powerful full-text search capabilities.

FULL-TEXT SEARCH – Elasticsearch performs linguistic searches against documents and returns the documents that match the search condition. Result relevancy for the given query is calculated using TF/IDF algorithm.

DOCUMENT-ORIENTED – It stores complex entities as structured JSON documents and indexes all fields by default, providing a higher performance.

SCHEMA FREE – It stores a large quantity of semi-structured (JSON) data in a distributed fashion. It also attempts to detect the data structure, index the data present and makes it search-friendly.

RESTFUL API – Elasticsearch supports REST API which is light-weight protocol. We can query Elasticsearch using the REST API with Chrome plug-in Sense. Sense provides a simple user interface. Since plugin has features like autocomplete Elasticsearch query syntax, copying the query as cURL command.

Disadvantages of Elasticsearch:

  • Elasticsearch does not have multi-language support in terms of handling request and response data (only possible in JSON) unlike in Apache Solr, where it is possible in CSV, XML and JSON formats.
  • Elasticsearch also has a problem of Split brain situations but in rare cases.
  • It is not as good at being a data store as some other options like MongoDB, Hadoop, etc. For smaller use cases, it will perform fine. If you are streaming TB’s of data every day, you will find that it either chokes or loses data.
  • When you or your team are not that fluent at using the tool. Especially in the enterprise search use case, it is not as easy out of the box as, say, solutions from Algolia. To be sure, Elasticsearch is way more powerful and flexible, but it’s learning curve is much steeper.
  • When you can’t or won’t create a production-worthy setup because of economics. For test and dev, a single node will work fine. When you move to production, you should have no less than a 3-node/2-replica. 

Is Elasticsearch free? | Elasticsearch Tutorial

Elasticsearch is a free open source software.

You can run Elasticsearch on-premises, on Amazon EC2, or on Amazon Elasticsearch Service. With on-premises or Amazon EC2 deployments, you install Elasticsearch and other necessary software, provision infrastructure, and manage the cluster yourself. With Amazon Elasticsearch Service, you don’t have to worry about provisioning infrastructure or installing and maintaining Elasticsearch software. Amazon Elasticsearch Service is a fully managed service that simplifies time-consuming cluster management tasks such as software patching, failure recovery, backups, and monitoring.

How does Elasticsearch work? | Elasticsearch Tutorial

Elasticsearch is an open-source, RESTful, distributed search and analytics engine built on Apache Lucene.

  • You can send new data, called documents, to Elasticsearch using the API or ingestion tools such as Logstash and Amazon Kinesis Firehose.
  • Elasticsearch automatically stores the original document and adds a searchable reference to the document in the cluster’s index.
  • You can then search and retrieve the document using the Elasticsearch API.
  • You can also use Kibana, an open-source analytics, and visualization tool, to search, analyze, and dashboard your data.


When should we not use Elasticsearch? | Elasticsearch Tutorial

Don’t use Elasticsearch or use it with caution if:

  • You are looking for an ACID compliant data store.
  • You are looking for catering to transaction handling.
  • You are planning to do a highly intensive computational job in the data store layer.
  • You are looking to use this as a primary data store. If this is a requirement when data is inserted, Elasticsearch has to re-index and this would take some time and wouldn’t be available as and when the data was inserted and updated.
  • You are looking for a durable data store.


It is not as good at being a data store as some other options like MongoDB, Hadoop, etc. For smaller use cases, it will perform fine. If you are streaming TB’s of data every day, you will find that it either chokes or loses data.


What are elasticsearch real world examples? | real world use cases

Use Cases of Top Companies:

1. Facebook
Delivering a better help experience for over a billion users

2. Microsoft
Using the Logstash Azure module to streamline Azure monitoring

3. eBay
Searching across 800 million listings in subseconds

4. GoDaddy
Performing real-time anomaly detection to improve the customer experience

5. Accenture
Powering the search for the best client service

6. Netflix
Ensuring message delivery and operational excellence

7. Walmart
Gaining insights into customer purchasing patterns & store performance metrics

8. Uber
Aggregating business metrics to control critical marketplace behaviors

9. Tinder
Connecting people around the world

10. Adobe
Delivering a better user interface experience



What are use cases of Elasticsearch? | Elasticsearch Tutorial

  1. Log Analytics – Analyze un-structured and semi-structured logs generated by websites, mobile devices, servers, sensors, and more for a wide variety of applications such as digital marketing, application monitoring, fraud detection, ad tech, gaming, and IoT. Capture, pre-process, and load log data into Elasticsearch using Logstash, Amazon Kinesis Firehose, or Amazon CloudWatch Logs. You can then search, explore, and visualize the data using Kibana and the Elasticsearch query DSL to gain valuable insights about your users and applications.
  2. Full-Text Search – Provide your customers with a rich search and navigation experience. Elasticsearch supports faceting, which allows your customers to narrow their search results by value ranges for fields like price, product characteristics, and brands; ability to create advanced search criteria filters; search-as-you-type suggesters; and near real-time index updates.
  3. Distributed Document Store – Power your application with an easy to use JSON document-oriented storage platform. Elasticsearch provides a simple REST API, fast performance, powerful search capabilities, so you can build highly performant applications that can store and retrieve billions of documents.
  4. Real-time Application Monitoring – Capture activity logs across your customer-facing applications and websites. Use Logstash to push these logs to your Elasticsearch cluster. Elasticsearch indexes the data and makes it available for analysis in near real-time (less than one second). You can then use Kibana to visualize the data and perform operational analyses like identifying outages and problems. With Elasticsearch’s geospatial analysis, you can identify the geographical region where the problem is occurring. Troubleshooting teams can then search the index and perform statistical aggregations to identify root cause and fix issues.

Use Cases of Top Companies:

1. Facebook
Delivering a better help experience for over a billion users

2. Microsoft
Using the Logstash Azure module to streamline Azure monitoring

3. eBay
Searching across 800 million listings in subseconds

4. GoDaddy
Performing real-time anomaly detection to improve the customer experience

5. Accenture
Powering the search for the best client service

6. Netflix
Ensuring message delivery and operational excellence

7. Walmart
Gaining insights into customer purchasing patterns & store performance metrics

8. Uber
Aggregating business metrics to control critical marketplace behaviors

9. Tinder
Connecting people around the world

10. Adobe
Delivering a better user interface experience

Java Garbage Collection Algorithm – Mark and Sweep Algorithm

The mark-and-sweep algorithm is called a tracing garbage collector because is traces out the entire collection of objects that are directly or indirectly accessible by the program.

Root: –

The objects that a program can access directly are those objects which are referenced by local variables on the processor stack as well as by any static variables that refer to objects. In the context of garbage collection, these variables are called the roots.

Live Objects: –

An object is indirectly accessible if it is referenced by a field in some other (directly or indirectly) accessible object. An accessible object is said to be live . Conversely, an object which is not live is garbage.

The mark-and-sweep algorithm is divided into two phases:

Mark phase: –

The garbage collector traverses the graph of references from the root nodes and marks each heap object it encounters. Each object has an extra bit: the mark bit – initially the mark bit is 0. It is set to 1 for the reachable objects in the mark phase.

Sweep phase:

The GC scans the heap looking for objects with mark bit 0 – these objects have not been visited in the mark phase – they are garbage. Any such object is added to the free list of objects that can be reallocated. The objects with a mark bit 1 have their mark bit reset to 0.


What are the four pillars of OOPS?

Encapsulation: It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class.

Polymorphism: It is a feature, which lets us create functions with same name but different arguments, which will perform differently. That is function with same name, functioning in different way. Or, it also allows us to redefine a function to provide its new definition.

Abstraction: Abstraction refers to showing only the essential features of the application and hiding the details. In C++/Java, classes provide methods to the outside world to access & use the data variables, but the variables are hidden from direct access. This can be done access specifiers. For example, phone call, we don’t know the internal processing.

Abstraction = Encapsulation + Data Hiding

Inheritance: Inheritance is a way to reuse code. The class which is inherited from, is called the base class, and the class which inherits the code from the base class is called a derived class. A derived class can use all the functions which are defined in the base class, making the code reusable.


Who created coding?

Ada Lovelace is usually credited as being the first programmer. She worked with Charles Babbage and his difference engine and analysis engine projects (unfinished). So she wrote code but didn’t get to execute it.

During a nine-month period in 1842–1843, Ada Lovelace translated the memoir of Italian mathematician Luigi Menabrea about Charles Babbage‘s newest proposed machine, the analytical engine. With the article, she appended a set of notes which specified in complete detail a method for calculating Bernoulli numbers with the engine, recognized by some historians as the world’s first computer program.


Lovelace & Babbage and the creation of the 1843 ‘notes’

History of programming languages – Wikipedia

What are the best books to learn Java?


  • Head First Java, 2nd Edition
  • Thinking in Java (4th Edition)
  • Think Java
  • Introduction to Java by Sedgewick
  • Java in a Nutshell
  • Core Java Volume I–Fundamentals (9th Edition) (Core Series): Cay S. Horstmann
  • Java How To Program (late objects) by Paul Deitel, Harvey Deitel


  • Effective Java (2nd Edition): Joshua Bloch
  • Java Performance: Charlie Hunt, Binu John
  • Head First Servlets and JSP
  • SCJP by Kathy and Sierra
  • Java – The Complete Reference by Herbert Schildt.
  • Java Concurrency in Practice
  • Java Performance
  • The Java Programming Language, 4th Edition


  • Java Puzzlers: Traps, Pitfalls, And Corner Cases

What are the best resources to learn Java?

I am working with java around 6 years.

I have found that not all part of java tutorials on every famous website is good. so that I am providing java tutorial website link according to the quality of content in particular java part.

1. Java Basic from javatpoint

Java Tutorial | Learn Java – javatpoint

2. Java OOPS from beginnersbook :

Java tutorial: Learn Java Programming with examples

3. Java JDBC from jenkov :


4. Java collection from journaldev:

5. Java IO from journaldev:

6. Exception handling from jenkov :

Java Exception Handling

7. Java Inner Classes from javatpoint

Java Inner Class – javatpoint

8. Java Generics Tutorial from jenkov

Java Generics Tutorial

9. Java Multithreading Tutorial from journaldev

Java Concurrency / Multithreading Tutorial

10. Java Networking from javatpoint

Java Networking – javatpoint

Hope this will help.


How to extract text from pdf in python?

import csv    # spreadsheet outputimport re     # pattern matchingimport sys    # command-line argumentsimport zlib   # decompression# find deflated sectionsPARENT = b"FlateDecode"PARENTLEN = len(PARENT)START = b"stream\r\n"STARTLEN = len(START)END   = b"\r\nendstream"ENDLEN = len(END)# find output text in PostScript Tj and TJ fieldsPS_TEXT = re.compile(r"(?<!\\)\((.*?)(?<!\\)\)")# return desired per-person recordsRECORD = re.compile(r"Name : (.*?)Relation : (.*?)Address : (.*?)Age : (\d+)\s+Sex : (\w?)\s+(\d+)", re.DOTALL)def get_streams(byte_data):    streams = []    start_at = 0    while True:        # find block containing compressed data        p = byte_data.find(PARENT, start_at)        if p == -1:            # no more streams            break        # find start of data        s = byte_data.find(START, p + PARENTLEN)        if s == -1:            raise ValueError("Found parent at {} bytes with no start".format(p))        # find end of data        e = byte_data.find(END, s + STARTLEN)        if e == -1:            raise ValueError("Found start at {} bytes but no end".format(s))        # unpack compressed data        block = byte_data[s + STARTLEN:e]        unc = zlib.decompress(block)        streams.append(unc)        start_at = e + ENDLEN    return streamsdef depostscript(text):    out = []    for line in text.splitlines():        if line.endswith(" Tj"):            # new output line            s = "".join(PS_TEXT.findall(line))            out.append(s)        elif line.endswith(" TJ"):            # continued output line            s = "".join(PS_TEXT.findall(line))            out[-1] += s    return "\n".join(out)def main(in_pdf, out_csv):    # load .pdf file into memory    with open(in_pdf, "rb") as f:        pdf =    # get content of all compressed streams    # NB: sample file results in 32 streams    streams = get_streams(pdf)          # we only want the streams which contain text data    # NB: sample file results in 22 text streams    text_streams = []    for stream in streams:        try:            text = stream.decode()            text_streams.append(text)        except UnicodeDecodeError:            pass    # of the remaining blocks, we only want those containing the text '(Relation : '    # NB: sample file results in 4 streams    text_streams = [t for t in text_streams if '(Relation : ' in t]    # consolidate target text    # NB: sample file results in 886 lines of text    text = "\n".join(depostscript(ts) for ts in text_streams)    # pull desired data from text    records = []    for name,relation,address,age,sex,num in RECORD.findall(text):        name = name.strip()        relation = relation.strip()        t = address.strip().splitlines()        code = t[-1]        address = " ".join(t[:-1])        age = int(age)        sex = sex.strip()        num = int(num)        records.append((num, code, name, relation, address, age, sex))    # save results as csv    with open(out_csv, "w", newline='') as outf:        wr = csv.writer(outf)        wr.writerows(records)if __name__ == "__main__":    if len(sys.argv) < 3:        print("Usage: python {} input.pdf output.csv".format(__name__))    else:        main(sys.argv[1], sys.argv[2])

running at the command line:

python voters.pdf voters.csv

it produces a .csv spreadsheet:

How to extract text from pdf in python?


[Solved]: Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Problem Statement:

I get this error message as I execute my program in eclipse:

java.lang.OutOfMemoryError: GC overhead limit exceeded

How to solve this problem?


The GC throws this exception when too much time is spent in garbage collection for too little return, eg. 98% of CPU time is spent on GC and less than 2% of the heap is recovered.

This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small.

Method1: Best Solution

Just increase the heap size a little by setting this option in

Run → Run Configurations → Arguments → VM arguments

-Xms1024M -Xmx2048M

Xms – for minimum limit

Xmx – for the maximum limit

Method2: only go for method 2 when method 1 is not working

Enable the concurrent low pause collector with the command line option -XX:+UseConcMarkSweepGC

Method3: only go for method 3 when method 1 and 2 is not working

The GC throws this exception when too much time is spent in garbage collection for too little return, eg. 98% of CPU time is spent on GC and less than 2% of the heap is recovered.

This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small.

You can turn this off with the command line option -XX:-UseGCOverheadLimit

if you are not able to solve your problem then tell us in the comment section.

CPU usage more than 100% on iMac

Most modern macs are dual core. Meaning essentially two processors are on one chip. In Activity Monitor on OSX, each core can be used up to 100% so, at full capacity, Activity Monitor will report 200-800% depending on the horsepower of your Mac. (some mac pros may exceed 800% or 8 cores)

The % CPU is relative to 1 core, so 726% is using almost 8 cores. A core is loosely defined, so 1 Hyper-Threaded, “virtual” core looks like 2 cores to Activity Monitor.

Top 10 Machine Learning Algorithms | You Should Know to Become a Data Scientist

Machine Learning is the science of getting computers to learn and act like humans do, and improve their learning over time in autonomous fashion, by feeding them data and information in the form of observations and real-world interactions

Here is the list of commonly used machine learning algorithms. These algorithms can be applied to almost any data problem.

Popular Machine learning algorithms are :

  1. Linear Regression
  2. Logistic Regression
  3. Decision Tree
  4. SVM
  5. Naive Bayes
  6. kNN
  7. K-Means
  8. Random Forest
  9. Dimensionality Reduction Algorithms
  10. Gradient Boosting algorithms such as GBM, XGBoost, LightGBM, CatBoost


Top 10 Machine Learning Applications in Real World


Top 10 Real World Examples of Machine Learning and AI

What is the difference between using generic type and a wildcard in Java Generics?

There are certain places, where wildcards and type parameters do the same thing. But there are also certain places, where you have to use type parameters. If you want to enforce some relationship on the different types of method arguments, you can’t do that with wildcards, you have to use type parameters.


Suppose you want to ensure that the src and dest list passed to copy() method should be of the same parameterized type, you can do it with type parameters like so:

public static <T extends Number> void copy(List<T> dest, List<T> src)

Here, you are ensured that both dest and src have a same parameterized type for List. So, it’s safe to copy elements from src to dest.

But, if you go on to change the method to use a wildcard:

public static void copy(List<? extends Number> dest, List<? extends Number> src)

It won’t work as expected. In the 2nd case, you can pass List<Integer> and List<Float> as dest and src. So, moving elements from src to dest wouldn’t be type-safe anymore. If you don’t need such kind of relation, then you are free not to use type parameters at all.


Some other differences between using wildcards and type parameters are:

  • If you have only one parameterized type argument, then you can use a wildcard, although type parameter will also work.
  • Type parameters support multiple bounds, wildcards don’t.
  • Wildcards support both upper and lower bounds, type parameters just support upper bounds. So, if you want to define a method that takes a List of type Integer or it’s superclass, you can do:
public void print(List<? super Integer> list) // OK

but you can’t use type parameter:

public <T super Integer> void print(List<T> list) // Won't compile

source: stackoverflow

Top 10 Machine Learning Applications in Real World

Below are some real-world examples of machine learning that really ground what machine learning is all about.

1. Speech conversion from one language to other

2. Medical diagnostics for detecting diseases

3. Suspicious activity detection from CCTV

CCTV images of a possible petty crime

4. Stock Trading

5. Text and Speech Recognition

6. Web Search and Recommendation Engines:

7. Computational Biology & Drug Discovery/Design

8. Credit Card Fraud Detection

9. Face Detection

10. Spam Detection


1. Speech conversion from one language to other

2. Medical diagnostics for detecting diseases

3. Suspicious activity detection from CCTV

4. Stock Trading

5. Text and Speech Recognition

6. Web Search and Recommendation Engines:

7. Computational Biology & Drug Discovery/Design

8. Credit Card Fraud Detection

9. Face Detection

10. Spam Detection

Top 10 Real World Examples of Machine Learning and AI

1. Apple Siri: 

For Speech Understanding

2. Microsoft Cortana: 

For Speech Understanding

3. Amazon Echo: 

Echo smart speakers that allow you to integrate Alexa into your living room and use voice commands to ask natural language questions, play music, order pizza, hail an Uber, and integrate with smart home devices.

 4. Facebook: 

When you upload photos to Facebook, the service automatically highlights faces and suggests friends to tag. How can it instantly identify which of your friends is in the photo? Facebook uses AI to recognize faces.  

5. Google Maps: 

Google Maps (Maps) can analyze the speed of movement of traffic at any given time

 6. Google Search: 

Find recognize input, find relevant searches, predict which results are most relevant to us, return a ranked output

7. Gmail: 

Spam Filters, Smart Email Categorization

8. PayPal: 

For Credit Card Fraud Detection

9. Netflix: 

Recommend similar products (e.g., Netflix, Amazon, etc.)

10. Uber: 

Uber’s Head of Machine Learning Danny Lange confirmed Uber’s use of machine learning for ETAs for rides, estimated meal delivery times on UberEATS, computing optimal pickup locations, as well as for fraud detection.

Uber heat map

Image: Uber heat map

What is WEKA? | Weka Tutorial


Weka is a collection of machine learning algorithms for solving real-world data mining problems. It is written in Java and runs on almost any platform. The algorithms can either be applied directly to a dataset or called from your own Java code.


  • Collection of ML algorithms – open source Java package
  • Schemes for classification include:
    • decision trees, rule learners, naive Bayes, decision tables, locally weighted regression, SVMs, instance-based learners, logistic regression, voted perceptrons, multi-laver perceptron
  • Schemes for numeric prediction include:
    • linear regression, model tree generators, locally weighted regression, instance-based learners, decision tables, multi-laver perceptron
  • Meta-schemes include:
    • Bagging, boosting, stacking, regression via classification, classification via regression, cost sensitive classification
  • Schemes for clustering:
    • EM and Cobweb

How to prepare for java interview for freshers?

Preparation for interview totally depended on your Experience. I am giving you some suggestion according to your experience.

Java interview preparation guide for freshers

If you are a college graduate(or  you are fresher to Java) then you need to prepare only for Core Java related questions like –

Java Basics Interview Questions And Answers

Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. Read more…

Java OOPs Interview Questions and Answers

Object Oriented programming is a programming style which is associated with the concepts like class, object, Inheritance, Encapsulation, Abstraction, Polymorphism. Most popular programming languages like Java,. Read more…

Java String Interview Questions and Answers

String is a Class in Java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings. A string is used in almost all the Java applications and there are some . Read more…

Java Exception Handling Interview Questions

An exception is an abnormal event that occurs during the execution of a program and disrupts the normal flow of the program’s instructions.Exception Handling is a mechanism to handle runtime errors. Read more…

Java Multithreading Interview Questions and Answers

The thread is an independent path of execution i.e. Thread is a lightweight process. It’s way to take advantage of multiple CPU .Read more…

JDBC Interview Questions and Answers

JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers to connects to the database. JDBC Driver is a software component that enables java application: Read more…

here is the list of topics I suggest to any Java developer who is serious about interviews.

  • Java Fundamentals
  • Object-Oriented Concepts
  • Data Structure and Algorithms
  • Multithreading, concurrency, and thread basics
  • Date type conversion and fundamentals
  • Garbage Collection
  • Java Collections Framework
  • Array
  • String
  • GOF Design Patterns
  • SOLID design principles
  • Abstract class and interface
  • Java basics e.g. equals and hashcode
  • Generics and Enum
  • Java IO and NIO
  • Common Networking protocols
  • Data structure and algorithm in Java
  • Regular expressions
  • JVM internals
  • Java Best Practices
  • JDBC
  • Date, Time and Calendar
  • XML Processing in Java
  • JUnit
  • Programming questions

Websites to learn basics of java.

What is Root Cause Analysis (RCA)?

The Root Cause Analysis Process:

Root cause analysis (RCA) is a method of problem-solving used for identifying the root causes of faults or problems.

RCA has five identifiable steps.

1. Define the Problem
2. Collect Data
3. Identify Possible Causal Factors
4. Identify the Root Cause(s)
5. Recommend and Implement Solutions

What Is Problem Solving? | The stages of problem solving

The process of working through details of a problem to reach a solution. Problem-solving may include mathematical or systematic operations and can be a gauge of an individual’s critical thinking skills.

Having good, strong problem-solving skills can make a huge difference to your career.

To be a successful problem solver you need to understand what the stages involve and follow them methodically whenever you encounter a problem.
To be a successful problem solver you must go through these stages:

  • Recognizing and defining the problem 
  • Finding possible solutions
  • Choosing the best solution
  • Implementing the solution


What are problems? | A Problem Solving Skills Guide

Problems can be defined broadly as situations in which we experience uncertainty or difficulty in achieving what we want to achieve

For example:

  • Stopping smoking is a problem when you decide you want to stop but cannot.
  • A computer malfunction is a problem if it prevents you completing work on time.
  • An excessive workload is a problem when it interferes with your ability to work effectively.
  • Poor communication is a problem when it reduces the efficiency of an organization.

Why people fail to solve problems effectively? | A Problem Solving Skills Guide

Solving problems is a complex process and each of us is better at the skills required at some stages than others.

The following is a list of some of the reasons why people fail to find effective solutions:

1. Not being methodical
2. Lack of commitment to solving the problem
3. Misinterpreting the problem
4. Lack of knowledge of the techniques and processes involved in problem-solving
5. Inability to use the techniques effectively
6. Using a method inappropriate to the particular problem
7. Insufficient or inaccurate information
8. Inability to combine analytical and creative thinking
9. Failure to ensure effective implementation
10. Only thinking of the first-level explanation


1. A problem exists when an obstacle prevents you from reaching an objective.
2. Problem-solving can be divided into stages, which you must follow methodically. If you want to be sure of finding an effective solution.
3. Solving problems effectively requires a con­trolled mixture of analytical and creative thinking skills.

[Solved]: ERROR: transport error 202: gethostbyname: unknown host ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510) JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [debugInit.c:750]

Problem Statement:
Eclipse Mac OS X Debug Error:
ERROR: transport error 202: gethostbyname: unknown host
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [debugInit.c:750]

Solution 1:

I had exactly the same issue (on Mac OS), in my case the line in /etc/host was commented out:    localhost

Solution 2:

  • You will see three 3  hosts, hosts~orig, hosts.equiv on /etc/hosts
  • Where hosts file is Zero byte in size and hosts~orig contains all settings
  • Delete hosts file 
  • Create duplicate of hosts~orig and rename as hosts

It’s explained in Eclipse Wiki:

How to extract the contents of a jar file with command line?


The basic command to use for extracting the contents of a JAR file is:

jar xf jar-file [archived-file(s)]

Let’s look at the options and arguments in this command:

  • The x option indicates that you want to extract files from the JAR archive.
  • The f options indicate that the JAR file from which files are to be extracted is specified on the command line, rather than through stdin.
  • The jar-file argument is the filename (or path and filename) of the JAR file from which to extract files.
  • archived-file(s) is an optional argument consisting of a space-separated list of the files to be extracted from the archive. If this argument is not present, the Jar tool will extract all the files in the archive.


To extract the files from a jar file,use,x, as in:

$ jar xf myFile.jar

To extract only certain files from a jar file, supply their filenames:

$ jar xf myFile.jar foo bar

Note that a jar file is a Zip file, and any Zip tool (such as 7-Zip) can look inside the jar. Useful for systems that don’t have a jar command Ex  CentOS

unzip file.jar -d dir_name_where_extracting


How to view the Contents of a JAR File | Eclipse Tutorial

In this tutorial, I will show you how to install in Eclipse one of the most popular java decompilers – JD.

  • Download and unzip the JD-Eclipse Update Site,
  • Launch Eclipse,
  • Click on Help > Install New Software…”,
  • Click on the button Add… to add a new repository,
  • Enter JD-Eclipse Update Site and select the local site directory(where you have unzipped)
  • Check “Java Decompiler Eclipse Plug-in”,
  • Next, next, next… and restart Eclipse.

That’s it.

what if JD decompiler doesn’t work? In order to fix this you just need to perform the following steps:

  • Go to Preferences
  • General > Editors > File Associations
  • Select “*.class without source

  • Click on Add.. in Internal Editors select JD Class File Viewer

  • make it Default. Don’t forget to click on the default

To check that everything is OK now, place the cursor on the class which doesn’t have the source code and press the “F3” button(you can use double click also).

That’s all.

Top 20 Most Inspiring Company Mission Statements


‘To give everyone the power to create and share ideas and information instantly, without barriers.’


‘To inspire and nurture the human spirit – one person, one cup  and one neighborhood at a time.’


‘McDonald’s brand mission is to be our customer’s favorite place and way to eat and drink.’


‘Our mission is to enable people and businesses throughout the world to realize their full potential. We consider our mission statement a commitment to our customers. We deliver on that commitment by striving to create technology that is accessible to everyone – of all ages and abilities. ‘


‘Facebook’s mission is to give people the power to share and make the world more open and connected.’


‘We go further to make our cars better, our employees happier and our planet a better place to be.’


‘Google’s mission is to organize the world’s information and make it universally accessible and useful.’


‘To refresh the world in mind, body and spirit. To inspire the moments of optimism and happiness through our brands and actions. To create value and make a difference.’


‘Provide a global trading platform where practically anyone can trade practically anything.’


‘To bring inspiration and innovation to every athlete in the world. If you have a body, you are an athlete.’

“To make it easy to do business anywhere.”


“To build the Web’s most convenient, secure, cost-effective payment solution.”


“To deliver information on the people, ideas and technologies changing the world to our community of affluent business decision makers.”


“Uber is evolving the way the world moves. By seamlessly connecting riders to drivers through our apps, we make cities more accessible, opening up more possibilities for riders and more business for drivers.”


“Shape the future of the Internet by creating unprecedented value and opportunity for our customers, employees, investors, and ecosystem partners.”


“To be the catalyst in communities of customers, contributors, and partners creating better technology the open source way.”


“To improve its customers’ financial lives so profoundly, they couldn’t imagine going back to the old way.”


“Improving people’s lives through meaningful innovation.”


“To move the web forward and give web designers and developers the best tools and services in the world.”


“We save people money so they can live better.”

Shell/Bash scripting cheatsheet

Shell Bash Scripting Cheatsheet


$ NAME="Interview Bubble"$ echo $NAMEInterview Bubble
# Each command starts on a new line, or after semicolonecho 'This is the first line'; echo 'This is the second line'

This is the first line
This is the second line

Shell Variables

$variable ="Hello"echo $variable


Steps in creating a Shell Script

1. Create a file using a vi editor(or any other editor).  Name  script file with extension .sh

$ vi

2. Start the script with #! /bin/sh

3. Write some code.

4. Save the script file as

#! /bin/sh# This is a commentecho "Hello World"  # This ia also a comment

5. For executing the script type bash

$ bash Hello World

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;    }}