Sie sind auf Seite 1von 52

Tricky Java interview questions and Answers

Explain why Java doesn't support multiple inheritance


i. First reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below A foo() /\ / \ foo() B C foo() \ / \/ D foo() In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity. Some times if you give this reason to interviewer he asks if C++ can support multiple inheritance than why not Java. hmmmmm in that case I would try to explain him the second reason which I have given below that its not because of technical difficulty but more to maintainable and clearer design was driving factor though this can only be confirmed by any of java designer and we can just speculate. Wikipedia link has some good explanation on how different language address problem arises due to diamond problem while using multiple inheritances. ii. Second and more convincing reason to me is that multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

Can we overload a main() method in Java?


You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM. For example: public class Test { public static void main(String[] args) { System.out.println("main(String[] args)"); } public static void main(String arg1) { System.out.println("main(String arg1)"); } public static void main(String arg1, String arg2) { System.out.println("main(String arg1, String arg2)"); }

} That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments. You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

Can we override a main() method in Java?


MAIN is a class method (since its static by definition). Hence, it does not makes sense to "override" it (or for that matter any static method). The concept of "overriding" is only for instance methods.

What is immutable object in Java? Can you change values of a immutable object?
A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable objects from the Java Development Kit. Immutable objects simplify your program due to following characteristics :


again.

Immutable objects are simple to use test and construct. Immutable objects are automatically thread-safe. Immutable objects do not require a copy constructor. Immutable objects do not require an implementation of clone. Immutable objects allow hashCode to use lazy initialization, and to cache its return value. Immutable objects do not need to be copied defensively when used as a field.

Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection). Immutable objects have their class invariant established once upon construction, and it never needs to be checked

Immutable objects always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state.

How to create a immutable object in Java? Does all property of immutable object needs to be final?
To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

What is difference between String, StringBuffer and StringBuilder? When to use them?
The main difference between the three most commonly used String classes as follows.

StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable. StringBuffer class implementation is synchronized while StringBuilder class is not synchronized. Concatenation operator "+" is internally implemented by Java using either StringBuffer or StringBuilder. If the Object value will not change in a scenario use String Class because a String object is immutable.

Criteria to choose among String, StringBuffer and StringBuilder If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster). If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

Why String class is final or immutable?


It is very useful to have strings implemented as final or immutable objects. Below are some advantages of String Immutability in Java

Immutable objects are thread-safe. Two threads can both work on an immutable object at the same time without any possibility of conflict. Security: the system can pass on sensitive bits of read-only information without worrying that it will be altered You can share duplicates by pointing them to a single instance.

You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret that makes Java substring implementation very fast. Immutable objects are good fit for becoming Hashtable keys. If you change the value of any object that is used as a hash table key without removing it and re-adding it you will lose the object mapping. Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth. If String were not final, you could create a subclass and have two strings that look alike when "seen as Strings", but that are actually different.

Is Java Pass by Reference or Pass by Value?


The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java. The difficult thing can be to understand that Java passes "objects as references" passed by value. This can certainly get confusing and I would recommend reading this article from an expert: http://javadude.com/articles/passbyvalue.htm Also read this interesting thread with example on StackOverflow : Java Pass By Ref or Value

What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?

This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered 1. java.lang.OutOfMemoryError: Java heap space

The quick solution is to add these flags to JVM command line when Java runtime is started:

1. 2.

-Xms1024m -Xmx1024m

java.lang.OutOfMemoryError: PermGen space

The solution is to add these flags to JVM command line when Java runtime is started: view plainprint? 1. -XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled Long Term Solution: Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. You can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place.

What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?
Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. Finally block is NOT called in following conditions

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call. if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.

Why there are two Date classes; one in java.util package and another in java.sql?
From the JavaDoc of java.sql.Date: A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE, the millisecond values wrapped inside a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero. Explanation: A java.util.Date represents date and time of day, a java.sql.Date only represents a date (the complement of java.sql.Date is java.sql.Time, which only represents a time of day, but also extends java.util.Date).

What is Marker interface? How is it used in Java?


The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are

java.io.Serializable - Serializability of a class is enabled by the class implementing the java.io.Serializable interface. The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

java.rmi.Remote - The Remote interface serves to identify interfaces whose methods may be invoked from a nonlocal virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.

java.lang.Cloneable - A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

methods.

javax.servlet.SingleThreadModel - Ensures that servlets handle only one request at a time. This interface has no java.util.EvenListener - A tagging interface that all event listener interfaces must extend.

The "instanceof" keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.

Why main() in java is declared as public static void main? What if the main method is declared as private?
Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application static - When the JVM makes are call to the main method there is not object existing for the class being called therefore it has to have static method to allow invocation from class. void Java is platform independent language therefore if it will return some value then the value may mean different to different platforms so unlike C it can not assume a behavior of returning value to the operating system. If main method is declared as private then - Program will compile properly but at run-time it will give "Main method not public." error.

What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

Can we override private method in Java


No, We can not override private method in Java, just like we can not override static method in Java. Like static methods, private method in Java is also bonded during compile time using static binding by Type information and doesn't depends on what kind of object a particular reference variable is holding. Since method overriding works on dynamic binding, its not possible to override private method in Java. private methods are not even visible to Child class, they are only visible and accessible in the class on which they are declared. private keyword provides highest level of Encapsulation in Java. Though you can hide private method in Java by declaring another private method with same name and different method signature. public class PrivateMethodCanNotBeOverriden{

public static void main(String args[]) { //shows that private method can not be overridden in Java Parent parent = new Child(); }

class Parent{

public Parent(){ name(); normal(); }

private void name(){ System.out.printf("private method inside Parent class in Java %n"); }

public void normal(){ System.out.println("non private method from Parent class can be overridden"); }

class Child extends Parent{

/* * Private method can not be overridden in Java, they can only be hidden */

private void name(){ System.out.printf("private method inside Child class in Java %n"); }

@Override public void normal(){ System.out.println("non private overridden method from Child class "); }

Output private method inside Parent class in Java non private overridden method from Child class

What will happen if we put a key object in a HashMap which is already there?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys.

Why non static variable can not be called from static method
Now before finding answer of compiler error "non-static variable cannot be referenced from a static context", let's have a quick revision of static. Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance(). So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance. In summary since code in static context can be run even without creating any instance of class, it does not make sense asking value for an specific instance which is not yet created.

How to access non static variable inside static method or block


You can still access any non static variable inside any static method or block by creating an instance of class in Java and using that instance to reference instance variable. This is the only legitimate way to access non static variable on static context. here is a code example of accessing non static variable inside static context:

public class StaticTest { private int count=0; public static void main(String args[]) throws IOException { StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class test.count++; } } So next time if you get compiler error non-static variable cannot be referenced from a static context access static member by creating an instance of Class.

Imp Points about String Class


1) String is immutable in Java: String is by design immutable in Java you can check this post for reason. Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads without any extra synchronization. 2)when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are actually same instance of String. Anyway comparing object with equality operator is bad practice in Java and you should always use equals method to check equality. 3) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBufferor StringBuilder. 4) Strings are backed up by character Array and represented in UTF-16 format. By the way this behavior can cause memory leak in Stringbecause same character array is shared between source String and SubString which can prevent source String from being garbage collected. SeeHow SubString works in Java for more details. 5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. See how to correctly override equals method in Java to learn more about best practices on equals method. Another worth noting point is that equals method must be consistent with compareTo() method for String because SortedSet and SortedMap e.g. TreeMap uses compareTo method to compare String in Java. 7) toString() method provides String representation of any object and its declared in Object class and its recommended for other class to implement this and provide String representation. 8) String is represented using UTF-16 format in Java.

9) In Java you can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.

String Methods:
Here is the list methods supported by String class: SN Methods with Description char charAt(int index) Returns the character at the specified index. int compareTo(Object o) Compares this String to another Object. int compareTo(String anotherString) Compares two strings lexicographically. int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences. String concat(String str) Concatenates the specified string to the end of this string. boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array specified. static String copyValueOf(char[] data, int offset, int count) Returns a String that represents the character sequence in the array specified. boolean endsWith(String suffix) Tests if this string ends with the specified suffix. boolean equals(Object anObject) Compares this string to the specified object. boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations.

10

11

12

byte getBytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. byte[] getBytes(String charsetName Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array. int hashCode() Returns a hash code for this string. int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. String intern() Returns a canonical representation for the string object. int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

13

14

15

16

17

18

19

20

21

22

23

24

25

int length() Returns the length of this string. boolean matches(String regex) Tells whether or not this string matches the given regular expression. boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal. boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal. String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. String replaceAll(String regex, String replacement Replaces each substring of this string that matches the given regular expression with the given replacement. String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. String[] split(String regex) Splits this string around matches of the given regular expression. String[] split(String regex, int limit) Splits this string around matches of the given regular expression. boolean startsWith(String prefix) Tests if this string starts with the specified prefix. boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index. CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence. String substring(int beginIndex) Returns a new string that is a substring of this string. String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.

26

27

28

29

30

31

32

33

34

35

36

37

38

39

char[] toCharArray() Converts this string to a new character array. String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale. String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale. String toString() This object (which is already a string!) is itself returned. String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale. String trim() Returns a copy of the string, with leading and trailing whitespace omitted. static String valueOf(primitive data type x) Returns the string representation of the passed data type argument.

40

41

42

43

44

45

46

Examples:-

charAt
Description: This method returns the character located at the String's specified index. The string indexes start from zero. Syntax: Here is the syntax of this method:

public char charAt(int index)


Parameters: Here is the detail of parameters:

index -- Index of the character to be returned. Return Value:

This method Returns a char at the specified index.

Example:

public class Test {


public static void main(String args[]) { String s = "Strings are immutable"; char result = s.charAt(8); System.out.println(result); } } This produces following result: a

compareTo
Description: There are two variant of this method. First method compares this String to another Object and second method compares two strings lexicographically. Syntax: Here is the syntax of this method:

int compareTo(Object o) or int compareTo(String anotherString)


Parameters: Here is the detail of parameters:

o -- the Object to be compared. anotherString -- the String to be compared. Return Value :

The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string. Example: public class Test { public static void main(String args[]) { String str1 = "Strings are immutable"; String str2 = "Strings are immutable"; String str3 = "Integers are not immutable";

int result = str1.compareTo( str2 ); System.out.println(result); result = str2.compareTo( str3 ); System.out.println(result); result = str3.compareTo( str1 ); System.out.println(result); } } This produces following result: 0 10 -10

compareToIgnoreCase
Description: This method compares two strings lexicographically, ignoring case differences. Syntax: Here is the syntax of this method:

int compareToIgnoreCase(String str)


Parameters: Here is the detail of parameters:

str -- the String to be compared. Return Value:

This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations. Example:

public class Test {


public static void main(String args[]) { String str1 = "Strings are immutable"; String str2 = "Strings are immutable"; String str3 = "Integers are not immutable"; int result = str1.compareToIgnoreCase( str2 ); System.out.println(result); result = str2.compareToIgnoreCase( str3 ); System.out.println(result);

result = str3.compareToIgnoreCase( str1 ); System.out.println(result); } } This produces following result: 0 10 -10

concat
Description: This method appends one String to the end of another. The method returns a String with the value of the String passed in to the method appended to the end of the String used to invoke this method. Syntax: Here is the syntax of this method:

public String concat(String s)


Parameters: Here is the detail of parameters:

s -- the String that is concatenated to the end of this String. Return Value :

This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters. Example: public class Test { public static void main(String args[]) { String s = "Strings are immutable"; s = s.concat(" all the time"); System.out.println(s); } } This produces following result: Strings are immutable all the time

contentEquals

Description: This method returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. Syntax: Here is the syntax of this method:

public boolean contentEquals(StringBuffer sb)


Parameters: Here is the detail of parameters:

sb -- the StringBuffer to compare. Return Value :

This method returns true if and only if this String represents the same sequence of characters as the specified StringBuffer, otherwise false. Example: public class Test { public static void main(String args[]) { String str1 = "Not immutable"; String str2 = "Strings are immutable"; StringBuffer str3 = new StringBuffer( "Not immutable"); boolean result = str1.contentEquals( str3 ); System.out.println(result); result = str2.contentEquals( str3 ); System.out.println(result); } } This produces following result: true false

copyValueOf
Description: This method has two different forms:

public static String copyValueOf(char[] data): Returns a String that represents the character sequence in the array specified. public static String copyValueOf(char[] data, int offset, int count): Returns a String that represents the character sequence in the array specified.

Syntax: Here is the syntax of this method:

public static String copyValueOf(char[] data) or public static String copyValueOf(char[] data, int offset, int count)
Parameters: Here is the detail of parameters:

data -- the character array. offset -- initial offset of the subarray. count -- length of the subarray. Return Value :

This method returns a String that contains the characters of the character array. Example: public class Test { public static void main(String args[]) { char[] Str1 = "This is really not immutable!!"; String Str2; Str2 = copyValueOf( Str1 ); System.out.println("Returned String " + Str2); Str2 = copyValueOf( Str1, 5, 10 ); System.out.println("Returned String " + Str2); } } This produces following result: This is really not immutable!! is rea

endsWith

Description: This method tests if this string ends with the specified suffix. Syntax: Here is the syntax of this method: public boolean endsWith(String suffix) Parameters: Here is the detail of parameters: suffix -- the suffix. Return Value: This method returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise. Note that the result will be true if the argument is the empty string or is equal to this String object as determined by the equals(Object) method. Example: public class Test{ public static void main(String args[]){ String Str = new String("This is really not immutable!!"); boolean retVal; retVal = Str.endsWith( "immutable!!" ); System.out.println("Returned Value = " + retVal ); retVal = Str.endsWith( "immu" ); System.out.println("Returned Value = " + retVal ); } } This produces following result: Returned Value = true Returned Value = false

equals
Description: This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. Syntax: Here is the syntax of this method:

public boolean equals(Object anObject) Parameters: Here is the detail of parameters: anObject -- the object to compare this String against. Return Value : This method returns true if the String are equal; false otherwise. Example: public class Test { public static void main(String args[]) { String Str1 = new String("This is really not immutable!!"); String Str2 = Str1; String Str3 = new String("This is really not immutable!!"); boolean retVal; retVal = Str1.equals( Str2 ); System.out.println("Returned Value = " + retVal ); retVal = Str1.equals( Str3 ); System.out.println("Returned Value = " + retVal ); } } This produces following result: Returned Value = true Returned Value = true

equalsIgnoreCase
Description: This method compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case. Syntax: Here is the syntax of this method: public boolean equalsIgnoreCase(String anotherString) Parameters: Here is the detail of parameters: anotherString -- the String to compare this String against Return Value :

This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise. Example: public class Test { public static void main(String args[]) { String Str1 = new String("This is really not immutable!!"); String Str2 = Str1; String Str3 = new String("This is really not immutable!!"); String Str4 = new String("This IS REALLY NOT IMMUTABLE!!"); boolean retVal; retVal = Str1.equals( Str2 ); System.out.println("Returned Value = " + retVal ); retVal = Str1.equals( Str3 ); System.out.println("Returned Value = " + retVal ); retVal = Str1.equalsIgnoreCase( Str4 ); System.out.println("Returned Value = " + retVal ); } } This produces following result: Returned Value = true Returned Value = true Returned Value = true

getBytes
Description: This method has following two forms: getBytes(String charsetName): Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. getBytes(): Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. Syntax: Here is the syntax of this method: public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

or

public byte[] getBytes() Parameters: Here is the detail of parameters: charsetName -- the name of a supported charset. Return Value : This method returns the resultant byte array Example: import java.io.*; public class Test{ public static void main(String args[]){ String Str1 = new String("Welcome to Tutorialspoint.com"); try{ byte[] Str2 = Str1.getBytes(); System.out.println("Returned Value " + Str2 ); Str2 = Str1.getBytes( "UTF-8" ); System.out.println("Returned Value " + Str2 ); Str2 = Str1.getBytes( "ISO-8859-1" ); System.out.println("Returned Value " + Str2 ); }catch( UnsupportedEncodingException e){ System.out.println("Unsupported character set"); } } } This produces following result: Returned Returned Returned Value [B@192d342 Value [B@15ff48b Value [B@1b90b39

getChars
Description: This method copies characters from this string into the destination character array. Syntax: Here is the syntax of this method: public void getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) Parameters:

Here is the detail of parameters: srcBegin -- index of the first character in the string to copy. srcEnd -- index after the last character in the string to copy. dst -- the destination array. dstBegin -- the start offset in the destination array. Return Value : It does not return any value but throws IndexOutOfBoundsException. Example: import java.io.*; public class Test{ public static void main(String args[]){ String Str1 = new String("Welcome to Tutorialspoint.com"); char[] Str2 = new char[7]; try{ Str1.getChars(2, 9, Str2, 0); System.out.print("Copied Value = " ); System.out.println(Str2 ); }catch( Exception ex){ System.out.println("Raised exception..."); } } } This produces following result: Copied Value = lcome t

hashCode
Description: This method returns a hash code for this string. The hash code for a String object is computed as: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) Syntax: Here is the syntax of this method: public int hashCode()

Parameters: Here is the detail of parameters: NA Return Value: This method returns a hash code value for this object.

Example:
import java.io.*; public class Test{ public static void main(String args[]){ String Str = new String("Welcome to Tutorialspoint.com"); System.out.println("Hashcode for Str :" + Str.hashCode() ); } } This produces following result: Hashcode for Str :1186874997

indexOf
Description: This method has following different variants: public int indexOf(int ch): Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur. public int indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index or -1 if the character does not occur. int indexOf(String str): Returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned. int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If it does not occur, -1 is returned. Syntax: Here is the syntax of this method: public int indexOf(int ch ) or public int indexOf(int ch, int fromIndex)

or int indexOf(String str) or int indexOf(String str, int fromIndex) Parameters: Here is the detail of parameters: ch -- a character. fromIndex -- the index to start the search from. str -- a string. Return Value: See the description. Example: import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); String SubStr1 = new String("Tutorials"); String SubStr2 = new String("Sutorials"); System.out.print("Found Index :" ); System.out.println(Str.indexOf( 'o' )); System.out.print("Found Index :" ); System.out.println(Str.indexOf( 'o', 5 )); System.out.print("Found Index :" ); System.out.println( Str.indexOf( SubStr1 )); System.out.print("Found Index :" ); System.out.println( Str.indexOf( SubStr1, 15 )); System.out.print("Found Index :" ); System.out.println(Str.indexOf( SubStr2 )); } } This produces following result: Found Found Found Found Found Index Index Index Index Index :4 :9 :11 :-1 :-1

intern

Description: This method returns a canonical representation for the string object. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. Syntax: Here is the syntax of this method: public String intern() Parameters: Here is the detail of parameters: NA Return Value: This method Returns a canonical representation for the string object. Example: import java.io.*; public class Test{ public static void main(String args[]){ String Str1 = new String("Welcome to Tutorialspoint.com"); String Str2 = new String("WELCOME TO SUTORIALSPOINT.COM"); System.out.print("Canonical representation:" ); System.out.println(Str1.intern()); System.out.print("Canonical representation:" ); System.out.println(Str2.intern()); } } This produces following result: Canonical representation: Welcome to Tutorialspoint.com Canonical representation: WELCOME TO SUTORIALSPOINT.COM

Differences between String and StringBuffer in Java


Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBufferobject once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular Java interview questions for

either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.

Difference between StringBuilder and StringBuffer in Java


StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using eitherStringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilder vs String.

Summary
In summary here are list of difference between StringBuffer, String and StringBuilder in Java : 1) String is immutable while StringBuffer and StringBuilder is mutable object. 2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer. 3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder. 4) Use String if you require immutability, use Stringbuffer in java if you need mutable + thread-safety and use StringBuilder in Java if you require mutable + without thread-safety. That's all on famous String vs StringBuffer or StringBuffer vs StringBuilder discussion. All these differences helps to avoid common coding mistake of using String in place of StringBuffer in many places. from Java 5 onwards either use + operator of StringBuilder for concatenating String in Java.

Important Questions HashMap & HashTable


Difference between HashMap & HashTable
Both HashMap and Hashtable implements Map interface but there are some significant difference between them which is important to remember before deciding whether to use HashMap or Hashtable in Java. Some of them is thread-safety, synchronization and speed. here are those differences :

1.The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

2. One of the major differences between HashMap and Hashtable is that HashMap is non synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not be shared between multiple threads without proper synchronization. Java 5 introduces ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java. 3. Another significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java. 4. One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don't need synchronization and HashMap is only used by one thread, it out perform Hashtable in Java. 5. HashMap does not guarantee that the order of the map will remain constant over time. Note on Some Important Terms 1)Synchronized means only one Thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for lock to be released. 2)Fail-safe is relevant from the context of iterators. If an Iterator or ListIterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown. 3)Structurally modification means deleting or inserting element which could effectively change the structure of map. HashMap can be synchronized by Map m = Collections.synchronizeMap(hashMap); In Summary there are significant differences between Hashtable and HashMap in Java e.g. thread-safety and speed and based upon that only use Hashtable if you absolutely need thread-safety, if you are running Java 5 consider using ConcurrentHashMap in Java. "Do you Know how HashMap works in Java or "How does get () method of HashMap works in Java" And then you get answers like I don't bother its standard Java API, you better look code on Java source or Open JDK; I can find it out in Google at any time etc. But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put(key, value) and get(key) method for storing and retrievingObjects from HashMap. When we pass Key and Value object to put() method on Java HashMap, HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket which is essential to understand the retrieving logic. If people fails

to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in Java HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge on how hashing works and how HashMap works in Java. But this is just start of story and confusion increases when you put interviewee on scenarios faced by Java developers on day by day basis. Next question could be about collision detection and collision resolution in Java HashMap e.g. "What will happen if two different objects have same hashcode? Now from here onwards real confusion starts, Some time candidate will say that since hashcode is equal, both objects are equal and HashMap will throw exception or not store them again etc, Then you might want to remind them about equals() and hashCode() contract that two unequal object in Java can have same hashcode. Some will give up at this point and few will move ahead and say "Since hashcode is same, bucket location would be same and collision will occur in HashMap, SinceHashMap use LinkedList to store object, this entry (object of Map.Entry comprise key and value ) will be stored in LinkedList. Great this answer make sense though there are many collision resolution methods available this is simplest and HashMap in Java does follow this. But story does not end here and interviewer asks "How will you retrieve Value object if two Keys will have same hashcode? Interviewee will say we will call get() method and then HashMap uses Key Object's hashcode to find out bucket location and retrieves Value object but then you need to remind him that there are two Value objects are stored in same bucket , so they will say about traversal in LinkedList until we find the value object , then you ask how do you identify value object because you don't have value object to compare ,Until they know that HashMap stores both Key and Value in LinkedListnode or as Map.Entry they won't be able to resolve this issue and will try and fail. But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in LinkedList and return associated value object for that key in Java HashMap . Perfect this is the correct answer. In many cases interviewee fails at this stage because they get confused between hashCode() and equals() or keys and values object in Java HashMap which is pretty obvious because they are dealing with the hashcode() in all previous questions and equals() come in picture only in case of retrieving value object from HashMap in Java. Some good developer point out here that using immutable, final object with proper equals() and hashcode() implementation would act as perfect Java HashMap keys and improve performance of Java HashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap. Now if you clear this entire Java HashMap interview, You will be surprised by this very interesting question "What happens On HashMap in Java if the size of the HashMap exceeds a given threshold defined by load factor ?". Until you know how HashMap works exactly you won't be able to answer this question. If the size of the Map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Similar to other collection classes likeArrayList, Java HashMap re-size itself by creating a new bucket array of size twice of previous size of HashMap , and then start putting every old element into that new bucket array. This process is called rehashing because it also applies hash function to find new bucket location.

If you manage to answer this question on HashMap in Java you will be greeted by "do you see any problem with resizing of HashMap in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the Java HashMap and potentially looking for race condition on HashMap in Java. So the answer is Yes there is potential race condition exists while resizing HashMap in Java, if two thread at the same time found that now HashMap needs resizing and they both try to resizing. on the process of resizing of HashMap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java HashMap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop. Though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer :) Few more question on HashMap in Java which is contributed by readers of Javarevisited blog : 1) Why String, Integer and other wrapper classes are considered good keys ? String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method. Other wrapper class also shares similar property. Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap. Immutability is best as it offers other advantages as well like thread-safety, If you can keep your hashCode same by only making certain fields final, then you go for that as well. Since equals() and hashCode() method is used during reterival of value object from HashMap, its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap. 2) Can we use any custom object as key in HashMap ? This is an extension of previous questions. Ofcourse you can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map. If custom object is Immutable than this will be already taken care because you can not change it once created. 3) Can we use ConcurrentHashMap in place of Hashtable ? This is another question which getting popular due to increasing popularity of ConcurrentHashMap. Since we know Hashtable is synchronized butConcurrentHashMap provides better concurrency by only locking portion of map determined by concurrency level. ConcurrentHashMap is certainly introduced asHashtable and can be used in place of it but Hashtable provide stronger thread-safety than ConcurrentHashMap. See my post difference between Hashtable and ConcurrentHashMap for more details. Personally, I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified

Concept of hashing Collision resolution in HashMap Use of equals () and hashCode () and there importance in HashMap?

Benefit of immutable object? Race condition on HashMap in Java Resizing of Java HashMap

Just to summarize here are the answers which does makes sense for above questions How HashMap works in Java HashMap works on principle of hashing, we have put() and get() method for storing and retrieving object form HashMap .When we pass an both key and value to put() method to store on HashMap , it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object. While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list. Also HashMap stores both key+value tuple in every node of linked list. What will happen if two different HashMap key objects have same hashcode? They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap . In terms of usage Java HashMap is very versatile and I have mostly used HashMap as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching HashMap and ConcurrentHashMap comes as very handy there

10 Java Hashtable Examples:


Now lets move on Hashtable examples in Java following is a list of all examples of hashtable operation we will see in this article: 1. How to put object into Hashtable? 2. How to retrieve object from Hashtable in Java? 3. How to reuse Hashtable by using clear()? 4. How to check if Hastable contains a particular value? 5. How to check if Hashtable contains a particular key? 6. How to traverse Hashtable in Java? 7. How to check if Hashtable is empty in Java? 8. How to Copy content of Hashtable into HashMap? 9. How to find size of Hashtable in Java? 10. How to get all values form hashtable in Java?

11. How to get all keys from hashtable in Java?


import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Set; public class HashtableDemo { public static void main(String args[]) { // Creating Hashtable for example Hashtable companies = new Hashtable(); // Java Hashtable example to put object into Hashtable // put(key, value) is used to insert object into map companies.put("Google", "United States"); companies.put("Nokia", "Finland"); companies.put("Sony", "Japan"); // Java Hashtable example to get Object from Hashtable // get(key) method is used to retrieve Objects from Hashtable companies.get("Google"); // Hashtable containsKey Example // Use containsKey(Object) method to check if an Object exits as key in // hashtable System.out.println("Does hashtable contains Google as key: " + companies.containsKey("Google")); // Hashtable containsValue Example // just like containsKey(), containsValue returns true if hashtable // contains specified object as value System.out.println("Does hashtable contains Japan as value: " + companies.containsValue("Japan")); // Hashtable enumeration Example // hashtabl.elements() return enumeration of all hashtable values Enumeration enumeration = companies.elements(); while (enumeration.hasMoreElements()) { System.out.println("hashtable values: " + enumeration.nextElement());

} // How to check if Hashtable is empty in Java // use isEmpty method of hashtable to check emptiness of hashtable in // Java System.out.println("Is companies hashtable empty: " + companies.isEmpty()); // How to find size of Hashtable in Java // use hashtable.size() method to find size of hashtable in Java System.out.println("Size of hashtable in Java: " + companies.size()); // How to get all values form hashtable in Java // you can use keySet() method to get a Set of all the keys of hashtable // in Java Set hashtableKeys = companies.keySet(); // you can also get enumeration of all keys by using method keys() Enumeration hashtableKeysEnum = companies.keys(); // How to get all keys from hashtable in Java // There are two ways to get all values form hashtalbe first by using // Enumeration and second getting values ad Collection Enumeration hashtableValuesEnum = companies.elements(); Collection hashtableValues = companies.values(); // Hashtable clear example // by using clear() we can reuse an existing hashtable, it clears all // mappings. companies.clear(); } } Output: Does hashtable contains Google as key: true Does hashtable contains Japan as value: true hashtable values: Finland hashtable values: United States hashtable values: Japan

Is companies hashtable empty: false Size of hashtable in Java: 3

Difference between HashSet and HashMap in Java


Following are some differences between HashMap and Hashset: Hash Map HashMap is a implementation of Map interface HashMap Stores data in form of key value pair Put method is used to add element in map In hash map hashcode value is calculated using key object Hash Set HashSet is an implementation of Set Interface HashSet Store only objects

Add method is used to add element is Set Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different. HashSet is slower than Hashmap

HashMap is faster than hashset because unique key is used to access object

Other Basic questions :1. What are the principle concepts of OOPS? There are four principle concepts upon which object oriented design and programming rest. They are: Abstraction Polymorphism Inheritance Encapsulation (i.e. easily remembered as A-PIE). 2.What is Abstraction? Abstraction refers to the act of representing essential features without including the background details or explanations. 3.What is Encapsulation? Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

4.What is the difference between abstraction and encapsulation? Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing its inside view, where the behavior of the abstraction is implemented. Abstraction solves the problem in the design side while Encapsulation is the Implementation. Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

5.What is Inheritance? Inheritance is the process by which objects of one class acquire the properties of objects of another class. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Inheritance is done by using the keyword extends. The two most common reasons to use inheritance are: o To promote code reuse o To use polymorphism

6.What is Polymorphism? Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts specifically, to allow an entity such as a variable, a function, or an object to have more than one form. 7.How does Java implement polymorphism? (Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name. In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

8.Explain the different forms of Polymorphism. There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface. Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java: Method overloading Method overriding through inheritance Method overriding through the Java interface

9.What is runtime polymorphism or dynamic method dispatch? In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. 10.What is Dynamic Binding? Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance. 11.What is method overloading? Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type. Note: Overloaded methods MUST change the argument list Overloaded methods CAN change the return type Overloaded methods CAN change the access modifier Overloaded methods CAN declare new or broader checked exceptions A method can be overloaded in the same class or in a subclass

12.What is method overriding? Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior thats specific to a particular subclass type. Note: The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You cant override a method marked public and make it protected). You cannot override a method marked final You cannot override a method marked static

13.What are the differences between method overloading and method overriding? Overloaded Method Arguments Return type Exceptions Access Must change Can change Can change Can change Overridden Method Must not change Cant change except for covariant returns Can reduce or eliminate. Must not throw new or broader checked exceptions Must not make more restrictive (can be less restrictive)

Invocation

Reference type determines which overloaded version is selected. Happens at compile time.

Object type determines which method is selected. Happens at runtime.

14.Can overloaded methods be override too? Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future. 15.Is it possible to override the main method? NO, because main is a static method. A static method can't be overridden in Java. 16.How to invoke a superclass version of an Overridden method? To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.

// From subclass super.overriddenMethod();


17.What is super? super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. Note: You can only go back one level. In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.

18.How do you prevent a method from being overridden? To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.

public final void exampleMethod() { // Method statements }


19.What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must have. Note: You cant mark an interface as final. Interface variables must be static. An Interface cannot extend anything but another interfaces.

20.Can we instantiate an interface? You cant instantiate an interface directly, but you can instantiate a class that implements an interface. 21.Can we create an object for an interface? Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it. 22.Do interfaces have member variables? Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example. 23.What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces. 24.What is a marker interface? Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializableinterface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized. 25.What is an abstract class? Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Note: If even a single method is abstract, the whole class must be declared abstract. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. You cant mark a class as both abstract and final.

26.Can we instantiate an abstract class? An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed). 27.What are the differences between Interface and Abstract class? Abstract Class An abstract class can provide Interfaces An interface cannot provide any code

complete, default code and/or just the details that have to be overridden. In case of abstract class, a class may extend only one abstract class. An abstract class can have nonabstract methods. An abstract class can have instance variables. An abstract class can have any visibility: public, private, protected. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. An abstract class can contain constructors . Abstract classes are fast.

at all,just the signature.

A Class may implement several interfaces. All methods of an Interface are abstract. An Interface cannot have instance variables. An Interface visibility must be public (or) none. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. An Interface cannot contain constructors . Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.

28.When should I use abstract classes and when should I use interfaces? Use Interfaces when You see that something in your design will change frequently. If various implementations only share method signatures then it is better to use Interfaces. you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.

Use Abstract Class when If various implementations are of the same kind and use common behavior or status then abstract class is better to use. When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.

29.When you declare a method as abstract, can other nonabstract methods access it? Yes, other nonabstract methods can access a method that you declare as abstract. 30.Can there be an abstract class with no abstract methods in it? Yes, there can be an abstract class without abstract methods. 31.What is Constructor?

A constructor is a special method whose task is to initialize the object of its class. It is special because its name is the same as the class name. They do not have return types, not even void and therefore they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Constructor is invoked whenever an object of its associated class is created.

32.How does the Java default constructor be provided? If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself. 33.Can constructor be inherited? No, constructor cannot be inherited, though a derived class can call the base class constructor. 34.What are the differences between Contructors and Methods? Constructors Purpose Modifiers Return Type Name Create an instance of a class Cannot be abstract, final, native, static, or synchronized No return type, not even void Same name as the class (first letter is capitalized by convention) -- usually a noun Methods Group Java statements Can be abstract, final, native, static, or synchronized void or a valid return type Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action Refers to an instance of the owning class. Cannot be used by static methods. Calls an overridden method in the parent class

this

Refers to another constructor in the same class. If used, it must be the first line of the constructor Calls the constructor of the parent class. If used, must be the first line of the constructor Constructors are not inherited

super

Inheritance

Methods are inherited

35.How are this() and super() used with constructors? Constructors use this to refer to another constructor in the same class with a different parameter list. Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

36.What are the differences between Class Methods and Instance Methods?

Class Methods

Instance Methods

Instance methods on the other hand require an instance of the class to Class methods are methods which are exist before they can be called, so an declared as static. The method can be instance of a class needs to be called without creating an instance of created by using the new keyword. the class Instance methods operate on specific instances of classes. Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.

Class methods are methods which are declared as static. The method can be Instance methods are not declared as called without creating an instance of static. the class. 37.How are this() and super() used with constructors? Constructors use this to refer to another constructor in the same class with a different parameter list. Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

38.What are Access Specifiers? One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers.. 39.What are Access Specifiers available in Java? Java offers four access specifiers, listed below in decreasing accessibility: Public- public classes, methods, and fields can be accessed from everywhere. Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package. Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. Situation Accessible to class from same package? Accessible to class
public protected

default yes no

private

yes yes

yes no, unless it is a

No No

from different package?

subclass

40.What is final modifier? The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method. final Classes- A final class cannot have subclasses. final Variables- A final variable cannot be changed once it is initialized. final Methods- A final method cannot be overridden by subclasses.

41.What are the uses of final method? There are two reasons for marking a method as final: Disallowing subclasses to change the meaning of the method. Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.

42.What is static block? Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute. 43.What are static variables? Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.

static type

varIdentifier;

where, the name of the variable is varIdentifier and its data type is specified by type. Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables. 44.What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. 45.What are static methods? Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class. Note:The use of a static method suffers from the following restrictions: A static method can only call other static methods. A static method must only access static data. A static method cannot reference to the current object using keywords super or this.

46.What is an Iterator ? The Iterator interface is used to step through the elements of a Collection. Iterators let you process each element of a Collection. Iterators are a generic way to go through all the elements of a Collection no matter how it is organized. Iterator is an Interface implemented a different way for every Collection.

47.How do you traverse through a collection using its Iterator? To use an iterator to traverse through the contents of a collection, follow these steps: Obtain an iterator to the start of the collection by calling the collections iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. Within the loop, obtain each element by calling next().

48.How do you remove elements during Iteration? Iterator also has a method remove() when remove is called, the current element in the iteration is deleted. 49.What is the difference between Enumeration and Iterator? Enumeration Enumeration doesn't have a remove() method Iterator Iterator has a remove() method

Enumeration acts as Read-only Can be abstract, final, native, static, interface, because it has the methods or synchronized only to traverse and fetch the objects Note: So Enumeration is used whenever we want to make Collection objects as Read-only. 50.How is ListIterator? ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element 51.What is the List interface? The List interface provides support for ordered collections of objects. Lists may contain duplicate elements.

52.What are the main implementations of the List interface ? The main implementations of the List interface are as follows : ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.

Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods." LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).

53.What are the advantages of ArrayList over arrays ? Some of the advantages ArrayList has over arrays are: It can grow dynamically It provides more powerful insertion and search mechanisms than arrays.

54.Difference between ArrayList and Vector ? ArrayList ArrayList is NOT synchronized by default. ArrayList can use only Iterator to access the elements. The ArrayList increases its array size by 50 percent if it runs out of room. ArrayList has no default size. Vector List is synchronized by default.

Vector

Vector list can use Iterator and Enumerati elements.

A Vector defaults to doubling the size of it While vector has a default size of 10.

55.How to obtain Array from an ArrayList ? Array can be obtained from an ArrayList using toArray() method on ArrayList.

List arrayList = new ArrayList(); arrayList.add( Object a[] = arrayList.toArray();

56.Why insertion and deletion in ArrayList is slow compared to LinkedList ? ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

57. Why are Iterators returned by ArrayList called Fail Fast ? Because, 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. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. 58.How do you decide when to use ArrayList and When to use LinkedList? If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation. What is the Set interface ?

The Set interface provides methods for accessing the elements of a finite mathematical set Sets do not allow duplicate elements Contains no methods other than those inherited from Collection It adds the restriction that duplicate elements are prohibited Two Set objects are equal if they contain the same elements

60.What are the main Implementations of the Set interface ? The main implementations of the List interface are as follows: HashSet TreeSet LinkedHashSet EnumSet

61.What is a HashSet ? A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance youll get). Use this class when you want a collection with no duplicates and you dont care about order when you iterate through it.

62.What is a TreeSet ? TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time. 63.What is an EnumSet ? An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created. 64.Difference between HashSet and TreeSet ?

HashSet HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order. We can add any type of elements to hash set.

TreeSet

TreeSet is under set i.e. it provides eleme order). We can add only similar types of elements to tree set.

65.What is a Map ?

A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot.

66.What are the main Implementations of the Map interface ? The main implementations of the List interface are as follows: HashMap HashTable TreeMap EnumMap

67.What is a TreeMap ? TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure. 68.How do you decide when to use HashMap and when to use TreeMap ? For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. 69.Difference between HashMap and Hashtable ? HashMap HashMap lets you have null values as well as one null key. The iterator in the HashMap is fail-safe (If you change the map while iterating, youll know). HashMap is unsynchronized. HashTable does not allows null values as The enumerator for the Hashtable is not f Hashtable is synchronized.

Hashtabl

Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.

70.How does a Hashtable internally maintain the key-value pairs? TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure. 71.What Are the different Collection Views That Maps Provide? Maps Provide Three Collection Views. Key Set - allow a map's contents to be viewed as a set of keys. Values Collection - allow a map's contents to be viewed as a set of values. Entry Set - allow a map's contents to be viewed as a set of key-value mappings.

72.What is a KeySet View ? KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map. 73.What is a Values Collection View ? Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map. 74.What is an EntrySet View ? Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value. 75.How do you sort an ArrayList (or any list) of user-defined objects ? Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator). 76.What is the Comparable interface ? The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered. The Comparable interface in the generic form is written as follows:

interface Comparable<T>
where T is the name of the type parameter. All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of thecompareTo() method is as follows:

int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative. If object1 > object2: The value of i returned will be positive. If object1 = object2: The value of i returned will be zero.

77.What are the differences between the Comparable and Comparator interfaces ?
Comparable It uses the compareTo() method. int objectOne.compareTo(objectTwo). It is necessary to modify the class whose instance is going to be sorted. Only one sort sequence can be created. It is frequently used by the API classes. It uses the compare() method. int compare(ObjOne, ObjTwo) A separate class can be created in order to sort the instances. Many sort sequences can be created. It used by third-party classes to sort instances. Comparator

InterviewQuestions
Java Threads,Collections,Jsp,Spring,Hibernate

Java

JSP

Tutorials

Interview Questions

Java Keywords Key Concepts OOPS in java Java Collections#1 Java Collections #2 Exceptions #1

Exceptions #2 Threads#1 Threads#2 InnerClass Serialization Immutable Class Cloning in Java Garbage Collection JSP #1 JSP #2 Programming Q#1 Programming Q#2 Programming Q#3

Garbage Collections Interview Questions


Q1) Which part of the memory is involved in Garbage Collection? Stack or Heap? Ans) Heap

Q2)What is responsiblity of Garbage Collector? Ans) Garbage collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects. It ensures that the available memory will be used efficiently, but does not guarantee that there will

be sufficient memory for the program to run.

Q3) Is garbage collector a dameon thread? Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM. The thread stops when all non-dameon threads stop.

Q4)Garbage Collector is controlled by whom? Ans) The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low, but this behavior of jvm can not be guaranteed. One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by jvm.

Q5) When does an object become eligible for garbage collection? Ans) An object becomes eligible for Garbage Collection when no live thread can access it.

Q6) What are the different ways to make an object eligible for Garbage Collection when it is no longer needed?
Ans)

1. Set all available object references to null once the purpose of creating the object is served :
public class GarbageCollnTest1 { public static void main (String [] args){ String str = "Set the object ref to null"; //String object referenced by variable str is not eligible for GC yet str = null; /*String object referenced by variable str becomes eligible for GC */ } }

2. Make the reference variable to refer to another object : Decouple the reference variable from the object and set it refer to another object, so the object which it was referring to before reassigning is eligible for Garbage Collection.

publc class GarbageCollnTest2 { public static void main(String [] args){ String str1 = "Garbage collected after use"; String str2 = "Another String"; System.out.println(str1); //String object referred by str1 is not eligible for GC yet str1 = str2; /* Now the str1 variable referes to the String object "Another String" and the object "Garbage collected after use" is not referred by any variable and hence is eligible for GC */

} }

3) Creating Islands of Isolation : If you have two instance reference variables which are referring to the instances of the same class, and these two reference variables refer to each other and the objects referred by these reference variables do not have any other valid reference then these two objects are said to form an Island of Isolation and are eligible for Garbage Collection.

public class GCTest3 { GCTest3 g; public static void main(String [] str){ GCTest3 gc1 = new GCTest3(); GCTest3 gc2 = new GCTest3(); gc1.g = gc2; //gc1 refers to gc2 gc2.g = gc1; //gc2 refers to gc1 gc1 = null; gc2 = null; //gc1 and gc2 refer to each other and have no other valid //references //gc1 and gc2 form Island of Isolation //gc1 and gc2 are eligible for Garbage collection here } }

Q7) Can the Garbage Collection be forced by any means? Ans) No. The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.

Q8) How can the Garbage Collection be requested? Ans) There are two ways in which we can request the jvm to execute the Garbage Collection.

1) The methods to perform the garbage collections are present in the Runtime class provided by java. The Runtime class is a Singleton for each java main program. The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked using this instance of Runtime to request the garbage collection. 2) Call the System class System.gc() method which will request the jvm to perform GC.

Q9) What is the purpose of overriding finalize() method? Ans) The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

Q10) If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some point the same object becomes eligible for Garbage collection, will the finalize() method be called again? Ans) No

Q11) How many times does the garbage collector calls the finalize() method for an object? Ans) Only once.

Q12) What happens if an uncaught exception is thrown from during the execution of the finalize() method of an object? Ans) The exception will be ignored and the garbage collection (finalization) of that object terminates.

Q13) What are different ways to call garbage collector? Ans) Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().

Q14) How to enable/disable call of finalize() method of exit of the application Ans) Runtime.getRuntime().runFinalizersOnExit(boolean value) . Passing the boolean value will either disable or enable the finalize() call.

Das könnte Ihnen auch gefallen