Friday, 22 June 2018
Monday, 6 March 2017
Frequently asked java interview question and answers
Q. What are all the Object class methods?
A. equals, hashCode,toString,clone,wait,notify,notifyAll,getClass,finalize
Q. When do you go for Interface and abstract class?
A. When there is a complex logic to be used across the application, then provide that logic as a concrete method and place inside a abstract class as it allows both concrete and abstract methods. To get 100% abstraction, use interfaces in the application
Q. Write a psudo java code to print 1 to 10 numbers in sequence with two multiple threads in which one is printing even numbers and another is printing odd nos?
A. class Thread1 implements Runnable{
@Override
public synchronized void run() {
for(int i=0;i<10 args="" auto-generated="" block="" catch="" class="" code="" e.printstacktrace="" e="" even="" evenoddthreaddemo="" for="" i="" if="" implements="" int="" main="" notify="" nterruptedexception="" numbers="" odd="" public="" r1="" r2="" run="" runnable="" static="" synchronized="" system.out.println="" t1.start="" t1="new" t2.start="" t2="new" thread1="" thread2="" thread="" todo="" tring="" try="" verride="" void="" wait="">10>
Q. What are the types of Inner Classes?
A. Anonymous inner class
Q. How to create a thread and which is best and why?
A. Using Thread© and Runnable(I)- Runnable is best as java does not support multiple inheritance.
Q. What is checked and unchecked exception?
A. Exception thrown by compiler - checked exception; exceptions thrown at runtime- unchecked exceptions
Q. Write the code to insert an element in ArrayList?
A. list.add(index, object)
Q. Differences between Array and ArrayList?
A. Array is fixed in size and allows homogenious elements Whereas ArrayList is growable and allows hetrogenious elements.
Q. What is HashMap ?
A. allows key and value pairs or entries
Q. Explain the internal implementation of HashMap?
A. It uses LinkedList data structures; when duplicate key found, will be replaced with update key; equals and hashCode should be overridden when custom objects are used.
Q. What is thread executor framework?
A. Used to call all multiple thread tasks with only one thread
Q. What is Serialization?
A. Sending objects over network. Objects will be converted to streams.
Q. How to synchronize a class?
A. We can use 'synchronized' key word along with a method, used for a block
Q. What is garbage collection?
A. All objects with no references will be collected by garbage collector
Q. How to customize garbage collection in Java?
A. I think we cannot. JVM will take care of it.
Q. What is Generics in Java?
A. Provides Type safety and avoid external type Casting
Q. Features of Java 8?
A. Default/static method Interfaces, Functional Interfaces, Lamda Expressions, Java Stream API and etc
Q. When there is a requirement to do frequent insertions and deletions, which collection is useful and why?
A. LinkedList as it is node based data structure
Q. what is the code to write Immutable object?
A. Need to make the class as final, and all fields must be either private or final.
Q. How to sort objects in java?
A. Using Comparable and Comparator
Q. Write the code to sort using Comparable?
A.
class Person implements Comparable{
private String empName;
private Integer empId;
public Person(Integer id,String name){
this.empId = id;
this.empName = name;
}
@Override
public int compareTo(Person e){
return (this.empId - e.empId);
}
public String toString(){
return empId+" "+empName;
} }
public class ComparableDemo {
public static void main(String[] args) {
Person e1 = new Person(3,"XXX");
Person e2 = new Person(1,"YYYY");
Person e3 = new Person(2,"ZZZ");
List empList = new ArrayList();
empList.add(e1);
empList.add(e2);
empList.add(e3);
Collections.sort(empList);
for(Person e:empList)
System.out.println(e);
}}
Q. When will you get StackOverflow Exception?
A. When we create an object inside a loop without having end condition
Q. What is final, finally, finalize?
A. final - a class with final cannot be subclassed - a final method cannot be overridden - a final variable cannot be re-initialized; finally - code gets executed irrespective of an exception occurred, its gets executed always except when System.exist(0) is used. finalize() - used before objects get garbage collected.
Q. Differences between throw and throws?
A. throw should be used along with throws but not vice versa. When developer develops custom exception, throw is useful to throw that exception.
Q. What is concurrent Map in java?
A. ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time .
while HashMap is not thread-safe .
Q. What are all the oops conecpts and explain?
A. overloading,overriding; Encapsulation-gives security to the code/fields; Abstraction-hides the complexity of the code and just gives the functionality
Q. Which design patterns do you know?
A. MVC, Singleton, Factory, VO, DTO, FrontEndController
Q. What is implict object in jsp?
A. Ready made objects which needs no instantiation
Q. What are all the implicit objects in jsp?
A. request,response,session,out,application,page,pageContext,exception,config
Q. How to establish a connection in jdbc?
A. load the driver class, get the connection, create statement, prepare the query, execute the query, get the resultset object, iterate it and get the results or executeUpdate for non-select queries
Q. What are the types of Statements?
A. Simple sTatement, PreparedStatement, CallableStatement
Q. What is PreparedStatement and what is the advantage of it?
A. PreparedStatement allows to enter the values using setter methods and query will be compiled and placed at server side only once.
Q. Did you work on tuning queries/tables in db?
A. indexing, using views
Q. What are ACID properties?
A. Automicity, Consistency, Isolation, Durabiltiy
Q. How to get data from multiple tables?
A. Using joins - inner join, out joins-left and right, full join
Q. What are all the Isolation levels?
A. Read-only, Read-write…
Q. Which version of Hibernate used in your project?
A. 3.x
Q. What is hibernate configuration file?
A. a xml file where db related stuff, beans, hibenate mapping file gets configured.
Q. What is alternative for hibernate configuration?
A. We can use Java related api.
Q. What are all the hibenate properties?
A. dialect to show db equivalent qeuries, show-sql , hbm2ddl,…
Q.What is hibernate?
A. its an ORM tool where we can map a java class object with record in a table
Q. What are all the associations available in hibernate?
A. one-to-one; one-to-many;many-to-one;many-to-many
Q. What oops concepts are used in hibernate?
A.inheritance and association
Q. What is inverse="true"/"false"?
A. true-birectional association; false-uni-directional association
Q. What are all the generators in hibernate?
A. generates ids - assigned, sequence, increment…
Q. What are all the classes/interfaces used in hibernate?
A. Configuration, SessionFactory, Session, Transaction
Q. What are the states of object in hibenate?
A. Transient, Persistant, Detached
Q. what is get() and load() in hibernate?
A. get()- loads a class and returns null when specific object was not found; load()- loads class and return ObjectNotFound exception when the specific object not found.
Q. When the objects are moved to persistant state?
A. after session.flush()
Q. What is connection pool?
A. a pool of connection/session objects available and used connection will be moved to this pool.
Q. What is the use of connection pool?
A. Developer can use readily available session in his code.
Q. What is the Spring MVC flow?
A. request --> DispatcherServlet -->HandlerMaaping -->Controller--returns ModelAndView object>ViewResolver-->View
Q. What is bean?
A. Any simple java class with setters and getters.
Q. What are all the modules in spring?
A. Spring core, Spring MVC. Knowledge on remianing modules like Spring JDBC, Spring ORM, Spring AOP
Q. What is IOC or Inversion of control?
A. Design pattern stands for Inversion Of Control. Dependency Injection in spring describes one of the implementation of it.
Q. What is AOP?
A. Stands Aspect Oriented Programming. Useful in separating the business logic from all others like logging, exception handling, tx management
Q. Did you work at authorization part of application?
A. Not get a chance but aware of it. In Spring , Spring Security module is there to do so.
Q. What are the events in spring?
A. ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent, ContextClosedEvent, RequestHandledEvent
Q. How to configure mail properties in spring?
A. Used spring given bean called ProperyPlaceHolderConfigurer. Added the mail.properties to the classpath. And retrieved them and added to "JavaMailSenderImpl" using ${}
Q. Why do we use ApplicationContext instead BeanFactory in Spring?
A. ApplicationContext supports all advanced features like events, i18n.,…
Q. What is Criteria api in Spring?
A. Used to put constraints on entity using static classes like Expressions,…
Q. How to call procedures and functions?
A. Used directly as native sql query and retrieved the results
Q. Do you why industry is prefering REST ?
A. for high performance in terms of fast and easy implementation
Tuesday, 20 December 2016
Java OOPs Concepts
Simula is considered as the first object-oriented programming language. The programming paradigm where everything is represented as an object, is known as truly object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
- Object
- Class
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
Class
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
Tuesday, 29 November 2016
Wednesday, 10 August 2016
Difference between ArrayList and LinkedList in Java
ArrayList and LinkedList both implements List interface and their methods and results are almost identical. However there are few differences between them which make one better over another depending on the requirement.
ArrayList Vs LinkedList
1) Search: ArrayList search operation is pretty fast compared to the LinkedList search operation. get(int index)
in ArrayList gives the performance of O(1)
while LinkedList performance is O(n)
.
Reason: ArrayList maintains index based system for its elements as it uses array data structure implicitly which makes it faster for searching an element in the list. On the other side LinkedList implements doubly linked list which requires the traversal through all the elements for searching an element.
2) Deletion: LinkedList remove operation gives O(1)
performance while ArrayList gives variable performance: O(n)
in worst case (while removing first element) and O(1)
in best case (While removing last element).
Conclusion: LinkedList element deletion is faster compared to ArrayList.
Reason: LinkedList’s each element maintains two pointers (addresses) which points to the both neighbor elements in the list. Hence removal only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be removed. While In ArrayList all the elements need to be shifted to fill out the space created by removed element.
3) Inserts Performance: LinkedList add method gives O(1)
performance while ArrayList gives O(n)
in worst case. Reason is same as explained for remove.
4) Memory Overhead: ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighbor nodes hence the memory consumption is high in LinkedList comparatively.
There are few similarities between these classes which are as follows:
- Both ArrayList and LinkedList are implementation of List interface.
- They both maintain the elements insertion order which means while displaying ArrayList and LinkedList elements the result set would be having the same order in which the elements got inserted into the List.
- Both these classes are non-synchronized and can be made synchronized explicitly by using
Collections.synchronizedList
method. - The iterator and listIterator returned by these classes are fail-fast (if list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException).
When to use LinkedList and when to use ArrayList?
1) As explained above the insert and remove operations give good performance (O(1)
) in LinkedList compared to ArrayList(O(n)
). Hence if there is a requirement of frequent addition and deletion in application then LinkedList is a best choice.
2) Search (get method) operations are fast in Arraylist (O(1)
) but not in LinkedList (O(n)
) so If there are less add and remove operations and more search operations requirement, ArrayList would be your best bet.
Monday, 18 July 2016
Difference Between String ,StringBuilder and StringBuffer
Difference Between String , StringBuilder and StringBuffer Classes with Example : Java
String
String is immutable ( once created can not be changed )object . The object created as a String is stored in the Constant String Pool .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String once assigned can not be changed.
String demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.
demo="Bye" ; //new "Bye" string is created in constant pool and referenced by the demo variable
// "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the "hello"string
StringBuffer
StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .
Due to this it does not allow two threads to simultaneously access the
same method . Each method can be accessed by one thread at a time .
But being thread safe has disadvantages too as the performance of the
StringBuffer hits due to thread safe property . Thus StringBuilder is
faster than the StringBuffer when calling the same methods of each
class.
StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer
StringBuilder
StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe .
StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder
----------------------------------------------------------------------------------
String StringBuffer StringBuilder
----------------------------------------------------------------------------------
Storage Area | Constant String Pool Heap Heap
Modifiable | No (immutable) Yes( mutable ) Yes( mutable )
Thread Safe | Yes Yes No
Performance | Fast Very slow Fast
-----------------------------------------------------------------------------------
HashCode and Equals method in Java object
Java.lang.Object has methods called hasCode() and equals(). These methods play a significant role in the real time application. However its use is not always common to all applications. In some case these methods are overridden to perform certain purpose. In this article I will explain you some concept of these methods and why it becomes necessary to override these methods.
hashCode()
As you know this method provides the has code of an object. Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode(); It indicates that hashCode is the native implementation which provides the memory address to a certain extent. However it is possible to override the hashCode method in your implementation class.
equals()
This particular method is used to make equal comparison between two objects. There are two types of comparisons in Java. One is using “= =” operator and another is “equals()”. I hope that you know the difference between this two. More specifically the “.equals()” refers to equivalence relations. So in broad sense you say that two objects are equivalent they satisfy the “equals()” condition. If you look into the source code of Object class you will find the following code for the equals() method.
{
return (this == obj);
}
Now I will explain you when to override the equals() and hashCode() methods and why it is necessary to override these methods. In this regard there is a rule of thumb that if you are going to override the one of the methods( ie equals() and hashCode() ) , you have to override the both otherwise it is a violation of contract made for equals() and hashCode(). Please refer to the Sun’s java docs for the method’s contract. I provide some test case scenario where you will find the significance of these methods. Case-1: You can override the hashCode method in your own way. Please refer to the following example.
package com.core;
/**
* @author
*
*/
public class Emp
{
private int age ;
public Emp( int age )
{
super();
this.age = age;
}
public int hashCode()
{
return age;
}
}
In the above example class “Emp” the variable age is the significant factor. Here the hashCode value will return the age of the person. Now let us consider the following test harness class.
package com.core;
/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
System.out.println("emp1.hashCode()--->>>"+emp1.hashCode());
}
}
If you run the above program, the output will be the age what you have given i.e. 23. Now question arises whether there is any way we can get the original hashCode(). We can say that if we do not override the hashCode() method what could have been the hashCode of this object. However please do not feel depressed, Java provide another approach even if you have overridden the hashCode() method , still you can get the original hashCode of a particular class. Now run the following test harness program.
package com.core;
package com.core;
/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
System.out.println("Overridden hashCode()--->>>"+emp1.hashCode());
int originalHashCode = System.identityHashCode(emp1);
System.out.println("Original hashCode of Emp---->>>"+originalHashCode);
}
}
Here the output will be like this Overridden hashCode()--->>>23 Original hashCode of Emp---->>>22222 As you know the above number is arbitrary, it depends upon your system. So then why it is necessary to override this method. There is one reason that if want to compare two objects based upon the equals() method. Although in a very simple class like “Emp”, you can achieve without overriding hashCode() method. But if you do this , you are going to violate the contract for the methods hashCode() and hashCode() of the object class. The similar case is for the method equals(). So funcational point is that if want to compare two objects based upon the equals() method you have to override both hashCode() and equals() methods. Please have look into the Emp class with the overridden methods and the related test harness class.
package com.core;
/**
* @author
*
*/
public class Emp
{
private int age ;
public Emp( int age )
{
super();
this.age = age;
}
public int hashCode()
{
return age;
}
public boolean equals( Object obj )
{
boolean flag = false;
Emp emp = ( Emp )obj;
if( emp.age == age )
flag = true;
return flag;
}
}
The related test harness class is given below.
package com.core;
/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(23);
System.out.println("emp1.equals(emp2)--->>>"+emp1.equals(emp2));
}
}
Case- 2 Think of a test scenario where you want to store your objects in a HasSet and you want to find a particular object. First let us see if we do not override the methods and we want to store the objects in the HashSet. Let us analyse the impact of it from the following code.
package com.core;
/**
* @author
*
*/
public class Emp
{
private int age ;
public Emp( int age )
{
super();
this.age = age;
}
}
In the above code it is a normal class. Now let us see the test harness class.
package com.core;
import java.util.HashSet;
/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(24);
Emp emp3 = new Emp(25);
Emp emp4 = new Emp(26);
Emp emp5 = new Emp(27);
HashSet
hs.add(emp1);
hs.add(emp2);
hs.add(emp3);
hs.add(emp4);
hs.add(emp5);
System.out.println("HashSet Size--->>>"+hs.size());
System.out.println("hs.contains( new Emp(25))--->>>"+hs.contains(new Emp(25)));
System.out.println("hs.remove( new Emp(24)--->>>"+hs.remove( new Emp(24));
System.out.println("Now HashSet Size--->>>"+hs.size());
}
}
If you run the above program, the will output will be like the following. HashSet Size--->>>5 hs.contains( new Emp(25))--->>>false hs.remove( new Emp(24)--->>>false Now HashSet Size--->>>5 It means that you can not find the object. However it is not the case for Integer object. You can put object of type Integer in a HashSet and you can try and you can see the effect. Now let us modify the “Emp” class so that we will get over the problems what we faced in the above test harness class.
package com.core;
/**
* @author
*
*/
public class Emp
{
private int age ;
public Emp( int age )
{
super();
this.age = age;
}
public int hashCode()
{
return age;
}
public boolean equals( Object obj )
{
boolean flag = false;
Emp emp = ( Emp )obj;
if( emp.age == age )
flag = true;
return flag;
}
}
Here in the above class, we have overridden the hashCode() and equals() methods. Now if you run the same test harness class, you will get the desired output like the following. HashSet Size--->>>5 hs.contains( new Emp(25))--->>>true hs.remove( new Emp(24))--->>>true Now HashSet Size--->>>4 Case – 3 In this case you want to use your object as key not the value in the HashMap. So you have to override both the methods hashCode() and equals(). However it is left to the reader to create the object and test the feature in a Map. Case-4 If want to make your own immutable object , it will be wiser to override the equals() and hashCode() methods. To test the above programs, please create the appropriate package as mentioned in the program. You can also create your own package and modify the package name in the above programs. You can all the code in your favorable java editor.
Run Postman API remote or code or command line
POSTMAN is used to run the APIs generally. What if we want to create a collection in postman and run it from some other code or command l...
-
The main reason for writing this tutorial is i found many examples online but all are either very basic or more complicated(i felt) so i wa...
-
In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm that provides many concepts such as inheritance,...
-
Tested Approach: number.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');Short solution #2: Alternate Solution: number.toFixed...