April 26, 2016

Part 3: Java Design Pattern Interview Questions & Answers (Factory and Abstract Factory)

In Part 1 of Java Design Pattern Interview Questions & Answers, we discussed the basics. In Part 2, we implemented the Singleton design pattern. In Part 3, we will understand Factory and Abstract Factory design patterns. 

What is a static factory or factory method Design Pattern?

It is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In the Factory pattern, we create an object without exposing the creation logic to the client and refer to a newly created object using a common interface.

Part 2: Java Design Pattern Interview Questions & Answers (All About Singleton Design Pattern)

In Part 1 of Java Design Pattern Interview Questions & Answers, we discussed the basics. Now in Part 2, we will discuss the Singleton design pattern in detail. 

What is the Singleton pattern?

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

This pattern involves a single class that is responsible to create an object while making sure that only a single object gets created. This class provides a way to access its only object which can be accessed directly without the need to instantiate the object of the class.

There are many classes in JDK which is implemented using Singleton pattern like : Java.lang.Runtime with getRuntime() method, Java.awt.Toolkit with getDefaultToolkit() and Java.awt.Desktop with getDesktop() etc.

Part 2: Scenario Based Java Design Pattern Interview Questions & Answers

Scenario 1

  • A company named XYZ Retail is in the business of selling Books, CD's and Cosmetics. 
  • Books are sales tax exempt and CDs and Cosmetics have a sales tax of 10%. 
  • CD's can be imported and attracts an import tax of 5%. 
  • Write a simple shopping basket program, which will calculate extended price (qty * (unitprice + tax)) inclusive of tax for each item in the basket?

Java Solution
We will first create the TaxCalculator interface and its implementation TaxCalculatorImpl.



Goods class is abstract as it implements the common behavior of Book, CDs, and Cosmetics. Also it composes (i.e composition) 'TaxCalculator' to perform the tax calculation based on if the good is imported and if sales tax is applicable.

Now, we will create Book, CDs, and Cosmetics classes that extends the shared behavior (inherits the shared behavior of Goods). The isTaxable & isImported are specific to the product. We can add new products in the future with specific taxable & importable behaviors.



-K Himaanshu Shuklaa

Part 1: Java Design Pattern Interview Questions & Answers

What are Design Patterns?
Design patterns are tried and tested ways to solve particular design issues by various programmers in the world. We can say design patterns are an extension of code reuse.

Design patterns versus frameworks
Are design patterns the same thing as frameworks? The answer to that is NO. Design patterns are more like general guidelines on how to solve specific programming problems, but they do not specify the detailed code that’s necessary to solve those problems.

What are the benefits of using design patterns?
  • Reusable in multiple projects.
  • Design patterns make our code easy to understand and debug.
  • They provide an industry standard approach to solve a recurring problem.
  • Design patterns also provide transparency to the design of an application.

April 24, 2016

#Java: Part 14-How does substring() inside String works?

Substring creates a new object out of source string by taking a portion of the original string. It is defined in defined in java.lang.String class.

substring() has two variants:-
  • substring(int beginIndex): returns the substring starting from the specified index. The beginIndex is inclusive. This method throws IndexOutOfBoundsException if the beginIndex is less than zero or greater than the length of String.
  • substring(int beginIndex, int endIndex): returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Thus the length of the substring is endIndex-beginIndex (beginIndex is inclusive and endIndex is exclusive while getting the substring).
If beginIndex is equal to length in substring(int beginIndex) it won't throw IndexOutOfBoundException instead it will return empty String. Same is the case when beginIndex and endIndex is equal.

#Java: Part 13 JDBC Interview Questions And Answers

> > Part 12 Serialization Interview Questions and Answers for Experienced Developers

What is JDBC?
JDBC (Java Database Connectivity) 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.

April 22, 2016

Madhuri shoots barefoot for the opening act of So You Think You Can Dance..

Everyone is aware of Madhuri’s love for dance. She believes that dance is an art and she has carved her niche in it. Madhuri Dixit who will be soon seen as the judge on &TV’s latest offering ‘So You Think You Can Dance - Ab India Ki Bari’ has done something phenomenal for the show. Read on to know more!

Tiger Shroff joins &TV’s 'So You Think You Can Dance'..


The new Baaghi in town, Tiger Shroff dropped by on the sets of &TV’s upcoming dance reality show SO YOU THINK YOU CAN DANCE. The actor showed off his cool dance moves and impressed everyone with his ‘Street’ style of dancing.

April 21, 2016

BARC Ratings (Impressions)- Week 15, 2016

  
In week 15 (9-15 April, 2016) of the BARC Ratings, Star Plus continued to be the most watched Hindi GEC. Colors remained at No.2 followed by Zee TV at No.3. Life OK took a leap to the fourth spot from seventh in week 14. Sony Pal remained at No.5.

April 15, 2016

A Fairy Tale Visit To Neuschwanstein Castle!!

Neuschwanstein Castle has been on my bucket list for ages because of its mesmerizing aura, breathtaking views and incredible artworks. That's why for me this visit was very, very thrilling. The kind of excitement where I let out little screams in complete anticipation.😻

April 13, 2016

All About jQuery..

What is jQuery?
Its a'lightweight' javascript library. With jQuery we, 'write less, and do more'.  jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation. jQuery run exactly the same in all major browsers, including Internet Explorer 6.

April 07, 2016

Java Reflection API Interview Questions and Answers..

What is Reflection?
Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. That means with reflection, we can examine or modify the runtime behavior of applications running in the Java virtual machine.

Reflection API usage can break the design pattern such as Singleton pattern by invoking the private constructor i.e violating the rules of access modifiers.

April 06, 2016

#Java: Part 12 Java Serialization Interview Questions and Answers for Experienced Developers(Serializable and Externalizable)

> > Part 11-Core Java Interview Questions and Answers: Comparator vs Comparable


What are Serialization and De-serialization in Java?

Serialization is a process by which you can save or transfer the state of an object by converting it to a byte stream.

During Serialization, the Object is converted into a binary format, which can be persisted into a disk or sent over the network to any other running Java virtual machine. During deserialization, the reverse process is performed by creating an object from a binary stream.

FYI, the serialization process is platform-independent, which means an object serialized on one platform can be deserialized on a different platform.

#Java: Part 11-Core Java Interview Questions and Answers: Comparator vs Comparable

> > #Java: Part 10-Core Java Interview Questions and Answers

Difference between Comparator and Comparable in Java

Comparable and Comparator both are interfaces and can be used to sort collection elements.

#Java: Part 10-Core Java Interview Questions and Answers

> > Part 9-Core Java Interview Questions and Answers(Java Memory Model, Garbage Collectors in Java)

How  do you prevent SQL Injection in Java Code?
In SQL Injection attack, malicious user pass SQL meta-data combined with input which allowed them to execute sql query of there choice.

ALSO READ: JDBC Interview Questions And Answers

PreparedStatement can be used to avoid SQL injection in Java code. Use of the PreparedStatement for executing SQL queries not only provides better performance but also shield your Java and J2EE application from SQL Injection attack. All the parameters passed as part of place-holder will be escaped automatically by JDBC Driver.

#Java: Part 9-Core Java Interview Questions and Answers(Java Memory Model, Garbage Collectors in Java)

> > Part 7-Core Java Interview Questions and Answers

What is JIT compiler in Java?
  • JIT stands for Just-In-Time compiler. 
  • It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor. 
  • The JIT compiler is by default enabled and is activated whenever a Java method is invoked. The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it 'just in time' to execute. 
  • Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.
Which are the different segments of memory ?
  • Stack Segment : contains local variables and Reference variables(variables that hold the address of an object in the heap)
  • Heap Segment : contains all created objects in runtime, objects only plus their object attributes (instance variables)
  • Code Segment :  The segment where the actual compiled Java bytecodes resides when loaded.

#Java: Part 8-Core Java Interview Questions and Answers (Interface, final, finalize, finally)

> > Part 7-Core Java Interview Questions and Answers (Generics)

What is an interface and what are the advantages and disadvantage of using interfaces in Java?
  • With interfaces, we can achieve abstraction in Java along with abstract class.
  • Interface in java is declared using keyword interface and it represent a Type like any Class in Java. A reference variable of type interface can point to any implementation of that interface in Java.
  • All variables declared inside interface is implicitly public final variable or constants. which brings a useful case of using Interface for declaring Constants.
  • All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword. You can not define any concrete method in interface (till java 7). That's why interface is used to define contracts in terms of variables and methods and you can rely on its implementation for performing job.

#Java: Part 7-Core Java Interview Questions and Answers (Generics)

> > Part 6-Core Java Interview Questions and Answers (Wrapper classes, Static variables, methods and imports)

What is Generics in Java ?
Generics is introduced in J2SE 5 to deal with type-safe objects. Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, provides compile time type-safety and ensures that you only insert correct Type in collection and avoids ClassCastException in runtime.

#Java: Part 6-Core Java Interview Questions and Answers (Wrapper classes, Static variables, methods and imports)

> >  Part 5-Core Java Interview Questions and Answers (Clone and Immutability)

What are Wrapper classes?
A wrapper class wraps (encloses) around a data type and gives it an object appearance. They include methods to unwrap the object and give back the data type. e.g
int intCount = 100;
Integer wrapperIntCount = new Integer(intCount); //this is called Boxing
int intCountBack = wrapperIntCount.intValue(); //thats unBoxing

There are mainly two uses with wrapper classes:
1) To convert simple data types into objects, i.e to give object form to a data type.
2) To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

#Java: Part 5-Core Java Interview Questions and Answers (Clone and Immutability)

> > Part 4-Core Java Interview Questions and Answers (HashCode & equals())

What is a Cloneable interface and what all methods does it contain?
Cloneable is a declaration that the class implementing it allows cloning or bitwise copy of it's object state. It is not having any method because it is a Marker interface.

How clone method works in Java?
The clone() method from java.lang.Object class is used to create a copy of an Object in Java. This copy is known as a clone of original instance. Constructor is not called during cloning of Object in Java.

clone() method is declared as protected and native in Object class. Since its convention to return clone() of an object by calling super.clone() method, any cloning process eventually reaches to java.lang.Object clone() method.

#Java: Part 4-Core Java Interview Questions and Answers (HashCode & equals())

> > Part 3-Core Java Interview Questions and Answers

When you are writing equals() method, which other method or methods you need to override? 
The right answer is hashCode(). Since equals and hashCode has there contract, so overriding one and not other, will break contract between them. Interviewer may ask about what are those contracts, what happens if those contracts breaks etc.

#Java: Part 3-Core Java Interview Questions and Answers

> > Part 2-Core Java Interview Questions and Answers (Polymorphism, Overloading and Overriding)

What is Encapsulation?
It means binding the data with the code that manipulates it, it keeps the data and the code safe from external interference

By Encapsulation we can keep all the related members (variables and methods) together in an object.

The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. However if we setup public getter and setter methods to update (for e.g. void setUserName(String userName))and read (for e.g.  int getUserName()) the private data fields then the outside class can access those private data fields via public methods.

This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is also known as 'Data Hiding' or 'Information Hiding'.

The idea of encapsulation is to keep classes separated and prevent them from having tightly coupled with each other.

Encapsulated code should have following characteristics:
  • Everyone knows how to access it.
  • Can be easily used regardless of implementation details.
  • There shouldn’t any side effects of the code, to the rest of the application.
Difference between Abstraction and Encapsulation in Java?
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Abstraction is the concept of hiding irrelevant details.In other words make complex system simple by hiding the unnecessary detail from the user.

Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

What's the difference between "==" and "equals()"?
Both equals() and "==" operator in Java is used to compare two objects to check whether they are equal or not. The main difference between equals method and  the == operator is that former is a method and later is an operator.

Since operator overloading is not supported by Java, that's why== behaves identical for every object, but user override equals() method and write their own logic to compare the objects based on the business rules.

Also ReadHashCode & equals() Interview Questions in Java

== is used to compare both primitive and objects, however equals() is only used for objects comparison.

A == B does object reference matching if both A and B are an object and only return true if both are pointing to the same object in the heap space, on the other hand, A.equals(B) is used for logical mapping and its expected from an object to override this method to provide logical equality.

What are three types of loops in Java?
Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java:
  • For loops are used in java to execute statements repeatedly for a given number of times. For loops are used when number of times to execute the statements is known to programmer.
  • While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, condition is checked first before execution of statements.
  • Do While loop is same as While loop with only difference that condition is checked after execution of block of statements. Hence in case of do while loop, statements are executed at least once. 
What is an infinite Loop? How infinite loop is declared?
An infinite loop runs without any condition and runs infinitely. An infinite loop can be broken by defining any breaking logic in the body of the statement blocks. e.g:

for (;;)
{
    //perform operations
    ..
    ..
    //Add the loop breaking logic
    if(loopBreaker)
    {
        break;
    }
}


What is the difference between continue and break statement?
When a break keyword is used in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken and loop continues with next iteration.

What is the difference between double and float variables in Java?
float takes 4 bytes in memory while Double takes 8 bytes in memory in Java. Float is single precision floating point decimal number while Double is double precision decimal number.

What is ternary operator?
Ternary operator , also called conditional operator is used to decide which value to assign to a variable based on a Boolean value evaluation. It’s denoted as ?

e.g, in the below example isAdult will be set to true if the age is greater than or equal to 18, else it will be set as false.
boolean isAdult=(age>=18) ? true : false;

Does Importing a package imports its sub-packages as well in Java?
In java, when a package is imported, its sub-packages aren’t imported and if required we need to import them separately.

Can you call a abstract method from a non abstract method ?
Yes, we can call a abstract method from a Non abstract method in a Java abstract class

What is an Inner class?
Inner class are defined inside the body of another class (known as outer class). These classes can have access modifier or even can be marked as abstract and final.

All the Inner classes have special relationship with outer class instances. This relationship allows them to have access to outer class members including private members too.

There are four types of Inner classes:
1) Inner class
2) Method-local inner class
3) Anonymous inner class
4) Static nested class

What is the difference between an Inner Class and a Sub-Class?
An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.

How can we copy Date object into another date Object without using a reference?
e.g:
Date mydate = new Date();
Date copiedmydate = new Date(mydate.getTime());

With Java 8 you can use the following null-safe code.
Optional.ofNullable(mydate)
.map(Date::getTime)
.map(Date::new)
.orElse(null);

ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

#Java: Part 2-Core Java Interview Questions and Answers (Polymorphism, Overloading and Overriding)

>> Check the Part 1-Core Java Interview Questions and Answers

What is Inheritance?
It is the mechanism by which an object acquires some/all properties of another object. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it.

The existing (or original) class is called the base class or super class or parent class. The new class which inherits from the base class is called the derived class or sub class or child class. Inheritance implements the “Is-A” or “Kind Of/ Has-A” relationship.

#Java: Part 1-Core Java Interview Questions and Answers

< < Part 2-Core Java Interview Questions and Answers (Polymorphism, Overloading and Overriding)

What is Association, Aggregation and Composition?
Association is a relationship between two separate classes which can be of any type say one to one, one to may etc. It joins two entirely separate entities.

Aggregation is a special form of association which is a unidirectional one way relationship between classes (or entities), for e.g. Wallet and Money classes. Wallet has Money but money doesn’t need to have Wallet necessarily so its a one directional relationship. In this relationship both the entries can survive if other one ends. In our example if Wallet class is not present, it does not mean that the Money class cannot exist.

Composition is a restricted form of Aggregation in which two entities (or you can say classes) are highly dependent on each other. For e.g. Human and Heart. A human needs heart to live and a heart needs a Human body to survive. In other words when the classes (entities) are dependent on each other and their life span are same (if one dies then another one too) then its a composition. Heart class has no sense if Human class is not present.

April 02, 2016

All About Agile!!

What is Agile?
In traditional software development methodologies like Waterfall model, a project can take several months or years to complete and the customer may not get to see the end product until the completion of the project.

A non-Agile projects allocate extensive periods of time for Requirements gathering, design, development, testing and UAT, before finally deploying the project.

In contrast to this, Agile projects have Sprints or iterations which are shorter in duration (Sprints/iterations can vary from 2 weeks to 2 months) during which pre-determined features are developed and delivered. 

We can say that, Agile is a time boxed, iterative approach to software delivery that builds software incrementally from the start of the project (incremental delivery), instead of trying to deliver it all at once near the end.

What is User Story?
User stories are short, simple descriptions of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system.

April 01, 2016

#Collections: Part 1- Java Collections Interview Questions and Answers


JDK 1.2 introduces a new framework for collections of objects, called the Java Collections Framework.

What are Collections?

A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.

Part 7: Java Thread Interview Questions & Answers (Thread Pool, Executor)



What is ThreadLocal variable in Java?

ThreadLocal is a special class for which each thread accessing the variable would have a separate instance of it. This was introduced on JDK 1.2 but it was later generified in JDK 1.4 to introduce type safety on ThreadLocal variable.

The ThreadLocal variable becomes eligible for Garbage collection after the thread finished or died, normally or due to any Exception (given those ThreadLocal variable doesn't have any other live references).

ThreadLocal is a generic class and can be applied to any type.

ThreadLocal variables in Java are generally private static fields in Classes and maintain its state inside Thread. e.g :

private static final ThreadLocal < SimpleDateFormat > dateformatter = new ThreadLocal < SimpleDateFormat > ();

Part 6: Java Thread Interview Questions & Answers (CountDownLatch vs CyclicBarrier)


Let's first understand what exactly CountDownLatch and CyclicBarrier do.

Part 5: Java Thread Interview Questions & Answers (UncaughtExceptionHandler, Synchronization, Context-Switching)


What happens when an exception occurs in a thread?
If an exception is not caught thread will die, else if an uncaught exception handler is registered then it will get a callback.

What is the use of Thread.UncaughtExceptionHandler interface?
Thread.UncaughtExceptionHandler is an interface, defined as a nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.

Checked exceptions must be specified in the throws clause of a method or caught inside them. Whereas, Unchecked exceptions don’t have to be specified or caught.

Part 4: Java Thread Interview Questions & Answers (Race condition, Deprecated Methods, isInterrupted and interrupted)


What is a race condition in Java?
  • A race condition occurs when the critical section is concurrently executed by two or more threads. This can lead to incorrect behaviour of a program. 
  • We can say it is a condition in which two or more threads compete together to get certain shared resources.
  • A race condition is when multiple threads read and write the same variable i.e. they have access to some shared data and they try to change it at the same time. This results in a non-deterministic bug, which is one of the hardest bugs to find and re-produce because of the random nature of racing between threads.
There are the following two solutions to avoid race conditions.
a). Mutual exclusion: If a thread is using a shared variable or thread, another thread will exclude itself from doing the same thing.
b). Synchronize the process: A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.

Part 3: Java Thread Interview Questions & Answers (Thread lifecycle)

What are the different states of a thread's lifecycle?
  • Runnable: waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
  • Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should not be used very frequently.
  • Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
  • Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  • Blocked on I/O: Will move to runnable after I/O conditions like reading bytes of data etc changes.
  • Blocked on synchronization: Will move to Runnable when a lock is acquired.
  • Dead: The thread is finished working.

Part 2: Java Thread Interview Questions & Answers (volatile and AtomicInteger)

What is a volatile variable in Java?
volatile variable in Java is a special variable that is used to signal threads, a compiler that the value of this particular variable is going to be updated by multiple threads inside the Java application.

When we make a variable volatile, we ensure that its value should always be read from the main memory and the thread should not use the cached value of that variable from its own stack.

The volatile keyword can only be applied to a variable, it can not be applied to a class or method. Using volatile keywords along with class and method will result in a compile-time error.

Part 1: Java Thread Interview Questions & Answers

What is Multithreading and why does it Exist?

Let's take an example to understand this. Assume we need to compute a simple multi-step mathematical computation problem. ((2 + 5) * (6 + 4)). The computer is going to compute this in 3 steps:
1). Find (2 + 5)
2). Find (6 + 4)
3). Lastly, multiply the results of steps 1 and 2.

Now let's assume each step takes exactly 1 unit of time, the above would be completed in 3 units of time. But what if two threads could be run simultaneously to solve the above problem?

When we used 2 threads, steps 1 and 2 will be performed simultaneously and then subsequently multiplied by each other once the result is found. the same computation that previously took 3 units of time would be completed in only 2 units of time — a saving of 33%.


Multithreading enables us to run multiple threads concurrently. For example, after you log in to your Instagram account, one thread will load the stories of the accounts you are following, whereas another thread updates your Instagram feed with the latest posts. 

We can say multithreading improves the responsiveness of a system. Imagine what would happen if Instagram ran in a thread? It might take 10 seconds to fetch the stories, and after that, it might take another 10 seconds to fetch the posts. This might make Instagram completely unresponsive because it won't allow users to perform another operation till all the stories and posts are loading.

What is Thread in Java?

Thread in Java is a lightweight process and represents an independent path of execution. It's a way to take advantage of multiple CPUs available on a machine. By employing multiple threads we can speed up CPU-bound tasks.

Let's assume that one thread takes 100 milliseconds to do a job, we can use 10 threads to reduce that task to 10 milliseconds. Java provides excellent support for multithreading at the language level, and it's also one of the strong selling points.