Skip to main content

Posts

Showing posts from September, 2014

Java MCQ's on Internal Working of HashMaps

This test contains 10 questions based on Internal Working of the HashMap . Each question answered correctly awards you 1 point and each incorrect answer has a penalty of -0.25 points, no points are deducted for unattempted answers. Select Test Type Timed Test UnTimed Test You Get +1 for each correct answer and -0.25 for each incorrect answer Time Left - minutes : seconds How are key values stored in a hashmap ? as Entry object as a LinkedList as an ArrayList None of these A All the objects in the form of a key-value pair are stored as an Entry object. What is the initial size of a HashMap when we create an object of a HashMap ? 0 8 16 None of these C When we create a HashMap like "HashMap map = new HashMap ();" , it creates an empty hashmap of initial size of 16

What are static variables in Java ?

Points To Remember Static variable are the variables at the class level. Static variables are not attached to the objects. Static variable cannot be declared inside any method of a class. Static variables are assigned the memory only once during the execution of the class. Static variables can be called directly from static context or by class reference. Definition Static variables are the class level variable that are allocated the memory only once and they cannot be declared inside any method of a class or inside a static block or static method but can be declared only  outside all methods and inside a class. A static variable is called by using the reference of the class and not the object. Example So lets assume an easy example where we have a class Test, with two variables, " a " non-static variable and the other " b " a static variable. Then variable "a" will be specific to the objects of the class Test and variable "b" will be common for a

Can we override a static method in Java ?

Points To Remember Static methods can not be overriden. Static methods are at class level and not at object level. Static methods take lock on a class and non static methods takes lock on an object. Example : Trying to override a static method Suppose we have a class A and another class B that extends this class. Both the classes have same static method test() with same return type and same parameters. So this satisfies this the conditions for overriding a function. So what will be the output of the following program ? class A{ public static void test(){ System.out.println("Class A"); } } public class B extends A{ public static void main(String args[]){ A obj1 = new B(); B obj2 = new B(); obj1.test(); obj2.test(); A.test(); B.test(); } public static void test(){ System.out.println("Class B"); } } Class A Class B Class A Class B So, why did we get this output ? Incase it was a case of overriding we should have got the output of obj1.

What is a TreeSet in Java ?

Points To Remember TreeSet is ordered and sorted Set. TreeSet extends AbstractSet and implements NavigableSet. Objects are stored in ascending order based on natural ordering. You can even define your sorting rules for sorting a TreeSet using constructors with Comparable or Comparator. It is fast for Accessing/Retrieving objects but slow for Adding/Removing objects.  Constructor : TreeSet TreeSet(); // Default Constructor TreeSet(Collection<? extends E> c); //TreeSet from Collection C TreeSet(Comparator<? super E> comp); // TreeSet with custom ordering as per Comparator TreeSet(SortedSet<E>ss); //TreeSet that contains the elements of ss. Example : TreeSet Implementation Suppose we have a Set of Tourists from different countries and we want to sort them according to their names.(Right now we can just neglect the country of the tourists). import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<String> tourists = new

How HashSet works internally in Java ??

Points To Remember HashSet returns unordered and unsorted values. HashSet contains only the unique values. HashSet maintains an internal HashMap to provide uniqueness.  How Set maintains Uniqueness ?? The following program shows how we add new values to a set. import java.util.Set; import java.util.HashSet; class SetImpl{ public static void main(String args[]){ Set<object> set = new HashSet<object>(); set.add(100); set.add("Java"); set.add("String"); set.add("Java"); set.add("Java"); System.out.println(set); } } Output of the program is [100, String, Java] Now, the question is how does Set maintains  uniqueness. The answer is that Set internally maintains a HashMap. Surprised ?? If you open the implementation of HashSet in the java api you will get the following implementation. public class HashSet extends AbstractSet implements Set , Cloneable, java.io.Serializable { private transient HashMap

What is a JSP in Java J2EE.

Points To Remember JSP stands for Java Server Pages. Jsp at compilation time is a servlet and also behaves like a servlet. Jsp serves as views  in MVC architecture. Jsp can contain HTML code inside them. They are compiled everytime they are requested. What is a JSP ? JavaServer Pages (JSP) is a technology for developing dynamic web pages with dynamic data. You can write java code within a jsp along with the Html using special Jsp tags most of which start with <% and end with %>. A JavaServerPage component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands. Using JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. JSP tags can be used for a variety of purposes, such as retrieving information from a databa

Difference between ServletConfig and ServletContext

Difference : ServletContext vs ServletConfig ServletContext ServletConfig Servlet Context is a global configuration for servlets in a an application i.e this is same for all the servlets.  Servlet Config is a local configuration for each servlet in an application i.e each servlet has its own servlet configuration that may differ from the servlet config of another servlet. ServletContext is one per application. ServletConfig is one per servlet.  It is created at the time of deployment of the web application. It is initialized when a servlet is initialized.  Its scope is as long as the application is up and running, it will be destroyed when the application is removed from the server.  Its scope isand is destroyed when a servlet is destroyed by the servlet container.  In web.xml it should be declared as <context-param> tag and it should be under <web-app> tag. In web.xml it should be declared as <init-param> under <servlet-class> tag. ServletContext object will be

What are Filters in Java J2EE applications.

Points To Remember A filter is hit before the servlet or a controller is hit and before the response is sent back to the client. Filters can be used to apply some action on application level. A filter implements the javax.servlet.Filter interface and the primary filter functionality is implemented by the doFilter() method of the filter. Filters can be used to manipulate both requests from client and response from server. What is a Filter in Java Web Applications ? A filter is a useful way of performing filtering operations in java web applications bith before a request reaches the backend server and after the response is received from the backend server. A filter is basically used to filter things. Suppose you want to make your application accessible to a particular country, then you can apply IP filtering in your application, similarly we can have various types of filters like Authentication Filters Data compression Filters Encryption Filters Filters that trigger resource access event

How to select Second largest value from a database.

Why this question is important ? This is a most frequently asked question in an interview these days. This question tests the thinking of a candidate and how much the candidate knows about the database. This question  cannot be done without the use of a sub query and most of the people are not comfortable writing the sub-queries. So if you are not very comfortable with database queries you might get tricked in this question. Example  Suppose we have a table with id's from 1 to 1000 and we need to find the second largest id from this table. Let's say we have table create table test(id int not null primary_key, name varchar(50)); So we can get the second largest value of id in the following ways. SELECT max(id) FROM test WHERE id!=(SELECT MAX(id) FROM test GROUP BY id) GROUP BY id; SELECT MIN(id) FROM test (SELECT id FROM test ORDER BY id DESC LIMIT 2) t ; In Query 1 : SELECT max(id) FROM test WHERE id!=(SELECT MAX(id) FROM test GROUP BY id) GROUP BY id; We first find the largest

Introduction To Spring Roo

What is Spring Roo ? Spring Roo is a spring productivity tool that simply reduces the pain of a developer by doing all the configuration related stuff for a project. Spring Roo does not require any extra knowledge  expect java. Roo makes it fast and easy to build full Java applications in minutes. Why Use Spring Roo ? Following are the points why we should use Spring Roo. Higher Productivity - We can get started with the java project just in minutes and the roo follows the best practice standard methods to create the application for us Stock Standard Java -  Roo works perfectly with all the versions of java from Java 5.0 and above. So you need not to upgrade your java versions. Roo works perfectly with projects for Spring, JSP's ,  JPA like Hibernate etc. So working with Roo will be very easy and familiar for a developer. Usable and Learnable -  No Engineering Tradeoffs - Roo is not a part of Production code, hence Roo in no way can have any trade-off effects on the code. It will n

Sorting objects using Comparable Interface.

Points To Remember Comparable is an interface and is available in java.lang package. A class implementing it should override compareTo() method. compareTo(Object obj) method returns  negative integer if object obj is greater than the object with  whom it is compared. 0 if both the objects have same values or are same. positive integer if object obj have is less than the object with whom it is compared. While overriding compareTo() method we must check If the two objects belong to the same class, else throw ClassCastException. If the two objects are not null, if either is null then throw NullPointerException. We need not implement this class if we need to sort an array or list with objects like string, integers etc.  Example:  Sorting a list of objects using Comparable Interface Suppose we have a class Book with fields name and price and we need to sort the objects based on the name of the book, if the name of the book is same then we sort the book object based on the price of the bo

Difference between Comparator and Comparable Interfaces

Difference between Comparator and Comparable Comparator Comparable It is available in java.util package. It is available in java.lang package. We need to override compare()  method. We need to override compareTo() method. It takes two arguments as parameters. public int compare(Object obj1,Object obj2 )  It takes only one argument as a parameter. public int compareTo(Object obj) Its primary use is where we need to write the comparing logic outside the class which has to be compared.   It is used when we need to compare the instance of an object with a given object. Comparing logic is inside the class that needs to be compared.   this reference is not made while comparing objects this  reference is used to compare the object.  It is used for comparing objects based on any logic. It is mostly used for comparing objects based on the natural ordering. Points To Remember Both compareTo() and compare() methods return int value. Both compareTo() and compare() methods return either a nega

Difference between Interface and Abstract Class

Difference Between Interface and Abstract Class Interface Abstract Class An interface is an unimplemented class. An abstract class is an incomplete class. All methods are by default public abstract. An abstract class can have both abstract and non abstract methods. All variables by default public static final by default Variables may be static final or may not be.  They cannot have any implemented methods. They can have any number of  implemented methods. An interface must be implemented by the base class. An abstract class must be extended by the base class. You need to override each method of an interface in the sub class. You need to override abstract methods only. An interface cannot have a constructor An abstract class can have a constructor. An interface can extend more than one interfaces. An abstract class can implement more than one interface. Point To Remember Object of both an interface and an abstract class can not be made. An abstract class may not override all methods of

What are classes in Java

First things that comes in mind are A class is a blueprint from which objects are created. They are wrappers and have everything inside them e.g Functions/Methods/Variables etc. They can be public or default but not private or protected. Each Class has a name, and may belong to a package. A class can have both static and non static methods and variables. A class can not be static (however inner classes can be). Definition A class is the blueprint from which individual objects are created. A class containes A main method marked as public static void and taking an array of String arguments. Instance variables that are inside a class but outside all function. Local variables that are inside a function. Their scope is limited to the function only. Member functions that can be either static, non static or final or final static. A package declaration, this is important for grouping same type of classes together. package com.ekiras.demo; public class HelloWorld{ int instanceVarible = 1; p

How to sort objects using Comparator Interface

Points To Remember Comparator is an interface and is available in java.util package. A class that implement Comparator interface must override its compare() method.  We use Comparator when we have to write logic for comparing object of a class outside that class. compare(Object e1, Object e2): Can be called like compare(e1, e2) compare(Objecte obj1, Object obj2) method returns zero if the objects are equal. compare(Objecte obj1, Object obj2) method returns a positive value if obj1 is greater than obj2. compare(Objecte obj1, Object obj2) method returns a negative value if obj1 is smaller than obj2. It should throw ClassCastException if object types of e1 and e2 are not comparable. It should throw NullPointerException if either e1 or e2 or both passed are null. Syntax for using Comparator interface. First we need a class for which we need to write the sorting logic(how to compare objects of this class). Then we need to create a new class that will do this comparing for this class. A

Program to reverse each word of the String.

Program : Reverse each word of String  Write a program that takes a string input from the user and then reverse each word of the of the line as entered by the user. Expected input   : "This is a very good blog" Expected output : "sihT si a yrev doog golb" import java.io.*; public class ReverseString{ public static void main(String args[]){ ReverseString obj = new ReverseString(); String inputString = obj.getStringFromUser(); String outputString = ""; String aux = ""; for(int itr=0;itr<inputString.length();itr++){ // reverse the words if a whitespace occurs. if(inputString.charAt(itr) == ' '){ outputString += reverseString(aux) + " "; aux = ""; } else{ // extract the word from the string aux += inputString.charAt(itr); } } // reverse the last word of the string outputString += reverseString(aux); System.out.p

Program to reverse a String

Program -1 Reverse String with input String from arguments public class ReverseString{ public static void main(String args[]){ ReverseString obj = new ReverseString(); System.out.println(obj.reverseString(args[0])); } public String reverseString(String str){ String aux = ""; for(int itr = str.length()-1;itr>=0;itr--){ aux += str.charAt(itr); } return aux; } } Running the program as : java ReverseString ekiras  Output of the program : sarike Program -2 : Reverse String with input from command line at runtime. import java.io.*; public class ReverseString{ public static void main(String args[]){ ReverseString obj = new ReverseString(); System.out.println(obj.reverseString(obj.getStringFromUser())); } public String reverseString(String str){ String aux = ""; for(int itr = str.length()-1;itr>=0;itr--){ aux += str.charAt(itr); } return aux; } public String getStringFromUser(){

Different ways of creating Objects in Java

Different ways of creating Objects Using new  operator. Using Class.forName() and newInstance() . Using Factory Methods Using Object cloning Using Object deserialization Object Creation By Different Methods public class ObjectCreation { public static void main(String args[])throws Exception{ ObjectCreation objecByNewKeyword = createObjecByNewKeyword(); ObjectCreation objecByClassForName = createObjecByClassForName(); ObjectCreation objecByCloning = (ObjectCreation)createObjecByCloning(); // object to be cloned objecByNewKeyword.show("new keyword"); objecByClassForName.show("using Class.forName and newInstance"); objecByCloning.show("cloning"); } public static ObjectCreation createObjecByNewKeyword(){ ObjectCreation obj = new ObjectCreation(); return obj; } public static ObjectCreation createObjecByClassForName() throws ClassNotFoundException, InstantiationException, IllegalAccessException{ Obje

What is a static block in Java ??

Points To Remember A static block is called only once and is not a member of a class . A static block is executed before execution of any other method in the class. If there are more than one static block in a class then, they are executed in order of their occurence  in a class. They do not have a return statement . They cannot contain this or super reference. What is a Static block in Java?? A static block is a block of code that gets executed first at the time the class is called or its object is created. Even if we have a main method in a class and we run this class, even then the code in the static block will be executed before the execution of the main method. If we have more than one static blocks in a clss then they gets executed in the same order as they appear in the code but before any method or even constructor gets executed. Also a static block is not a member of a class and does not contain any return statement or a this or super reference. Example 1 - Static block ex

What is the Difference between Enumeration and Iterator

Points To Remember In java 1.0, there were two primary collection classes HashMap and Vector. Enumeration was a class in Java 1.0 to Iterate through these collection classes.(They are not the enum types.) Iterator was introduced in Java 1.2 Difference between Enumeration and Iterator. Enumeration Iterator It was introduces in Java v1.0 It was introduced in java v1.2 Enumeration does not have remove() method Iterator has remove() method Enumeration provides a read only iteration over collection Iterator provides iteration over collections along with manipulation of objects like adding and removing from object. Enumeration is less safe and secure Iterator is more secure and safe, when multiple thread work on same object, it does not allow any thread to modify the object and throws ConcurrentModificationException. Enumeration has lengthy method names like hasMoreElements() nextElements() Iterator have short method names like hasNext() next() Enumeration is used when we want to iterate Col

What is final keyword in Java.

Where can Finally keyword be used ?? Finally keyword can be  used with the following final variable, a variable marked as final acts like a constant variable whose value can not be changed once assigned throughout the life of the variable. final method,  a method marked as final can never be overridden but can be overloaded.  final class,  a class marked as final can never be extended. final object,  final object is an object whose reference can not be changed once assigned. Final variable final variable when used with any variable, then this variable starts acting like a constant. Value of this variable can not be changed throughout the life of this variable.Suppose we have a final variable in a class and we try to change the value of this variable. public class TestClass{ final int test = 1; public static void main(String args[]){ TestClass obj = new TestClass(); obj.test = 2; System.out.println(obj.test); } } The output of the above program will be TestClass.java:9

How does a HashMap works internally in Java ??

Points To Remember HashMap implements the Map Interface. It works on the principles of hashing.  It stores and retrieves data in a key value pair. HashMap can have only one key as a null element. HashMap stores both key and value in form of Entry object  Map.Entry.  Initial capacity of HashMap is 16. (Since jdk 1.7 we can have HashMap with initial capacity as 0). Default load Factor of a HashMap is 0.75, after this a HashMap gets rehashed.  Q1 : How does HashMap work internally ?  We add data to the HashMap in key-value pair, by method put(key, value).  When we do this, the hashCode() method is called upon the key to return a hashcode, this hashcode is an integer value 16 digit long by default. This hashcode is then used by the HashMap's internal hashing method to find a bucket location  to store the Entry object. At this bucket location both key and value is saved in the bucket. Since we know that different objects can result into the same hashcode, thus all the keys that result

Create Mysql Database JDBC connection in Java.

Points To Remember  Download  Mysql Java Connector  by clicking on the link. Put the above downloaded jar file in the lib  folder of your project. Code : Mysql JDBC connection in Java import java.sql.Connection; import java.sql.DriverManager; public class JavaMysqlConnection { private String host = "localhost:3306"; // For running on localhost private String db = "databaseName"; private String userName = "userName"; private String password = "password"; public Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://"+ host +"/"+db,userName, password); return conn; }catch(Exception e){ e.printStackTrace(); } return null; } } public class Test{ public static void main(String[] argv) { Connection conn = new JavaMysqlC

What is Method Overriding in Java ??

When a base class extends a super class and both the base class and the super class have a method with same name, same types of parameters and same number of parameters, then the two methods are said to be overriden. Points To Remember Overriding of methods is always done in a base class or in other words, we always override a parent class method. The access specifier of the overriden method can not be less than the parent class method's access specifier e.g if a parent class method is marked as protected, you can override it with access specifiers protected and public only. Overriden methods should have same number of arguments and of same type . The return type of the overridden method should be same as the overriding method. We cannot override a static methods. We cannot override private methods of parent class in a base class, it will give a compile time error if we try to do so. Example Of Overriding The following is a simple example of overriding. class Base { public Ba

Difference between Method Overloading and Method Overriding

Key Differences Method Overloading Method Overriding Method Overloading always happens within the same class. Method Overriding always happen between a super class and a sub class. In method overloading the return type of the method need not to be the same. In method overriding the return type of the method must be same  Number of arguments can be different. Number of arguments should be same. Overloaded methods can have different access specifiers. Overriding method should not have weaker access specifier than the method it is overriding. Type of arguments can be same or different. Type of arguments should be same. In method overloading one method cannot hide the other method. In method overriding base class method hides the super class method. It helps to achieve Static or Compile time Polymorphism It helps to achieve Dynamic or Run time Polymorphism The above picture tries to show the difference between Overloading and Overriding. In overloading we have more than one arrow(metho

What is Method Overloading in Java ??

We can have multiple methods with the same name as long as their parameter types or number of parameters differ. These methods are called overloaded methods. This is also referred as Static Polymorphism. Points To Remember Overloading of methods is always done in the same class . The access specifier of the overloaded method may or may not be same  to the other overloaded methods. Name of the overloaded methods should be same . The overloaded methods may have different return types . Overloaded methods should have at least one of the following Different argument types Different number of arguments They provide Static or Compile time Polymorphism. Example Of Overloading The following is a simple example of overloading. class Derived { public void show() { System.out.println("show()"); } public void show(String args) { System.out.println("show("+ args +")"); } public void show(int a){ System.out.println("show("+ a +

Overriding equals() method of Object class in java

Default equals() method of the java.lang.Object class compares the memory location of the objects and returns true if the two reference variables are pointing to the same memory location. i.e. they are the same objects. Points To Remember equals() method is the method of Object class. It compares the memory location of the two objects. equals() method in java is Reflexive.  i.e, object must be equal to itself. equals() method in java is  Symmetric.   i.e, if a.equals(b) then b.equals(a) must be true. equals() method in java is  Transitive.   i.e,  if a.equals(b) and b.equals(c) the a.equals(c) must be true. equals() method in java is  Consistent.   i.e, if two objects are same in java then they must remain same all time until any property of any object is changed. If two object are same then their hashCode() will be same, but if the two hashCodes are same then they may or may not be same. Steps to override equals method in Java this check, if the object is same as this, then retur

Can we have multiple main methods in Java ?

Points to remember We can have only one entry point per class in Java. Thus we can have only one " public static void main(String args[]) " . Any other method with a different name or type or arguments will not be treated as a main method(). Yes, we can have multiple main methods in a java class. Surprised ?? Method Overloading, by using this you can have as many main() methods as you want as long as their types or arguments are different. However these are not actually the main() methods , these are just overridden methods and may act as any other overridden method. None of these will be treated as an entry point for execution. Example What will be the output of the following program ?? public class TestClass{ public static final void main (String args[]){ System.out.println("Hello World String args[]"); } public void main (String args){ System.out.println("String args"); } public void main (Integer args){ System.out.println("

Why the main method in java is public static void

What is the "main" method in java?? It is the entry point of execution of any java program. We must have a main(String args[]) or main(String ...) method in a class for its execution. We can have multiple main() methods in a class. Why is main method "public" ?? The main method is always marked as public  because it must always be visible or available to the JVM. You can even say that this is the java convention and it needs to be followed. If we make our main() method as private, our code will still compile without giving any compilation error, but at runtime it will throw an exception " Main method not found in class Class, please define the main method" Why is main method "static" ?? A main method is always static, this because whenever a class has to be accessed, first its object is to be created and only then the class can be instantiated.  The static keyword allows the method to be accessed by the class name without instantiating the class.