Advanced Java Interview Questions - 10

Advanced Java Interview Questions - 10

1 What is difference in String on C and Java

If you have mentioned C in your resume, then you are likely to face this String interview question. Well C String and Java String are completely different to each other, C String is a null terminated character array while String in Java is an Object. Also String is more feature rich in Java than C.

2 Why char array is better than String for storing password?

This String interview question is debatable and you might not agree with interviewer but this is also a chance to show that how deep and differently you can think of. One of the reason which people give Why you should store password in char array over String is related to immutability, since its not possible to remove erase contents of String but you can erase contents of char array. See Why char array preferred over String for password for complete discussion.

3 How do you compare two String in Java ?

This is another common String interview question which appears on fresher level interviews. There are multiple ways to compare two String like equals() method, equalsIgnoreCase() etc, You can also see 4 ways to compare String in Java for more examples. Main thing which interviewer checks is that whether candidate mentioned equality operator or not "==", comparing String with equality operator is common mistake which works in some case and doesn't work in other. next String interview question is follow-up up of this.

4 Can we compare String using == operator? What is risk?

As discussed in previous String question, You can compare String using equality operator but that is not suggested or advised because equality operator is used to compare primitives and equals() method should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality operator can cause subtle issue while comparing primitive to Object, any way String is free from that issue because it doesn't have corresponding primitive type and not participate in autoboxing. Almost all the time comparing String means comparing contents of String i.e. characters and equals() method is used to perform character based comparison. equals() return true if two String points to same object or two String has same contents while == operator returns true if two String object points to same object but return false if two different String object contains same contents. That explains why sometime it works and sometime it doesn't. In short always use equals method in Java to check equality of two String object.

5 What is String in Java ? Is String is data type?

String in Java is not a primitive data type like int, long or double.  String is a class or in more simple term a user defined type. This is confusing for some one who comes from C background. String is defined in java.lang package and wrappers its content in a character array. String provides equals() method to compare two String and provides various other method to operate on String like toUpperCase() to convert String into upper case, replace() to replace String contents, substring() to get substring, split() to split long String into multiple String.

6  Why String is final in Java

String is final by design in Java, some of the points which makes sense why String is final is Security, optimization and to maintain pool of String in Java. for details on each of this point see Why String is final in Java.

7  What is Difference between String and StringBuffer in Java

This is probably the most common question on String I have seen in Java interviews. Though String and Stringbuffer are two different class they are used in context of concatenating two Strings, Since String is immutable in Java every operation which changes String produces new String, which can be avoided by using Stringbuffer. See String vs StringBuffer  for more details.

8 How substring method work in Java

This is one of the tricky Java question relate to String and until you are familiar with internals of String class, its difficult to answer. Substring shares same character array as original String which can create memory leak if original String is quite big and not required to retain in memory but unintentionally retained by substring which is very small in size and prevents large array from begin claimed during Garbage collection in Java. See How Substring works in Java for more details.

9 Does String is thread-safe in Java

If you are familiar with the concept of immutability and thread-safety you can easily answer this String interview question in Java. Since String is immutable, it is thread-safe and it can be shared between multiple thread without external synchronization.

That's all on Java String interview question. In Summary there are lot of specifics about String which needs to be know for any one who has started Java programming and these String question will not just help to perform better on Java Interviews but also opens new door of learning about String. I didn't know many String related concepts until I come across these question which motivated to research and learn more about String in Java.

10 What is String pool in Java

Another tough Java question asked in  String interview. String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like "abc". When Java program creates a new String using String literal, JVM checks for that String in pool and if String literal is already present in pool than same object is returned instead of creating a whole new object. String pool check is only performed when you create String as literal, if you create String using new() operator, a new String object will be created even if String with same content is available in pool.

11 What does intern() method do in Java

As discussed in previous String interview question, String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool.

12 Variables is an identifier that denotes a storage location used to store a data values.unlike constants that remain unchanged during the execution of a program, a variable may takes different values at different times during the execution of the program.

Instance variables
Class variables
Local variable
Parameters

13 Does String is thread-safe in Java

If you are familiar with the concept of immutability and thread-safety you can easily answer this String interview question in Java. Since String is immutable, it is thread-safe and it can be shared between multiple thread without external synchronization.

14  How substring method work in Java

This is one of the tricky Java question relate to String and until you are familiar with internals of String class, its difficult to answer. Substring shares same character array as original String which can create memory leak if original String is quite big and not required to retain in memory but unintentionally retained by substring which is very small in size and prevents large array from begin claimed during Garbage collection in Java. See How Substring works in Java for more details.

15 How do you compare two String in Java ?

This is another common String interview question which appears on fresher level interviews. There are multiple ways to compare two String like equals() method, equalsIgnoreCase() etc, You can also see 4 ways to compare String in Java for more examples. Main thing which interviewer checks is that whether candidate mentioned equality operator or not "==", comparing String with equality operator is common mistake which works in some case and doesn't work in other. next String interview question is follow-up up of this.

16 Why char array is better than String for storing password?

This String interview question is debatable and you might not agree with interviewer but this is also a chance to show that how deep and differently you can think of. One of the reason which people give Why you should store password in char array over String is related to immutability, since its not possible to remove erase contents of String but you can erase contents of char array. See Why char array preferred over String for password for complete discussion.

17  Why String is final in Java

String is final by design in Java, some of the points which makes sense why String is final is Security, optimization and to maintain pool of String in Java. for details on each of this point see Why String is final in Java.

18 What is difference in String on C and Java

If you have mentioned C in your resume, then you are likely to face this String interview question. Well C String and Java String are completely different to each other, C String is a null terminated character array while String in Java is an Object. Also String is more feature rich in Java than C.

19 What does intern() method do in Java

As discussed in previous String interview question, String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool.

20 What is String in Java ? Is String is data type?

String in Java is not a primitive data type like int, long or double.  String is a class or in more simple term a user defined type. This is confusing for some one who comes from C background. String is defined in java.lang package and wrappers its content in a character array. String provides equals() method to compare two String and provides various other method to operate on String like toUpperCase() to convert String into upper case, replace() to replace String contents, substring() to get substring, split() to split long String into multiple String.

21 What is String pool in Java

Another tough Java question asked in  String interview. String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like "abc". When Java program creates a new String using String literal, JVM checks for that String in pool and if String literal is already present in pool than same object is returned instead of creating a whole new object. String pool check is only performed when you create String as literal, if you create String using new() operator, a new String object will be created even if String with same content is available in pool.


22 Can we compare String using == operator? What is risk?

As discussed in previous String question, You can compare String using equality operator but that is not suggested or advised because equality operator is used to compare primitives and equals() method should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality operator can cause subtle issue while comparing primitive to Object, any way String is free from that issue because it doesn't have corresponding primitive type and not participate in autoboxing. Almost all the time comparing String means comparing contents of String i.e. characters and equals() method is used to perform character based comparison. equals() return true if two String points to same object or two String has same contents while == operator returns true if two String object points to same object but return false if two different String object contains same contents. That explains why sometime it works and sometime it doesn't. In short always use equals method in Java to check equality of two String object.

23 What is Difference between String and StringBuffer in Java

This is probably the most common question on String I have seen in Java interviews. Though String and Stringbuffer are two different class they are used in context of concatenating two Strings, Since String is immutable in Java every operation which changes String produces new String, which can be avoided by using Stringbuffer. See String vs StringBuffer  for more details.

24 What is the difference between java and c++?

Java is a true object - oriented language while c++ is basically c with object-oriented extension.
C++ supports multiple inheritence but Java provides interfaces in case of multiple inheritence.
Java does not support operator overloading.
Java does not have template classes as in c++.
java does not use pointers.

25 What is Byte Code?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

26 What are wrapped classes?

Wrapped classes are classes that allow primitive types to be accessed as objects.

27 what is a package?

A package is a namespace that organizes a set of related classes and interfaces.The classes contained in the packages of other programs can be easily reused.Packages, classes can be unique compared with classes in other packages.That is, two classes in two different packages can have the same name.

28 What is an instanceof operator?

Instanceof is an object reference operator and returns true if the object on the left-hand side is an instance of the glass given to the right hand side.This operator allows to determine whether the object belongs to a particular class or not.

29 What are wrapper classes?

primitive data types may be converted into object types by using the wrapper classes contained in the java.lang package.
Exampes : int, float, long, char, double

30 What is a user defined exception?

User defined exceptions may be implemented by defining a new exception class by extending the Exception class.

31 What is the difference between an instance variable and a static variable?

Class variables are called static variables. There is only one occurrence of a class variable per JVM per class loader.When a class is loaded the class variables are initialized.
Instance variables are non-static and there is one occurrence of an instance variable in each class instance.Also known as a member variable or a field.

32 What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

33 What do you mean by polymorphism?

Polymorphism means the ability to take more than one form. fro example, an operation may exhibit behaviour in different instances. The behaviour depends upon the types of data used in the operatiom.

34 What is type casting?

Type casting means treating a variable of one type as though it is another type.
Examples :
int m = 5;
byte n =i;

35 What is the base class of all classes?

java.lang.Object

36 Where and how can you use a private constructor?

Private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.The instantiation is done by a public static method (i.e. a static factory method) within the same class.

37 Why do threads block on I/O?

Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.

38 Describe life cycle of thread?

A thread is similiar to a program that has a single flow of control.A thread is a execution in a program. The life cycle of threads are
Newborn state
Runnable state
Running state
Blocked state
Dead state

39 What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

40 How is final different from finally and finalize()?

Final - constant declaration.
The finally block always executes when the try block exits, except System.exit(0) call.
finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

41 What is Locale?

A Locale object represents a specific geographical, political, or cultural region.

42 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.

43 What if the main method is declared as private?

When a method is declared as private, the program compiles properly but it will give runtime error Main method not “public„.

44 When is a method said to be overloaded and when is a method said to be overridden?

Overloading deals with multiple methods in the same class with the same name but different method signatures.
Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures.

45 What are runtime exceptions?

Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

46 What is the Vector class?

The Vector class provides the capability to implement a growable array of objects.

47 What is the difference between method overriding and overloading?

Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.

48 What is the difference between a while statement and a do while statement?

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do whilestatement will always execute the body of a loop at least once.

49 What is the difference between a break statement and a continue statement?

Break statement results in the termination of the statement to which it applies (switch, for, do, or while).
A Continue statement is used to end the current loop iteration and return control to the loop statement.

50 What is the List interface?

The List interface provides support for ordered collections of objects.

51 What is an Applets?

Applets are small java programs that are primarily used in Internet computing. They can be transported over the internet from one computer to another and run using the Applet Viewer or any web browser that supports java.

52 What is the difference between error and an exception?

Exception means When a method encounters an abnormal condition (an exception condition) that it can’t handle itself, it may throw an exception.
ssError mens system doesn’t handle.For example:Overflow,Out of memory.

53 What is the difference between constructors and normal methods?

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.

54 What is the difference between an if statement and a switch statement?

The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.s

55 What type of parameter passing does Java support?

In Java the arguments are always passed by value.

56 What is the difference between an interface and an abstract class?

An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

57 What is the difference between an abstract class and an interface?

Abstract class Interface - Have executable methods and abstract methods.Can only subclass one abstract class
Interface - Have no implementation code. All methods are abstract.A class can implement any number of interfaces.

58 What is the importance of static variable?

static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

59 What is singleton?

It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class.

60  Which one would you prefer and why?

The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice. Also note how the threads are started in each of the different cases as shown in the code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior. By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter is an object of type Base and will run as a thread.

61 Why is locking of a method or block of code for thread safety is called "synchronized" and not "lock" or "locked"?

When a method or block of code is locked with the reserved "synchronized" key word in Java, the memory (i.e. heap) where the shared data is kept is synchronized. This means,

When a synchronized block or method is entered after the lock has been acquired by a thread, it first reads any changes to the locked object from the main heap memory to ensure that the thread that has the lock has the current info before start executing.After the synchronized  block has completed and the thread is ready to relinquish the lock, all the changes that were made to the object that was locked is written or flushed back to the main heap memory so that the other threads that acquire the lock next has the current info.

This is why it is called "synchronized" and not "locked". This is also the reason why the immutable objects are inherently thread-safe and does not require any synchronization. Once created, the immutable objects cannot be modified.

62 Why String is immutable in java?

Three reasons:
1) String pool requires string to be immutable otherwise shared reference can be changed from anywhere.
2) security because string is shared on different area like file system, networking connection, database connection , having immutable string allows you to be secure and safe because no one can change reference of string once it gets created. if string had been mutable anyone can surpass the security be logging in someone else name and then later modifying file belongs to other.

63 Explain race condition in Java hashmap ?

Race conditions in Java are always tricky to find and solve. Not many people know about it that hashmap could run into race condition if it would be modified by two threads simultaneous and one thread tries to re-siz or rehash the map because of capacity crossing threshold value. Since hashmap maintains a linked list of element in bucket and while copying from one hashmap to other or old to new order of linked list got reversed, which could result in infinite loop if two threads are doing resizing at same time?
Otherwise some set e.g. TreeSet and TreeMap which uses compareTo will not able to detect duplicates and allow duplicate inside set.

64 Difference between noclassdeffounderror and classnotfoundexception?

As per my experience java.lang.NoClassDefFoundError occurs when a particular class was present during Compile time but not available during run time by any reason, while java.lang.ClassNotFoundException comes when class loaded explicitly during runtime.

65 How to detect deadlock and fix it?

when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock check here for detailed answer

66 Can we call static method with null object?

I bet this is the most tricky Java interview question I ever encountered. Yes we can call because static method is bound at compile time and only type of variable is used for static binding not the value of object. It’s not a good practice to call static method by instance, always call static method in Java by using class name like Math.max()

67 How to detect memory leak in Java.

This is the most tricky Java interview question, there is no sure sort answer but you can use profile and memory dump to find memory leak in Java. JConsole can also help to provide graph of memory usage which can show pattern for memory leak.

68 When a singleton is not singleton in Java?

Many cases like Serialization, RMI, Clasloader loading multiple instance etc.

69  How does volatile variable works in Java?

Another seriously senior developer question in Java and tricky part of this question is change in volatile variable in Java 5. Though volatile is just a keyword its probably most confusing one in core Java. Volatile guarantee not just limited to the variable but also all the variables two threads see known as “happens before” relationship. Another important aspect of making a variable volatile is that compiler will not reorder the variable when switching from client to server configuration or while performing optimization. Read What is volatile variable in Java and How it works for detailed information on volatile variable in Java

70 Why multiple inheritances are not supported in Java?

Short answer is because of diamond pattern, diamond pattern creates ambiguity and make problem for compiler. Anyway java supports multiple inheritances via interfaces.I think more convincing reason for not supporting multiple inheritance is complexity involved in constructor chaining, casting etc rather than diamond problem

71 Why equals() method must be compatible with compareTo in java ?

compareTo method in Java must be compatible with equals method in Java i.e. if two objects are equal via equals method compareTo method must return “0? for them, failing this may result in some subtle bug when you store those objects in collection class like arraylist in java.  check here for detailed answer

72 What is difference between HashMap and ConcurrentHashMap in Java?

This is rather simple concurrency interview question. HashMap is not thread-safe while ConcurrentHashMap is a thread-safe class and can be used as an alternative of hashtable in Java.

73 What is difference between CopyOnWriteArrayList and ArrayList in Java?

This Java concurrency interview questions is again based on Collection and similar to earlier question difference between HashMap and ConcurrentHashMap, like HashMap, ArrayList are not thread safe and CopyOnWriteArrayList is a thread-safe Concurrent Collection and can be used as an alternative of Vector class in Java.
7) What is Thread Pool ? Why should you use Thread Pool in Java?
8) What is difference between submit() and execute() in Java?
9) What is difference between Executor and Executors in Java?
10) What is BlockingQueue in Java? How it is difference to Other collection classes in Java.

74 What is difference between CountDownLatch and CyclicBarrier in Java?

This is the most popular concurrency Questions, almost always appear in Java concurrency and threading interviews. main difference between CountDownLatch and CyclicBarrier is that, you cannot reuse CountDownLatch but you can reuse CyclicBarrier once its finished and barrier is broken. this is in fact a tricky concurrency question because Java programmer some time confuse between CountDownLatch and CyclicBarrier.

75  What is difference between ReadWriteLock and ReentrantLock in Java?

Both are Lock implementation, I guess ReadWriteLock provides two separate locks for reading and writing operation which can effectively used to increase concurrency level just like Java did with ConcurrentHashMap. You can also check google for answer of this Java concurrency question.

76 What is difference between fail-fast and fail-safe iterator in Java?

One of my favorite Java concurrency interview question which is related to Collection classes. Fail-fast Iterators are those which fails by throwing ConcurrentModificationException once they detect any structural change in Iterator once iteration begins. while fail-safe Iterator doesn't throw ConcurrentModificationException. See fail-safe vs fail-fast Iterator in Java for more details.

77 What is ReentrantLock ? What is advantage of using Lock API in Java?
This is another advanced Concurrency Questions for java programmer. Reentrant lock is an implementation of Lock interface which is an alternative of synchronized keyword in Java.

78  How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

79  What is the Vector class?

The Vector class provides the capability to implement a growable array of objects

80  What modifiers may be used with an inner class that is a member of an outer class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

81  Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing.

82  Is sizeof a keyword?

The sizeof operator is not a keyword.

83 What method is used to specify a container’s layout?

The setLayout() method is used to specify a container’s layout.

84 Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.

85  What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

86 Why do threads block on I/O?

Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

87 How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

88  What is the List interface?

The List interface provides support for ordered collections of objects.

89 What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

90 Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object..

91  What is a transient variable?

A transient variable is a variable that may not be serialized.

92 Which containers use a border Layout as their default layout?

The Window, Frame and Dialog classes use a border layout as their default layout.

93 What’s new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

94 Is null a keyword?

The null is not a keyword.

95 What is the preferred size of a component?

The preferred size of a component is the minimum component size that will allow the component to display normally.

96 Which method of the Component class is used to set the position and size of a component?

setBounds() method is used to set the position and size of a component.

97 What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep()method, it returns to the waiting state.

98  What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection.

99  Which characters may be used as the second character of an identifier, but not as the first character of an identifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

100 What is the difference between the >> and >>> operators?

The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

101  What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

102 What does intern() method do in Java

As discussed in previous String interview question, String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool.

------------------------------------
Also Read:
Advanced Java Interview Questions -1

Advanced Java Interview Questions -2

Advanced Java Interview Questions -3

Advanced Java Interview Questions -4

Advanced Java Interview Questions -5

Advanced Java Interview Questions -6

Advanced Java Interview Questions -7

Advanced Java Interview Questions -8

Advanced Java Interview Questions -9

Advanced Java Interview Questions -10

Advanced Java Interview Questions -11

Advanced Java Interview Questions -12

Advanced Java Interview Questions -13

Advanced Java Interview Questions -14        

0 comments:

Post a Comment