MainMenu

Home Java Overview Maven Tutorials

Core Java Interview question and answer for beginner

Core java Interview questions


1.Question : What is java ?
Answer: Java is developed by Sun MicroSystem in 1995 and it is a High level programming language.
2.Question : What are the main 5 features of java ?
Answer: Main features of java are :
Object oriented, Plateform independent, Robust, Interpreted & Multi-threaded.

3.Question : What is the difference between JDK, JRE & JVM ?
Answer: JVM : JVM stands for Java Virtual machine, it is an abstract machine which provides runtime environment where java bytecode can be executed.
JRE :JRE stands for java run time environment & it is a bunddle of software tools for developement, It combines the Java Virtual Machine , plateform core classes and supporting libraries.
JDK :JDK stands for Java development kit, it is a software development environment used for developing java applications and applets.

4.Question : Why java is plateform inependent?
Answer: Plateform Independent means writing code in one operation syatem(like windows) and running it in some other OS like(linux).
Also known as WORA - Write once and run anywhere.
Java Source code is complied by JavaC compiler and then JavaC compiler convert this source code to Bytecode
this bytecode send to the JVM & Jvm have java interpreter and JIT compiler inside, now this is converted in .obj file & this is easily to any operation system.

5.Question : What are the Objects, class & method in java?
Answer: Click the link for Answer Java Object , Class and Method

6.Question : What is constructor in java?
Answer: click the link for Answer Constructor

7.Question : Default value of bytedata type?
Answer: Default value of byte datatype is 0.

8.Question : What is static variable?
Answer: Class variable also known as static variable are declared with the static keyword in a class, but outside a method constructor or a block.

9.Question : What are difference access modifier in java ?
Answer: click the link for Answer Access Specifier

10.Question : Why String Class is immutable?
Answer: The string class is immutable, because once its object(instance) is created, it can not be modified.
All information in an instance is initialized when the instance is created and the information can not be modified.If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.

11.Question : What are the classes java.util.regex have?
Answer: Java.util.regex have three classes - Pattern Class, Matcher class and PatternSyntaxException class.

12.Question : What is an exception ?
Answer: click the link for Answer Exception

13.Question : Difference between throw and throws keyword?
Answer: click the link for Answer Exception

14.Question : What is super keyword in java ?
Answer: click the link for Answer Constructor

15.Question : What is This keyword in java ?
Answer:click the link for Answer Constructor

16.Question : What is inheritance in java ?
Answer: click the link for Answer inheritance

17.Question : What is polymorphism in java ?
Answer: click the link for Answer polymorphism

18.Question : What is Abstraction in java ?
Answer: click the link for Answer abstraction

19.Question : What is Abstract class ?
Answer: click the link for Answer abstraction

20.Question : What is encapsulation in java ?
Answer: click the link for Answer encapsulation

21.Question : What is interface in java?
Answer: click the link for Answer interface

22.Question : Explain the line public static void main(String args[])
Answer: public : It is the access specifier.
static : it allows main() method to be called without instantiating a particular instance of a class.
void : It confirm to compiler that no value will be returned by main().
String args[]: args parameter is an instance array of class String.

23.Question : What is the difference between object oriented programing language & object oriented programming language?
Answer: Object based programming languages follow all the features of OOPs except Inheritance. JavaScript is an example of object based programming languages.

24.Question : What is static block?
Answer: It is used to initialize the static data member, it is executed before main method at the time of class loading.

25.Question : What is overloading ?
Answer: click the link for Answer overloading.

26.Question : What is overriding ?
Answer: click the link for Answer overriding.

27.Question : How to create dynamic size array ?
Answer: click the link for answer ArrayList

28.Question : What is package in java?
Answer: Click the link Package

29.Question : What are different phases of java program ?
Answer: There are five different phases of java program :
Edit : We write our code and save them.
Compile : The next step after writing the code is to compile it, here our compiler compile the program and create bytes code of program.
Load :Class loader load our compiled byte code into the memory.
Verify : The bytecode verifier checks the code fragments for illegal code that can violate access right to objects.
Execute : Finally the execution engine convert our byte ode into machine code via interpreter and execute it.

30.Question :What is main method?
is it necessary to put a main method in a program ?
Answer:Main method is starting point of any java program
Yes, it is necessary to put a main method in a program, without a main() method our program will compile but it will throw "main method not found" Exception at run time.

31.Question :Is it necessary to save java file name same as of class name?

Answer: No, It is not necessary.we can save our java filename with any name unless there is no "public class" inside our java program. If a class is defined public then it is mandatory to save the Java filename same as the public class name.

32.Question :Explain Data types in java?

Answer: DATA TYPES

33.Question :What is a signed Data Type?

Answer:A signed data type is one which can have both positive as well as negative values. but in case of unsigned data types, they can have only positive values. In java all the datatypes are signed except Char.

34.Question :What is upcasting and downcasting in java ?

Answer:

35.Question :What are the different types of memory area inside JVM?

Answer: There are various types of memory area inside JVM. Some of them are :
Stack :The virtual machine creates a new stack frame for each java method it invokes. The stack frame contains space for methods local variables, its operand stack.
Heap : Here only object gets the memory and that is at runtime.
Class Area : It is furture devided into three memory areas which are class information, constant pool and method area.
Native stacks
PC, FP and SP registers
36.Question :Can we declare our main method as final ?

Answer: Yes, we can, see below example :
public class Chandan
{
public static final void main(String args[])
{
System.out.println("welcome to way2testi.com");
}
}
output : welcome to iamchandan.com

37.Question :What is Anonymous object?

Answer: Anonymous means nameless and a person without any identity. Similarly in Java, an Object who have no reference is known as anonymous Object.
This is very useful if we do not have to reuse out class object. If we do not want to reuse our Object then make them anonymous.

38.Question :What is initialization ?

Answer: Initialization is to enter the first value for any parameter when it is born.

39.Question :Is it possible to have a class without constructor ?

Answer: No, no class can exist without a constructor in java.

40.Question :Can we overload a constructor?

Answer: Yes, we can overload a constructor just like a method by changing the number and type of arguments.

41.Question :Can we define a constructor as final?

Answer: No. we can not define a constructor as final.

42.Question :What is a String?

Answer:String is an array of character.

43.Question :What is a deadlock?

Answer: It is a situation where a thread is waiting for an object lock another threads holds since each thread is waiting for the other thread to release a lock. They both remain waiting forever in the blocked pool for lock acquisition state. The threads are said to be dead locked.

44.Question :What is thread?

Answer: Threading is used to achieve multitasking in java Programming. Whenever a work is to be done simultaneously, use threading.

45.Question :
Answer:

1 :What do you know about Java?

Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.



2 :What are the supported platforms by Java Programming Language?

Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.



3 :List any five features of Java?

Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded



4 :Why is Java Architectural Neutral?

It’s compiler generates an architecture-neutral object file format, which makes the compiled code to be executable on many processors, with the presence of Java runtime system.



5 :How Java enabled High Performance?

Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode, which is a program that contains instructions that must be interpreted into instructions that can be sent directly to the processor.



6 :Why Java is considered dynamic?

It is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.



7 :What is Java Virtual Machine and how it is considered in context of Java’s platform independent feature?

When Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.



8 :List two Java IDE’s?

Netbeans, Eclipse, etc.



9 :List some Java keywords(unlike C, C++ keywords)?

Some Java keywords are import, super, finally, etc.



10 :What do you mean by Object?

Object is a runtime entity and it’s state is stored in fields and behavior is shown via methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.



11 :Define class?

A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.



12 :What kind of variables a class can consist of?

A class consist of Local variable, instance variables and class variables.



13 :What is a Local Variable?

Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.



14 :What is a Instance Variable?

Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.



15 :What is a Class Variable?

These are variables declared with in a class, outside any method, with the static keyword.



16 :What is Singleton class?

Singleton class control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.



17 :What do you mean by Constructor?

Constructor gets invoked when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.



18 :List the three steps for creating an Object for a class?

An Object is first declared, then instantiated and then it is initialized.



19 :What is the default value of byte datatype in Java?

Default value of byte datatype is 0.



20 :What is the default value of float and double datatype in Java?

Default value of float and double datatype in different as compared to C/C++. For float its 0.0f and for double it’s 0.0d



21 :When a byte datatype is used?

This data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.



22 :What is a static variable?

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.



23 :What do you mean by Access Modifier?

Java provides access modifiers to set access levels for classes, variables, methods and constructors. A member has package or default accessibility when no accessibility modifier is specified.



24 :What is protected access modifier?

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.



25 :What do you mean by synchronized Non Access Modifier?

Java provides these modifiers for providing functionalities other than Access Modifiers, synchronized used to indicate that a method can be accessed by only one thread at a time.



26 :According to Java Operator precedence, which operator is considered to be with highest precedence?

Postfix operators i.e () [] . is at the highest precedence.



27 :Variables used in a switch statement can be used with which datatypes?

Variables used in a switch statement can only be a string, enum, byte, short, int, or char.



28 :When parseInt() method can be used?

This method is used to get the primitive data type of a certain String.



29 :Why is String class considered immutable?

The String class is immutable, so that once it is created a String object cannot be changed. Since String is immutable it can safely be shared between many threads ,which is considered very important for multithreaded programming.



30 :Why is StringBuffer called mutable?

The String class is considered as immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.



31 :What is the difference between StringBuffer and StringBuilder class?

Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.



32 :Which package is used for pattern matching with regular expressions?

java.util.regex package is used for this purpose.



33 :java.util.regex consists of which classes?

java.util.regex consists of three classes − Pattern class, Matcher class and PatternSyntaxException class.



34 :What is finalize() method?

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.



35 :What is an Exception?

An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread's method invocation stack.



36 :What do you mean by Checked Exceptions?

It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.



37 :Explain Runtime Exceptions?

It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.



38 :Which are the two subclasses under Exception class?

The Exception class has two main subclasses : IOException class and RuntimeException Class.



39 :When throws keyword is used?

If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature.



40 :When throw keyword is used?

An exception can be thrown, either a newly instantiated one or an exception that you just caught, by using throw keyword.



41 :How finally used under Exception Handling?

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.



42 :What things should be kept in mind while creating your own exceptions in Java?

While creating your own exception − All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. You want to write a runtime exception, you need to extend the RuntimeException class.



43 :Define Inheritance?

It is the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.



44 :When super keyword is used?

If the method overrides one of its superclass's methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.



45 :What is Polymorphism?

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.



46 :What is Abstraction?

It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves the maintainability of the system.



47 :What is Abstract class?

These classes cannot be instantiated and are either partially implemented or not at all implemented. This class contains one or more abstract methods which are simply method declarations without a body.



48 :When Abstract methods are used?

If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.



49 :What is Encapsulation?

It is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. Therefore encapsulation is also referred to as data hiding.



50 :What is the primary benefit of Encapsulation?

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our code.



51 :What is an Interface?

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.



52 :Give some features of Interface?

It includes − Interface cannot be instantiated An interface does not contain any constructors. All of the methods in an interface are abstract.



53 :Define Packages in Java?

A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.



54 :Why Packages are used?

Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations, etc., easier.



55 :What do you mean by Multithreaded program?

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.



56 :What are the two ways in which Thread can be created?

Thread can be created by: implementing Runnable interface, extending the Thread class.



57 :What is an applet?

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.



58 :An applet extend which class?

An applet extends java.applet.Applet class.



59 :Explain garbage collection in Java?

It uses garbage collection to free the memory. By cleaning those objects that is no longer reference by any of the program.



60 :Define immutable object?

An immutable object can’t be changed once it is created.



61 :Explain the usage of this() with constructors?

It is used with variables or methods and used to call constructer of same class.



62 :Explain Set Interface?

It is a collection of element which cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.



63 :Explain TreeSet?

It is a Set implemented when we want elements in a sorted order.



64 :What is Comparable Interface?

It is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered.



65 :Difference between throw and throws?

It includes: Throw is used to trigger an exception where as throws is used in declaration of exception. Without throws, Checked exception cannot be handled where as checked exception can be propagated with throws.



66 :Explain the following line used under Java Program − public static void main (String args[ ]) The following shows the explanation individually − public − it is the access specifier. static − it allows main() to be called without instantiating a particular instance of a class. void − it affirns the compiler that no value is returned by main(). main() − this method is called at the beginning of a Java program. String args[ ] − args parameter is an instance array of class String



67 :Define JRE i.e. Java Runtime Environment?

Java Runtime Environment is an implementation of the Java Virtual Machine which executes Java programs. It provides the minimum requirements for executing a Java application;



68 :What is JAR file?

JAR files is Java Archive fles and it aggregates many files into one. It holds Java classes in a library. JAR files are built on ZIP file format and have .jar file extension.



69 :What is a WAR file?

This is Web Archive File and used to store XML, java classes, and JavaServer pages. which is used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages etc.



70 :Define JIT compiler?

It improves the runtime performance of computer programs based on bytecode.



71 :What is the difference between object oriented programming language and object based programming language?

Object based programming languages follow all the features of OOPs except Inheritance. JavaScript is an example of object based programming languages.



72 :What is the purpose of default constructor?

The java compiler creates a default constructor only if there is no constructor in the class.



73 :Can a constructor be made final?

No, this is not possible.



74 :What is static block?

It is used to initialize the static data member, It is excuted before main method at the time of classloading.



75 :Define composition?

Holding the reference of the other class within some other class is known as composition.



76 :What is function overloading?

If a class has multiple functions by same name but different parameters, it is known as Method Overloading.



77 :What is function overriding?

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding.



78 :Difference between Overloading and Overriding?

Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class parameter must be different in case of overloading, parameter must be same in case of overriding.



79 :What is final class?

Final classes are created so the methods implemented by that class cannot be overridden. It can’t be inherited.



80 :What is NullPointerException?

A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object etc.



81 :What are the ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.



82 :How does multi-threading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.



83 :What invokes a thread's run() method?

After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.



84 :Does it matter in what order catch statements for FileNotFoundException and IOException are written?

Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.



85 :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.



86 :Why Vector class is used?

The Vector class provides the capability to implement a growable array of objects. Vector proves to be very useful if you don't know the size of the array in advance, or you just need one that can change sizes over the lifetime of a program.



87 :How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.



88 :What are Wrapper classes?

These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean etc.



89 :What is the difference between a Window and a Frame?

The Frame class extends Window to define a main application window that can have a menu bar.



90 :Which package has light weight components?

javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.



91 :What is the difference between the paint() and repaint() methods?

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.



92 :What is the purpose of File class?

It is used to create objects that provide access to the files and directories of a local file system.



93 :What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.



94 :Which class should you use to obtain design information about an object?

The Class class is used to obtain information about an object's design and java.lang.Class class instance represent classes, interfaces in a running Java application.



95 :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.



96 :What is Serialization and deserialization?

Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.



97 :What are use cases?

It is part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.



98 :Explain the use of sublass in a Java program?

Sub class inherits all the public and protected methods and the implementation. It also inherits all the default modifier methods and their implementation.



99 :How to add menushortcut to menu item?

If there is a button instance called b1, you may add menu short cut by calling b1.setMnemonic('F'), so the user may be able to use Alt+F to click the button.



100 :Can you write a Java class that could be used both as an applet as well as an application?

Yes, just add a main() method to the applet.



101 :What is the difference between Swing and AWT components?

AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.



102 :What's the difference between constructors and other 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.



103 :Is there any limitation of using Inheritance?

Yes, since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation.



104 :When is the ArrayStoreException thrown?

When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.



105 :Can you call one constructor from another if a class has multiple constructors?

Yes, use this() syntax.



106 :What's the difference between the methods sleep() and wait()?

The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.



107 :When ArithmeticException is thrown?

The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.



108 :What is a transient variable?

A transient variable is a variable that may not be serialized during Serialization and which is initialized by its default value during de-serialization,



109 :What is synchronization?

Synchronization is the capability to control the access of multiple threads to shared resources. synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.



110 :What is the Collections API?

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



111 :Does garbage collection guarantee that a program will not run out of memory?

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.



112 :The immediate superclass of the Applet class?

Panel is the immediate superclass. A panel provides space in which an application can attach any other component, including other panels.



113 :Which Java operator is right associative?

The = operator is right associative.



114 :What is the difference between a break statement and a continue statement?

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



115 :If a variable is declared as private, where may the variable be accessed?

A private variable may only be accessed within the class in which it is declared.



116 :What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.



117 :List primitive Java types?

The eight primitive types are byte, char, short, int, long, float, double, and boolean.



118 :What is the relationship between clipping and repainting under AWT?

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.



119 :Which class is the immediate superclass of the Container class?

Component class is the immediate super class.



120 :What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions.



121 :Under what conditions is an object's finalize() method invoked by the garbage collector?

The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable.



122 :How can a dead thread be restarted?

A dead thread cannot be restarted.



123 :Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException.



124 :Variable of the boolean type is automatically initialized as?

The default value of the boolean type is false.



125 :Can try statements be nested?

Yes



126 :What are ClassLoaders?

A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class.



127 :What is the difference between an Interface and an Abstract class?

An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation.



128 :What will happen if static modifier is removed from the signature of the main method?

Program throws "NoSuchMethodError" error at runtime.



129 :What is the default value of an object reference declared as an instance variable?

Null, unless it is defined explicitly.



130 :Can a top level class be private or protected?

No, a top level class can not be private or protected. It can have either "public" or no modifier.



131 :Why do we need wrapper classes?

We can pass them around as method parameters where a method expects an object. It also provides utility methods.



132 :What is the difference between error and an exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.



133 :Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block.



134 :When a thread is created and started, what is its initial state?

A thread is in the ready state as initial state after it has been created and started.



135 :What is the Locale class?

The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.



136 :What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.



137 :What is runtime polymorphism or dynamic method dispatch?

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.



138 :What is Dynamic Binding(late binding)?

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.



139 :Can constructor be inherited?

No, constructor cannot be inherited.



140 :What are the advantages of ArrayList over arrays?

ArrayList can grow dynamically and provides more powerful insertion and search mechanisms than arrays.



141 :Why deletion in LinkedList is fast than ArrayList?

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.



142 :How do you decide when to use ArrayList and LinkedList?

If you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList should be used. If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList should be used.



143 :What is a Values Collection View ?

It is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.



144 :What is dot operator?

The dot operator(.) is used to access the instance variables and methods of class objects.It is also used to access classes and sub-packages from a package.



145 :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.T



146 :What is type casting?

Type casting means treating a variable of one type as though it is another type.



147 :Describe life cycle of thread?

A thread is a execution in a program. The life cycle of a thread include − Newborn state Runnable state Running state Blocked state Dead state



148 :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.



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

setBounds() method is used for this purpose.



150 :What is the range of the short type?

The range of the short type is -(2^15) to 2^15 - 1.



151 :What is the immediate superclass of Menu?

MenuItem class



152 :Does Java allow Default Arguments?

No, Java does not allow Default Arguments.



153 :Which number is denoted by leading zero in java?

Octal Numbers are denoted by leading zero in java, example: 06



154 :Which number is denoted by leading 0x or 0X in java?

Hexadecimal Numbers are denoted by leading 0x or 0X in java, example − 0XF



155 :Break statement can be used as labels in Java?

Yes, an example can be break one;



156 :Where import statement is used in a Java program?

Import statement is allowed at the beginning of the program file after package statement.



157 :Explain suspend() method under Thread class> It is used to pause or temporarily stop the execution of the thread.



158 :Explain isAlive() method under Thread class?

It is used to find out whether a thread is still running or not.



159 :What is currentThread()?

It is a public static method used to obtain a reference to the current thread.



160 :Explain main thread under Thread class execution?

The main thread is created automatically and it begins to execute immediately when a program starts. It ia thread from which all other child threads originate.



161 :Life cycle of an applet includes which steps?

Life cycle involves the following steps − Initialization Starting Stopping Destroying Painting



162 :Why is the role of init() method under applets?

It initializes the applet and is the first method to be called.



163 :Which method is called by Applet class to load an image?

getImage(URL object, filename) is used for this purpose.



164 :Define code as an attribute of Applet?

It is used to specify the name of the applet class.



165 :Define canvas?

It is a simple drawing surface which are used for painting images or to perform other graphical operations.



166 :Define Network Programming?

It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.



167 :What is a Socket?

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.



168 :Advantages of Java Sockets?

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. It cause low network traffic.



169 :Disadvantages of Java Sockets?

Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.



170 :Which class is used by server applications to obtain a port and listen for client requests?

java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests



171 :Which class represents the socket that both the client and server use to communicate with each other?

java.net.Socket class represents the socket that both the client and server use to communicate with each other.



172 :Why Generics are used in Java?

Generics provide compile-time type safety that allows programmers to catch invalid types at compile time. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types.



173 :What environment variables do I need to set on my machine in order to be able to run Java programs?

CLASSPATH and PATH are the two variables.



174 :Is there any need to import java.lang package?

No, there is no need to import this package. It is by default loaded internally by the JVM.



175 :What is Nested top-level class?

If a class is declared within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Nested top-level class is an Inner class.



176 :What is Externalizable interface?

Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism.



177 :If System.exit (0); is written at the end of the try block, will the finally block still execute?

No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.



178 :What is daemon thread?

Daemon thread is a low priority thread, which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.



179 :Which method is used to create the daemon thread?

setDaemon method is used to create a daemon thread.



180 :Which method must be implemented by all threads?

All tasks must implement the run() method



181 :What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars



182 :What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar .



183 :What is the difference between the size and capacity of a Vector?

The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.



184 :Can a vector contain heterogenous objects?

Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.



185 :What is an enumeration?

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.



186 :What is difference between Path and Classpath?

Path and Classpath are operating system level environment variales. Path is defines where the system can find the executables(.exe) files and classpath is used to specify the location of .class files.



187 :Can a class declared as private be accessed outside it's package?

No, it's not possible to accessed outside it's package.



188 :What are the restriction imposed on a static method or a static block of code?

A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.



189 :Can an Interface extend another Interface?

Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.



190 :Which object oriented Concept is achieved by using overloading and overriding?

Polymorphism



191 :What is an object's lock and which object's have locks?

An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock.



192 :What is Downcasting?

It is the casting from a general to a more specific type, i.e. casting down the hierarchy.



193 :What are order of precedence and associativity and how are they used?

Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left.



194 :If a method is declared as protected, where may the method be accessed?

A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.



195 :What is the difference between inner class and nested class?

When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class.



196 :What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.



197 :What is constructor chaining and how is it achieved in Java?

A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement.



198 :Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.



199 :How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.



200 :What will be the default values of all the elements of an array defined as an instance variable?

If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type.



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 it’s 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: To promote code reuse 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 that’s specific to a particular subclass type. Note: The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t 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 Overridden Method Arguments Must change Must not change Return type Can change Can’t change except for covariant returns Exceptions Can change Can reduce or eliminate. Must not throw new or broader checked exceptions Access Can change 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 can’t 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 can’t 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.Serializable interface 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 can’t 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 Interfaces An abstract class can provide complete, default code and/or just the details that have to be overridden. An interface cannot provide any code at all,just the signature. In case of abstract class, a class may extend only one abstract class. A Class may implement several interfaces. An abstract class can have non-abstract methods. All methods of an Interface are abstract. An abstract class can have instance variables. An Interface cannot have instance variables. An abstract class can have any visibility: public, private, protected. An Interface visibility must be public (or) none. 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. 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 abstract class can contain constructors . An Interface cannot contain constructors . Abstract classes are fast. 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 Methods Purpose Create an instance of a class Group Java statements Modifiers Cannot be abstract, final, native, static, or synchronized Can be abstract, final, native, static, or synchronized Return Type No return type, not even void void or a valid return type Name Same name as the class (first letter is capitalized by convention) -- usually a noun Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action this Refers to another constructor in the same class. If used, it must be the first line of the constructor Refers to an instance of the owning class. Cannot be used by static methods. super Calls the constructor of the parent class. If used, must be the first line of the constructor Calls an overridden method in the parent class Inheritance Constructors are not inherited 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 Class methods are methods which are declared as static. The method can be called without creating an instance of the class Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. 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 called without creating an instance of the class. Instance methods are not declared as static.

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 public protected default private Accessible to class from same package?

yes yes yes no Accessible to class from different package?

yes no, unless it is a subclass no no

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 collection’s 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 Iterator Enumeration doesn't have a remove() method Iterator has a remove() method Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects Can be abstract, final, native, static, or synchronized 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 Vector ArrayList is NOT synchronized by default. Vector List is synchronized by default. ArrayList can use only Iterator to access the elements. Vector list can use Iterator and Enumeration Interface to access the elements. The ArrayList increases its array size by 50 percent if it runs out of room. A Vector defaults to doubling the size of its array if it runs out of room ArrayList has no default size. 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.



59.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 you’ll get). Use this class when you want a collection with no duplicates and you don’t 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 TreeSet HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order. TreeSet is under set i.e. it provides elements in a sorted order (acceding order). We can add any type of elements to hash set. 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 Hashtable HashMap lets you have null values as well as one null key. HashTable does not allows null values as key and value. The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know). The enumerator for the Hashtable is not fail-safe. HashMap is unsynchronized. Hashtable is synchronized. 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 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 the compareTo() 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 Comparato It uses the compareTo() method. int objectOne.compareTo(objectTwo). t uses the compare() method. int compare(ObjOne, ObjTwo) It is necessary to modify the class whose instance is going to be sorted. A separate class can be created in order to sort the instances. Only one sort sequence can be created. Many sort sequences can be created. It is frequently used by the API classes. It used by third-party classes to sort instances.









No comments:

Post a Comment