java interview questions part-1

19

Upload: mindsmapped-consulting

Post on 20-Feb-2017

374 views

Category:

Technology


2 download

TRANSCRIPT

Page 1: Java Interview Questions Part-1

JAVA Interview Questions Part-1

JAVA J2EE Training

Page 2: Java Interview Questions Part-1

1) What is the difference between a JDK and a JVM?JDK is Java Development Kit which is for development purpose and itincludes execution environment also but JVM is purely a run timeenvironment and hence you will not be able to compile source using JVM.

2) Which are the different segments of memory JVM uses?a. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap).b. Heap Segment - contains all created objects in runtime, objects only plustheir object attributes (instance variables).c. Code Segment - The segment where the actual compiled Java byte codesresides when loaded.

3) What is Java bytecode?Java bytecode is the instruction set of the Java virtual machine. Eachbytecode is composed by one, or two bytes that represent the instruction,along with zero or more bytes for passing parameters.

Page 3: Java Interview Questions Part-1

4) What is the base class of all classes?Java.lang.object

5) What is a pointer? Does Java support pointers?Pointer means a reference handle to a memory location. Java doesn't supportthe use of pointers as their improper handling causes memory leaks andcompromises the reliability.

6) Does java supports multiple inheritance?Java doesn’t support multiple inheritance.

7) What is the difference between path and class path?Path and Class Path are operating system level environment variables. Pathis used define where the system can find executables (.exe) files and classpath is used to specify the location .class files.

Page 4: Java Interview Questions Part-1

8) What is difference between abstract class and interface?A class is called abstract when it contains at least one abstract method. It canalso contain n numbers of concrete method. Interface can contain onlyabstract (non implemented) methods.The abstract class can have public, private, protect or default variables andalso constants. In interface the variable is by default public final. In nutshellthe interface doesn’t have any variables it only has constants.A class can extend only one abstract class but a class can implementmultiple interfaces.If an interface is implemented its compulsory to implement all of itsmethods but if an abstract class is extended its not compulsory to implementall methods.The problem with an interface is, if you want to add a new feature (method)in its contract, then you MUST implement those methods in all of the classeswhich implement that interface. However, in the case of an abstract class,the method can be simply implemented in the abstract class and the samecan be called by its subclass.

Page 5: Java Interview Questions Part-1

9) What is the difference between StringBuffer and String class?A string buffer implements a mutable sequence of characters. A string bufferis like a String, but can be modified. At any point in time it contains someparticular sequence of characters, but the length and content of the sequencecan be changed through certain method calls.The String class represents character strings. All string literals in Javaprograms, such as "abc" are constant and implemented as instances of thisclass; their values cannot be changed after they are created.

10) Can static method access instance variables?Though Static methods cannot access the instance variables directly, theycan access them using instance handler.

11) Difference between implicit and explicit type casting?An explicit conversion is where you use some syntax to tell the program todo a conversion whereas in case of implicit type casting you need notprovide the target data type explicitly.

Page 6: Java Interview Questions Part-1

12) What is the difference between final, finally andfinalize()?finalIt is a modifier which can be applied to a class, method or variable. Itis not possible to inherit the final class, override the final methodand change the final variable.finallyIt is an exception handling code section. It gets executed whether anexception is raised or not by the try block code segment.finalize()It is a method of Object class.It is executed by the JVM just before garbage collecting object to give afinal chance for resource releasing activity.

13) Difference between Abstract and Concrete Class?Abstract classes are only meant to be sub classed and not meant to beinstantiated whereas concrete classes are meant to be instantiated.

Page 7: Java Interview Questions Part-1

14) Difference between Public, Private, Default andProtected?Private: Not accessible outside object scope.Public: Accessible from anywhere.Default: Accessible from anywhere within same package.Protected: Accessible from object and the sub class objects.

15) Explain Autoboxing?Autoboxing is the automatic conversion that the Java compiler makesbetween the primitive types and their corresponding object wrapper classes.

16) When do you get ClassCastException?As we downcast objects, The ClassCastException is thrown in case code hasattempted to cast an object to a subclass of which it is not an instance.

Page 8: Java Interview Questions Part-1

17) Does garbage collection guarantee that a program will notrun out of memory?Garbage collection does not guarantee that a program will not run out ofmemory. It is possible for programs to use up memory resources faster thanthey are garbage collected. It is also possible for programs to create objectsthat are not subject to garbage collection

18) What is a daemon thread? Give an Example?These are threads that normally run at a low priority and provide a basicservice to a program or programs when activity on a machine is reduced.Garbage collector thread is daemon thread.

19) Can a null element be added to a TreeSet or HashSet?A null element can be added only if the set contains is on size 1 becausewhen a second element is added then as per set definition a check is made tocheck duplicate value and comparison with null element will throwNullPointerException. HashSet is based on HashMap and can contain nullelement.

Page 9: Java Interview Questions Part-1

20) What is the difference between collections class vscollections interface?Collections class is a utility class having static methods for doing operationson objects of classes which implement the Collection interface. Forexample, Collections has methods for finding the max element in aCollection.

21) What is comparator interface used for?The purpose of comparator interface is to compare objects of the same classto identify the sorting order. Sorted Collection Classes (TreeSet, TreeMap)have been designed such to look for this method to identify the sorting order,that is why class need to implement Comparator interface to qualify itsobjects to be part of Sorted Collections.

22) Can we add heterogeneous elements into TreeMap?No, Sorted collections don't allow addition of heterogeneous elements asthey are not comparable.

Page 10: Java Interview Questions Part-1

23) What is the difference between an Inner Class and a Sub-Class?An Inner class is a class which is nested within another class. An Inner classhas access rights for the class which is nesting it and it can access allvariables and methods defined in the outer class.A sub-class is a class which inherits from another class called super class.Sub-class can access all public and protected methods and fields of its superclass.24) What is data encapsulation and what’s its significance?Encapsulation is a concept in Object Oriented Programming for combiningproperties and methods in a single unit.Encapsulation helps programmers to follow a modular approach for softwaredevelopment as each object has its own set of methods and variables andserves its functions independent of other objects. Encapsulation also servesdata hiding purpose.25) What is the difference between continue and breakstatement?break and continue are two important keywords used in Loops. When abreak keyword is used in a loop, loop is broken instantly while whencontinue keyword is used, current iteration is broken and loop continueswith next iteration.

Page 11: Java Interview Questions Part-1

26) Which types of exceptions are caught at compile time?Checked exceptions can be caught at the time of program compilation.Checked exceptions must be handled by using try catch block in the code inorder to successfully compile the code.

27) Can we use a default constructor of a class even if anexplicit constructor is defined?Java provides a default no argument constructor if no explicit constructor isdefined in a Java class. But if an explicit constructor has been defined,default constructor can’t be invoked and developer can use only thoseconstructors which are defined in the class.

Page 12: Java Interview Questions Part-1

28) Can we override a method by using same method nameand arguments but different return types?The basic condition of method overriding is that method name, arguments aswell as return type must he exactly same as is that of the method beingoverridden. Hence using a different return type doesn’t override a method.

29) How destructors are defined in Java?In Java, there are no destructors defined in the class as there is no need to doso. Java has its own garbage collection mechanism which does the jobautomatically by destroying the objects when no longer referenced.

30) How objects are stored in Java?In java, each object when created gets a memory space from a heap. Whenan object is destroyed by a garbage collector, the space allocated to it fromthe heap is re-allocated to the heap and becomes available for any newobjects.

Page 13: Java Interview Questions Part-1

31) What is the order of call of constructors in inheritance?In case of inheritance, when a new object of a derived class is created, firstthe constructor of the super class is invoked and then the constructor of thederived class is invoked.

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

Page 14: Java Interview Questions Part-1

33) What is difference between Enumeration and Iteratorinterface?Enumeration is twice as fast as Iterator and uses very less memory.Enumeration is very basic and fits to basic needs. But Iterator is much saferas compared to Enumeration because it always denies other threads tomodify the collection object which is being iterated by it.Iterator takes the place of Enumeration in the Java Collections Framework.Iterators allow the caller to remove elements from the underlying collectionthat is not possible with Enumeration. Iterator method names have beenimproved to make it’s functionality clear.

34) What is difference between Comparable and Comparatorinterface?Comparable and Comparator interfaces are used to sort collection or array ofobjects.Comparable interface is used to provide the natural sorting of objects and wecan use it to provide sorting based on single logic.Comparator interface is used to provide different algorithms for sorting andwe can choose the comparator we want to use to sort the given collection ofobjects.

Page 15: Java Interview Questions Part-1

35) Difference between throw and throws?throw is used to explicitly throw an exception especially custom exceptions,whereas throws is used to declare that the method can throw an exception.We cannot throw multiple exceptions using throw statement but we candeclare that a method can throw multiple exceptions using throws andcomma separator.

36) What are the disadvantages of using arrays?Arrays are of fixed size and have to reserve memory prior to use. Hence ifwe don't know size in advance arrays are not recommended to use.Arrays can store only homogeneous elements.Arrays store its values in contentious memory location. Not suitable if thecontent is too large and needs to be distributed in memory.There is no underlying data structure for arrays and no ready made methodsupport for arrays, for every requirement we need to code explicitly.

Page 16: Java Interview Questions Part-1

37) How substring() method of String class create memoryleaks?Substring method would build a new String object keeping a reference to thewhole char array, to avoid copying it. Hence you can inadvertently keep areference to a very big character array with just a one character string.

38) What is the difference between yield() and sleep()?When a object invokes yield() it returns to ready state. But when an objectinvokes sleep() method enters to not ready state.

39) Why threads block or enter to waiting state on I/O?Threads enters to waiting state or block on I/O because other threads canexecute while the I/O operations are performed.

40) What is the difference between System.out ,System.errand System.in?System.out and System.err both represent the monitor by default and hencecan be used to send data or results to the monitor. But System.out is used todisplay normal messages and results whereas System.err is used to displayerror messages and System.in represents InputStream object, which bydefault represents standard input device, i.e., keyboard.

Page 17: Java Interview Questions Part-1

41) Why Char array is preferred over String for storingpassword?String is immutable in java and stored in String pool. Once it’s created itstays in the pool until unless garbage collected, so even though we are donewith password it’s available in memory for longer duration and there is noway to avoid it. It’s a security risk because anyone having access to memorydump can find the password as clear text.

42) Why String is popular HashMap key in Java?Since String is immutable, its hashcode is cached at the time of creation andit doesn’t need to be calculated again. This makes it a great candidate for keyin a Map and it’s processing is fast than other HashMap key objects. This iswhy String is mostly used Object as HashMap keys.

43) Difference between Checked and Unchecked exceptions ?Checked exceptions and the exceptions for which compiler throws an errorsif they are not checked whereas unchecked exceptions and caught during runtime only and hence can't be checked.

Page 18: Java Interview Questions Part-1

44) Does Constructor creates the object?New operator in Java creates objects. Constructor is the later step in objectcreation. Constructor's job is to initialize the members after the object hasreserved memory for itself.

45) Can constructors be synchronized in Java ?No. Java doesn't allow multi thread access to object constructors sosynchronization is not even needed.

46) Difference between Array List and Linked List ?Linked List and Array List are two different implementations of the Listinterface. Linked List implements it with a doubly-linked list. Array Listimplements it with a dynamically resizing array.

47) How can we create objects if we make the constructorprivate?We can do so through a static public member method or static block.

Page 19: Java Interview Questions Part-1

48) Similarity and Difference between static block and staticmethod ?Both belong to the class as a whole and not to the individual objects. Staticmethods are explicitly called for execution whereas Static block getsexecuted when the Class gets loaded by the JVM.

49) What restrictions are placed on method overriding?Overridden methods must have the same name, argument list, and returntype. The overriding method may not limit the access of the method itoverrides. The overriding method may not throw any exceptions that maynot be thrown by the overridden method.

50) Difference Between this() and super() ?1. this is a reference to the current object in which this keyword is usedwhereas super is a reference used to access members specific to the parentClass.2. this is primarily used for accessing member variables if local variableshave same name, for constructor chaining and for passing itself to somemethod whereas super is primarily used to initialize base class memberswithin derived class constructor.