Google IO 2015 Main Features

  • Google announced a new smart home platform called Brillo on stage at its annual Google I/O developers 
  • At Google I/O 2015 Google officially announced Project Brillo, a new platform for the Internet of Things.
watch live HereGoogle IO 2015

Whats NEW????.... It's a LOT !!!!

  • Google announced a new smart home platform called Brillo on stage at its annual Google I/O developers 
  • At Google I/O 2015 Google officially announced Project Brillo, a new platform for the Internet of Things.
  • This is one of the biggest announcements from today's developer conference. Unlimited photo and video
  • Google Maps, including turn-by-turn voice directions, to be available offline.. 
  • Android M is big brother for sure. Google's latest version of Android will remind you to pick up your dry 
  • Have you tried this fun Google trick yet? #YouNeedToTryThis #BarrelRoll #Google #Funfact  
  • Google Cardboard received a big update today and it's also compatible with iOS now.
  • Google is adding a family friendly section to Google Play! 
  • Google I/O 2015 Keynote slides look pretty sleek and consistent - good to see! 
  • Google reveals their second virtual reality headset for phones, a larger Google Cardboard. Clay Bavor of Google 

public static void main(String[] args) in Java

  • main method is a standard method used by JVM to execute any java program(Java SE).
  • Lets see an example class without main method.

  1. package instanceofjava;
  2. public Demo{
  3.  
  4. }


  • This class will compile fine but while executing JVM fails to find the main method in that class
  • So it will throw an exception: NoSuchMethodError:main

  1. package instanceofjava;
  2. public Demo{
  3. public static void main(String [] args){
  4.  
  5. }
  • This program will compile and executed. Because at run time JVM calls the main method on that class.

Why main method is public?

  •  To call by JVM from anywhere main method should be public.
  • If JVM wants to call our method outside of our package then our class method should be public.

  1. package instanceofjava;
  2. public MainDemo{
  3. public static void main(String [] args){
  4.  
  5. }
  6. }

public static void main(string args) interview Questions

Why main method is static?

  • To execute main method without creating object then the main method oshould be static so that JVM will call main method by using class name itself.

Why main method return type is void?

  • main method wont return anything to JVM so its return type is void.

 Why the name main?

  • This is the name which is configured in the JVM.

Why the arguments String[] args?

  •  Command line arguments.
  • String array variable name args : by the naming conventions they named like that we can write any valid variable name.

Can we write static public void main(String [] args)?

  • Yes we can define main method like static public void main(String[] args){}
  •  Order of modifiers we can change.

  1. package instanceofjava;
  2. public MainDemo{
  3. static public void main(String [] args){
  4.  
  5. }
  6. }

What are the possible public static void main(String [] args)method declaration with String[] args?

  • public static void main(String[] args){ }
  • public static void main(String []args){ }
  • public static void main(String args[] ){ }
  • public static void main(String... args){ } 
  • Instead of args can place valid java identifier.

Can we declared main method with final modifier?

  • Yes we can define main method with final modifier.

  1. package instanceofjava;
  2. public MainDemo{
  3. public static final void main(String [] args){
  4.  
  5. }

Main method with all possible modifiers:

 

  1. package instanceofjava;
  2. public MainDemo{
  3. static final synchronized public void main(String [] args){
  4.  
  5.  System.out.println("Main method");
  6.  
  7. }

Output:

  1. Main method

Overloading main method:

  • We can declare multiple main methods with same name as per overloading concept.  
  • So we can overload main method but every time JVM looks for main method with String[] args method.
  • Lets see an example program on main method overloading.
  • main(String[] args) method will be called automatically by JVM.
  • If we want to call other methods we need to call explicitly.

 

  1. package instanceofjava;
  2. public MainDemo{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method String [] args");
  6.  
  7. public static void main(int[] args){
  8.  
  9.  System.out.println("Main method int[] args");
  10.  
  11. }
  12.  





Output:

  1. Main method String [] args


Main method Inheritance:

  • Inheritance concept is applicable for main method.
  • If a sub class not having main method and extending a super class which is having main method.
  • Then if we execute super class main method will be executed fine.
  • If we execute sub class which is not having main method also executed fine and super class main method will be called.

  1. package instanceofjava;
  2. public A{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method of class A");
  6.  
  7.  



Output:

  1. Main method of class A

 

  1. package instanceofjava;
  2. public B extends A{
  3.  
Output:

  1. Main method of class A

What happen if both super and sub class having main method?

  • Actually its not overriding concept here. it is a method hiding concept in this scenario regarding with main method.

  1. package instanceofjava;
  2. public A{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method of class A");
  6.  
  7.  

Output:

  1. Main method of class A


  1. package instanceofjava;
  2. public B extends A{
  3. public static void main(String [] args){
  4.  
  5.  System.out.println("Main method of class B");
  6.  
  7.  


Output:

  1. Main method of class B

Static block in Java

  • Static variables are class level variables and without instantiating class we can access these variables.

    1. Static int a;


  • Class loading time itself these variables gets memory
  • Static methods are the methods with static keyword are class level. without creating the object of the class we can call these static methods.

    1. public static void show(){ 
    2.  
    3. }

  • Now its time to discuss about static blocks.
  • Static block also known as static initializer
  • Static blocks are the blocks with static keyword.
  • Static blocks wont have any name in its prototype.
  • Static blocks are class level.
  • Static block will be executed only once.
  • No return statements.
  • No arguments.
  • No this or super keywords supported.
  •  
    1. static{ 
    2.  
    3.  }

     

What is the need of static block?

  • Static blocks will be executed at the time of class loading.
  • So if you want any logic that needs to be executed at the time of class loading that logic need to place inside the static block so that it will be executed at the time of class loading. 
  • To initialize the static variables while class loading itself we need static block.
  • If we have multiple classes then if you want to see the order of those classes loading then static block needed.

When to use static blocks?

  • If you want to access static variables before executing the constructor.
  • If you want to execute your code only once even any number of objects created.
  • If you want to initialize static constants.

When and where static blocks will be executed?

  • Static blocks will be executed at the time of class loading by the JVM  by creating separate stack frames in java stacks area (Please refer JVM Architecture  to know about stacks area).
  • Static blocks will be executed in the order they defined from top to bottom.



  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6. static{
  7.       System.out.println("First static block executed");
  8. }
  9.  
  10. static{
  11.      System.out.println("Second static block executed");
  12. }
  13.  
  14. static{
  15.      System.out.println("Third static block executed");
  16. }
  17.  
  18. }
     
Output:
  1. First static block executed
  2. Second static block executed
  3. Third static block executed

Order of execution of static block and main method:

  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6. public static void main (String[] args) throws java.lang.Exception
  7. {
  8.         System.out.println("Main method executed");
  9. }
  10.  
  11. static{
  12.       System.out.println("First static block executed");
  13. }
  14.  
  15. static{
  16.      System.out.println("Second static block executed");
  17. }
  18.  
  19. static{
  20.      System.out.println("Third static block executed");
  21. }
  22.  
  23. }
     
Output:
  1. First static block executed
  2. Second static block executed
  3. Third static block executed
  4. Main method executed


Order of execution of Static block and constructor:

 

  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6. StaticBlockDemo(){
  7.  
  8.   System.out.println("Constructor executed");
  9.  
  10. }
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13.  
  14.     System.out.println("Main method executed");
  15.     StaticBlockDemo obj = new StaticBlockDemo();
  16.  
  17. }
  18.  
  19. static{
  20.       System.out.println("First static block executed");
  21. }
  22.  
  23. static{
  24.      System.out.println("Second static block executed");
  25. }
  26.  
  27. static{
  28.      System.out.println("Third static block executed");
  29. }
  30.  
  31. }
     


Output:
  1. First static block executed
  2. Second static block executed
  3. Third static block executed
  4. Main method executed
  5. Constructor executed

What is the output of following program:


  1. package com.instanceofjava;
  2.  
  3. class StaticBlockDemo 
  4. {
  5.  
  6.   static int a=getNum();

  7. public static int getNum(){
  8.  
  9. System.out.println("In method m1()");
  10. return 10;
  11.  
  12. }

  13. public static void main (String[] args) throws java.lang.Exception
  14. {
  15.  
  16.     System.out.println("Main method executed");
  17.   
  18.  
  19. }
  20.  
  21. static{
  22.       System.out.println("First static block executed");
  23. }
  24.  
  25. static{
  26.      System.out.println("Second static block executed");
  27. }
  28.  
  29. static{
  30.      System.out.println("Third static block executed");
  31. }
  32.  
  33. }
     
Output:
  1. In method m1()
  2. First static block executed
  3. Second static block executed
  4. Third static block executed
  5. Main method executed


Java Jsp Interview Questions

1.Explain JSP life Cycle methods?

  • jsp engine controls the life cycle of jsp
  • Jsp life cycle is described by three life cycle methods and six life cycle phases


Jsp life cycle methods :

  • jspInit()
  • _jspService()
  • jspDestroy()


  • Jspinit() method is invoked when JSP page is initialized.
  • The _jspService() method corresponds to the body of the jsp page.
  • This method is defined automatically by the JSp container and should never be defined y the JSP page author.

Jsp Life cycle Phases: 

  • Translation phase
  • Compilation phase
  • Instantiation phase
  • initialization phase
  • Servicing phase
  • Destruction phase

Read More at : JSP Life Cycle

2. What are the Jsp Implicit Objects?


  • Implicit objects in jsp are the objects that are created by the container automatically and the container makes all these 9 implicit objects to the developer.
  • We do not need to create them explicitly, since these objects are created and automatically by container and are accessed using standard variables(objects) are called implicit objects.
  • The following are of implicit variables available in the JSP.  


  1. out
  2. request
  3. response
  4. config
  5. application
  6. session
  7. pagecontext
  8. page
  9. exception
Read More at: 9 Jsp Impicit Objects in java

3. Explain Jsp Scripting Elements?

  • Jsp scripting elements are used to embed jva code in to the jsp.
  • Jsp scripting elements are three types
    1. Declaration
    2. Expression
    3. Scriplet
Read More at: Jsp Scripting Elements



4. What are the Directives in Jsp?

  • A jsp directive is a translation time instruction to the jsp engine.
  • we have three kinds of directives.
  1. Page directive
  2. Include directive
  3. Taglib directive

 Read More at: Jsp Directive Elements


 5. What are the differences between include directive and include action?


Java Jsp interview Questions

 

6. How to disable session in JSP?

  • By using page directive
  • <%@ page session="false" %> 

7. How can we handle exceptions in a JSP page?

  • We can handle exception in jsp by using error page element of page directive 
  • The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs.
    The value of the errorPage attribute is a relative URL.
    The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown

    Syntax:

    errorPage="url"

    Example:

    <%@ page errorPage="error.jsp"%>

8.How can we override jspInit() and jspDestroy() methods in a jsp?

  • Both methods are executed once in a life cycle of a jsp.
  • We can override these two method as shown below.
  • <%!
        public void jspInit() {
            . . .
        }
    %>
  • <%!    
        public void jspDestroy() {
            . . .   
        }
    %>

9.Can a JSP extend a java class?

  • Yes we can extend a java class in jsp
  • <%@ include page extends="classname" %>
  • We can do this because jsp will convert to a servlet so a servlet can extend a class its fine

10.How can we pass information from one jsp to included jsp page?

  • <jsp:include page="employeedetail.jsp" flush="true">
  • <jsp:param name="name" value="abc"/>
  • <jsp:param name="id" value="220"/>

Java Servlet Interview Questions

 

1.Explain Servlet life cycle in java.

  • Servlet engine controls the life cycle of servlet
  • Servlet life cycle is described by three life cycle methods under 5 life cycle phases
  • life cycle methods are
  1. init(ServletConfig obj)
  2. service(servletRequest, servletResponse)
  3. destroy() 

  • When ever somethings happens in the life of servlet. servlet engine calls these methods on the servlet instance and hence the name.

Read more here: Servlet Life Cycle


2.What is ServletConfig ?

  • Request parameters are used by the servlet to receive data from client to process the request.
  • Some specific data must be supplied to the servlet at the time of initialization of the servlet and this data is specific to the client.But data is not supplied by the client via request parameters
  • Use initialization parameters to supply the data to the servlet at the time of initialization of the servlet. initialization parameters are set in deployment descriptor   (Web.xml).
  • Servlet can access these parameters during the run time
  • Request parameters change form Request to request 
  • Initialization parameters change from servlet to servlet.

Read more at : ServletConfig

3. What is ServletContext?

  • We can deploy multiple web applications in a servlet container.
  • Each web application contains its own resources in a separate  environment. This environment called ad Web Application context or ServletContext.
  • The resources belongs to the one web application context are not available to the other web application context.
  • A Servlet context contains zero or more number of servlets. For every servlet object the container creates separate ServletConfig object.
Read More at : ServlectContext


4. Can we define a Constructor in servlet?

  • Yes we can define a constructor in servlet but we can not call the constructor explicitly because servlet container will create the object of servlet so it will be called by the servlet container.

5. Can we call destroy() method inside init() method of a servlet. If yes what will happen?

  • Yes we can call destroy() method inside a init() method.
  • Actually container will call destroy() method if we call that method explicitly nothing will happen.
  • If we override destroy() method and called from init(). method will be called and code will be executed.

6.What are the difference between GenericServlet and HttpServlet?

GenericServlet HttpServlet
Abstract Class Abstract Class
Protocol Independent Http Protocol Dependent
Subclass of Servlet Subclass of GenericServlet
public void service(ServletRequest req,ServletResponse res ). Supports public void service() and protected void service(), doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions()etc.


7.What are the differences between doGet() and doPost()?



doGet() doPost()
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, java.io.IOException Protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
handles client's GET request handles client's POST request
Request parameters appended to the URL and sent along with header information Request parameters are submitted via form.
Request Parameters are not encrypted Request Parameters are encrypted
Maximum size of data that can be sent using doget() method is 240 bytes There is no maximum size for data.




8. Can we call a servlet from another servlet?

  • Yes. We can call a servlet from another servlet this is known as inter servlet communication.
  • By using RequestDispatcher object we can do this.
  • RequestDispatcher rd=request.getRequestDispatcher("other servlet url name");
  • rd.forward(req, res);
Read more at : RequestDipatcher in java

9. What are the differences between forward() and sendRedirect() methods?

 


forward() sendRedirect()
request.getRequestDispathcer("example.jsp").
forward(request, response);
response.sendRedirect
("http://www.instanceofjava.com");
Used to forward the Request to resources available in within the server Used to redirect the Request to other resources or domains

10.How can you get the information about one servlet context in another servlet?

  • By using setAttribut() method we can set the data in one servlet and get in another
  • Context.setAttribute (“name”,” value”)
  • Context.getAttribute (“name”)

11.Explain Servlet architecture?

  • Frequently asking java interview question in servlets you may get questions like
  • explain the architecture of java servlet?
  • explain the architecture of java servlet with diagram?
  • define the servlet architecture?
  • servlet architecture overview?
  • Servlets read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
  • Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
The Servlet architecture in Java is a Java-based framework for building web applications. It is a specification defined by the Java Community Process (JCP) and is implemented by various web containers such as Apache Tomcat, Jetty, and GlassFish.

The Servlet architecture consists of several components, including:

Servlets: These are the core components of the Servlet architecture. They are Java classes that handle HTTP requests and responses. Servlets are executed by a web container, which is responsible for managing their lifecycle, threading, and security.

Web Containers: Also known as servlet engines, web containers are responsible for managing the lifecycle of servlets, providing services such as request handling, thread management, and security.

JSP (JavaServer Pages): These are Java-based pages that are used to create dynamic web content. JSPs are compiled into servlets by the web container and executed by the servlet engine.

JSP Tag Libraries: These are collections of custom tags that can be used in JSP pages to simplify the creation of dynamic web content.

JavaBeans: These are Java classes that encapsulate business logic and data. They can be used in JSP pages to create dynamic web content.

Filters: These are Java classes that can intercept and modify the requests and responses sent to and from servlets. They can be used to implement security, logging, and other common functionality.

Listeners: These are Java classes that are notified of certain events that occur within the web container, such as a servlet being initialized or a session being created.

In summary, the Servlet architecture provides a powerful and flexible framework for building web applications in Java, by providing a set of components and services to handle HTTP requests and responses, providing a powerful and flexible way to handle web content, and providing a set of components to handle security, logging, and other common functionality.
Read More : servlet architecture with diagram

Singleton Design Pattern in java

Problem:

  • Instead of creating multiple objects of same class having same data and wasting memory, degrading performance it is recommended to create only one object and use it multiple times.

Solution:

  •  Use Singleton Java Class.
  • Java class that allows us to create one object per JVM is is called as singleton java class.
  • The logger class of  Log 4J API is given as singleton java class.

Rules:

  • It must have only private constructors.
  • It must have private static reference variable of same class.
  • It must have public static factory method having the logic of singleton.
  • Static method should create and return only one object.
  • All these rules close all the doors of creating objects for java class and opens only one door to create object.
  • factory method where singleton logic is placed
  • The method of a class capable of creating and returning same class or other class object is known as factory method.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  
  22. return object;
  23.  
  24. }
  25.  
  26. }
     

  1. package instanceofjava;
  2.  
  3. public class SingletonObjectDemo {

  4. public static void main(String args[]) {
  5.  
  6.      SingletonClass s1= SingletonClass .getInstance();
  7.      SingletonClass s2= SingletonClass .getInstance();
  8.      System.out.println(s1.hashCode());
  9.      System.out.println(s2.hashCode());
  10.  
  11. }
  12. }

Output:

  1. getInstance(): First time getInstance was called and object created !
  2. Singleton(): Private constructor invoked
  3. 655022016
  4. 655022016


Make the Factory method Synchronized to prevent from Thread Problems:


  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.   
  22. return object;
  23.  
  24. }
  25.  
  26. }

Override the clone method to prevent cloning:

 

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  else 
  22. return object;
  23.  
  24.  
  25. public Object clone() throws CloneNotSupportedException {
  26.  
  27. throw new CloneNotSupportedException();
  28.  
  29. }
  30.  
  31. }

Eager Initialization:

  • In eager initialization object of the class will be created when class loading itself its easy way to create singleton but its having one disadvantage that even though nobody needs it still it creates object.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object= new SingletonClass ();
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. return object;
  15.  
  16. }
  17.  
  18. }
     


Lazy Initialization:

  • When ever client needs object it will check for whether object is created or not if not it will create otherwise it will return created object
  • First basic example shows lazy initialization.


Static Block Initialization:

  • This is similar to eager initialization except that in this we create object in static block and we can place exception logic.

  1. package com.instanceofjava;
  2.  
  3. public class StaticBlockSingleton {
  4.  
  5. private static StaticBlockSingleton object;
  6.  
  7. private StaticBlockSingleton(){}
  8.  
  9.     //static block initialization for exception handling
  10. static{
  11.  
  12.  try{
  13.  
  14.             object = new StaticBlockSingleton();
  15.  
  16.         }catch(Exception e){
  17.  
  18.             throw new RuntimeException("Exception occured in creating singleton object");
  19. }
  20. }
  21.  
  22. public static StaticBlockSingleton getInstance(){
  23.         return object;
  24. }
  25.  
  26. }


Comparable vs Comparator

  • One of the common interview question What are the differences between comparable and comparator and how to sort collections using these interfaces ?
  • What are the differences between comparable and comparator and how to sort employee object by empId or empName using these interfaces.
  • In this topic we will clear questions like difference between comparable and comparator in java, comparator vs comparable in java with example and comparable and comparator in java
  • Comparator and Comparable are two interfaces in Java API.
  • Before discussing about differences lets see brief description about these two interfaces

Comparable Interface:

  • Comparable Interface is actually from java.lang package.
  • It will have a method compareTo(Object obj)to sort objects
  • public int compareTo(Object obj){ }
  • Comparable interface used for natural sorting these is the reason all wrapper classes and string class implementing this comparator and overriding compareTo(Object obj) method.
  • So in String and all wrapper classes compareTo(Object  obj) method is implemented in such way that it will sort all objects.

String class:

  • If we observe String class it is implementing comparable interface.
  • If compareTo(String str) methods returns 0 : both strings are equal
  • If compareTo(String str) method returns 1: string is lexicographically greater than the string argument
  • If compareTo(String str) method returns -1: string is lexicographically less than the string argument

  1. package java.lang;
  2.  
  3. public final class String
  4. extends Object
  5. implements Serializable, Comparable<String>, CharSequence {
  6.   
  7. public int compareTo(String anotherString){
  8.  //logic
  9. }
  10. }

Comparing String Objects:

  •  Lets see an example java program that will explains how two string objects are compared using compareTo(String str) method in String class.


  1. package com.instanceofjava;
  2. public class StringCompareDemo {
  3. public static void main(String [] args){
  4.    
  5.  String str1="comparable";
  6.  String str2="comparator";
  7.  
  8. int value=str1.compareTo(str2);
  9.  
  10. if(value==0){
  11.  
  12. System.out.println("Strings are equal");
  13.  
  14. }
  15. else{
  16.  
  17. System.out.println("Strings are not equal");
  18.  
  19. }
  20.  
  21. }
  22. }

Output:

  1. Strings are not equal

Wrapper classes:

  • Wrapper classes is used to convert primitive data values into java objects. for 8 primitive data types java has 8 corresponding wrapper classes. All these classes implementing comparable interface.
  • Lets see an example on Integer wrapper class 

Integer:


  1. package java.lang;
  2. public final class Integer
  3. extends Number
  4. implements Comparable<Integer> {
  5.   
  6. public int compareTo(Integer i){
  7.  //
  8. }
  9. }

  •  Lets see an example program of comparing two integer objects

  1. package instanceofjava;
  2.  
  3. public class IntegerComparableDemo {
  4.  
  5. public static void main(String [] args){
  6.  
  7.    // compares two Integer objects numerically
  8.  
  9.    Integer obj1 = new Integer("37");
  10.    Integer obj2 = new Integer("37");
  11.  
  12.    int retval =  obj1.compareTo(obj2);
  13.  
  14. if(retval > 0) {
  15.  
  16.    System.out.println("obj1 is greater than obj2");
  17. }
  18.  
  19. else if(retval < 0) {
  20.  
  21.  System.out.println("obj1 is less than obj2");
  22.  
  23.  }
  24.  else {
  25.  
  26.  System.out.println("obj1 is equal to obj2");
  27.  
  28. }
  29.  
  30. }

Output:
  1. obj1 is equal to obj2;

Sorting Collections using Comparable :

  •  By using Collections.sort(list); method we can sort objects in natural object sorting order 
  • An example program on Collections.sort(list); 
  • Sorting Employee objects by id.



  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee implements  Comparable {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  @Override
  35.  public int compareTo(Object in) {
  36.         return  new Integer(this.id).compareTo(((Employee)in).id);
  37.   }
  38.  public static void main(String[] args) {
  39.  
  40.         Employee e1= new Employee("xyz", 37);
  41.         Employee e2= new Employee("abc", 46);
  42.         Employee e3= new Employee("sai", 38);
  43.  
  44.         ArrayList al= new ArrayList();
  45.  
  46.         al.add(e1);
  47.         al.add(e2);
  48.         al.add(e3);
  49.         Collections.sort(al);
  50.         Iterator itr= al.iterator();
  51.  
  52.      while (itr.hasNext()) {
  53.             Employee em = (Employee) itr.next();
  54.             System.out.println(em.getId()+" "+em.getName());            
  55.        }
  56. }
  57. }
     
Output:

  1. 37 xyz
  2. 38 sai
  3. 46 abc

Comparator:

  • Comparator Interface is actually from java.util package.
  • It will have a method compare(Object obj1, Object obj2)to sort objects
  • public int  compare(Object obj1, Object obj2){ }
  • Comparator interface used for customized sorting.
  • Will place sorting logic in other class so that its easy to change.
  • An example program which will sort employee objects by name

 

 1.Employee.java

  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee  {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  
  35.  public static void main(String[] args) {
  36.  
  37.         Employee e1= new Employee("xyz", 37);
  38.         Employee e2= new Employee("abc", 46);
  39.         Employee e3= new Employee("sai", 38);
  40.  
  41.         ArrayList al= new ArrayList();
  42.  
  43.         al.add(e1);
  44.         al.add(e2);
  45.         al.add(e3);
  46.        Collections.sort(al, new EmpSortByName());
  47.         Iterator itr= al.iterator();
  48.  
  49.      while (itr.hasNext()) {
  50.             Employee em = (Employee) itr.next();
  51.             System.out.println(em.getId()+" "+em.getName());            
  52.        }
  53. }
  54. }

EmpSortByName.java:

 

  1. package instanceofjava;
  2. import java.util.Comparator;
  3. public class EmoSortByName implements Comparator<Employee> {
  4.  
  5.     @Override
  6.     public int compare(Employee arg0, Employee arg1) {
  7.         return arg0.getName().compareTo(arg1.getName());
  8.     }
  9.  
  10. }
     
Output:

  1. 46 abc
  2. 38 sai
  3. 37 xyz

Differences Between Comparable and Comparator:


Parameter Comparable Comparator
Package java.lang.Comparable java.util.Comparator
Sorting logic Must be in Same class Separate class
Method definition public int compareTo(Object obj) public int compare(Object obj1, Object obj2)
Method call Collections.sort(list) Collections.sort(list, new OtherSortClass())
Purpose Natural Sorting Custom Sorting


You Might Like:

1. Java Concept and Example Programs 
2. Java Concept and Interview Questions 
3. Core java Tutorial
4. Java experience interview Questions
5. Java Programs asked in Interviews

10 Interesting Core Java Interview Coding Questions and Answers

1. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class B{
  4.  
  5.   B b= new B();
  6.  
  7.  public int show(){
  8.       return (true ? null : 0);
  9.  }
  10.  
  11.  public static void main(String[] args)  {
  12.  
  13.         B b= new B();
  14.         b.show();
  15.     }
  16.  
  17. }




Exaplanation:

  • Whenever we create the object of any class constructor will be called first and memory allocated for all non static variables
  • Here  B b= new B(); variable is object and assigned to new object of same class
  • B b= new B(); statement leads to recursive execution of constructor will create infinite objects so at run time an exception will be raised
  • Exception in thread "main" java.lang.StackOverflowError
  • The common cause for a stack overflow exception  is a bad recursive call. Typically this is caused when your recursive functions doesn't have the correct termination condition

2. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.  
  5.  public static void show(){
  6.  
  7.         System.out.println("Static method called");
  8.  }
  9.  
  10.  public static void main(String[] args)  {
  11.  
  12.         A obj=null;
  13.         obj.show();
  14.  
  15.     }
  16.  
  17. }



Exaplanation:

  • We can call static methods using reference variable which is pointing to null because static methods are class level so we can either call using class name and reference variable which is pointing to null.


3. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.  
  5.  static int a = 1111;
  6.  static
  7.  {
  8.         a = a-- - --a;
  9.  }
  10.     
  11. {
  12.         a = a++ + ++a;
  13.  }
  14.  
  15.  public static void main(String[] args)  {
  16.  
  17.        System.out.println(a);
  18.  
  19.     }
  20.  
  21. }




Explanation:

Top 10 Increment and decrement  operators interview Questions

4. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.  
  5.  int GetValue()
  6.  {
  7.         return (true ? null : 0);
  8.  }
  9.  
  10.  public static void main(String[] args)  {
  11.  
  12.    A obj= new A();

  13.       obj.GetValue();
  14.  
  15.     }
  16.  
  17. }




5. What is the output of following program?


  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.   
  5.  public static void main(String[] args)  {
  6.  
  7.    Integer i1 = 128;
  8.  
  9.    Integer i2 = 128;
  10.  
  11.      System.out.println(i1 == i2);
  12.  
  13.    Integer i3 = 127;
  14.    Integer i4 = 127;
  15.  
  16.       System.out.println(i3 == i4);
  17.  
  18.     }
  19.  
  20. }




6. What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. void method(int i)
  6. {
  7.  
  8.  }
  9.  
  10.     }
  11.  
  12.  class B extends A
  13.  {
  14.  
  15. @Override
  16. void method(Integer i)
  17.  {
  18.  
  19.  }
  20.           


  21. }



7. Which line will throw compile time error? 8 or 9?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. public static void main(String [] args)
  6. {
  7.  
  8.   Integer i = new Integer(null);
  9.   String s = new String(null);
  10.  
  11.  }
  12.  
  13. }



8.What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. public static void main(String [] args)
  6. {
  7.  
  8.   String s = "ONE"+3+2+"TWO"+"THREE"+5+4+"FOUR"+"FIVE"+5;
  9.   System.out.println(s);
  10.  
  11.  }
  12.  
  13. }



9.What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.  
  5. static int method1(int i)
  6. {
  7. return method2(i *= 11);
  8. }
  9.  
  10.  static int method2(int i)
  11. {
  12.   return method3(i /= 11);
  13. }
  14.  
  15.  static int method3(int i)
  16. {
  17.  return method4(i -= 11);
  18. }
  19.  
  20.  static int method4(int i)
  21. {
  22.   return i += 11;
  23. }
        
  24. public static void main(String [] args)
  25. {
  26.  
  27.   System.out.println(method1(11));
  28.  
  29.  }
  30.  
  31. }





10.What is the output of following program?


  1. package com.instanceofjava;
  2. class A
  3. {
  4.     
  5. public static void main(String [] args)
  6. {
  7.  
  8.   System.out.println(null);

  9.  }
  10.  
  11. }



Explanation:

What happens When System.out.println(null)?


  1. Print prime numbers? 
  2. Java Program Find Second highest number in an integer array 
  3. Java Interview Program to find smallest and second smallest number in an array 
  4. Java Coding Interview programming Questions : Java Test on HashMap 
  5. Constructor chaining in java with example programs 
  6. Swap two numbers without using third variable in java 
  7. Find sum of digits in java 
  8. How to create immutable class in java 
  9. AtomicInteger in java 
  10. Check Even or Odd without using modulus and division  
  11. String Reverse Without using String API 
  12. Find Biggest substring in between specified character
  13. Check string is palindrome or not?
  14. Reverse a number in java? 
For more interview programs : Java Programs asked in interviews

Group Discussion on Java Topic

Hi Friends We are planning to conduct a group discussion on a topic every week So interested candidates can join us based on everybody convenience time we will schedule it.

We will conclude the topic at the end.

Our Skype ID : Instanceofjava.

Update: Based on your interest and time we will schedule the session. its free




Select Menu