Top 50 Interview Questions on JAVA

1. Why the main method is static in java? Ans: The main method is static because if it is not static then their would be ambiguity (which constructor to be called). 2. Can we overload static method? Ans: yes, we can overload static method with the same name but the parameters but be different. 3. What will happen if you remove the static modifier from the main method? Ans: the program will be complied successfully but when running it will show the error “NoSuchMethodError”. 4. What is the scope of the vairables in java? Ans: Member variable: Member variables must declared inside the class and they can be directly accessed from anywhere in class. Local variables: local variables should be declared inside a method have method level scope and cannot be accessed outside the method. Loop variables: loop variable should declared inside the pair of brackets “{“and”}” in the a method has scope within the brackets only. 5. What is “this” keyword in Java? Ans: this is the reference to the current object, the object whose method or constructor is being called. This is used to invoke the current class constructor. 6. Which class is the superclass for every class? Ans: Object class 7. What is object cloning? Ans: object cloning refers to creating an exact copy of the original object. 8. How inheritance in C++ is different from java? Ans: In java, all the classes inherit from the object class directly or indirectly. Therefore, there is always a single inheritance tree of classes in java and the object class is the root of the tree. The members of the grandparent class are not directly accessible. In java the protected member of class A can access the class B even if the class B is not inherit from class A but both should have to be same package. 9. Can we override the private methods in java? Ans: No, we cannot override private method in java because it is not visual from any other class. 10. What is the blank final variable in java? Ans: It is the final variable that has not initialized during the declaration. 11. What is “super” keyword in java? Ans: the super keyword is used to refer parent class objects. This comes into picture with the concept of inheritance. Used to refer the immediate parent instance variable, to call the parent class method. 12. What is JAVA? Ans: Java is a high-level programming language and is platform independent. Java is a collection of objects. It was developed by Sun Microsystems. There are a lot of applications, websites and Games that are developed using Java. 13. What are the features in JAVA? Ans: Features of Java: • Oops concepts • Object-oriented • Inheritance • Encapsulation • Polymorphism • Abstraction • Platform independent: A single program works on different platforms without any modification. • High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine language and then JVM starts the execution. • Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called main thread. The user can create multiple threads by extending the thread class or by implementing Runnable interface. 14. How does Java enable high performance? Ans: Java uses Just In Time compiler to enable high performance. JIT is used to convert the instructions into bytecodes. 15. What are the Java IDE’s? Ans: Eclipse and NetBeans are the IDE’s of JAVA. 16. What do you mean by Constructor? Ans: • When a new object is created in a program a constructor gets invoked corresponding to the class. • The constructor is a method which has the same name as class name. • If a user doesn’t create a constructor implicitly a default constructor will be created. • The constructor can be overloaded. • If the user created a constructor with a parameter then he should create another constructor explicitly without a parameter. 17. What is meant by Local variable and Instance variable? Ans: Local variables are defined in the method and scope of the variables that have existed inside the method itself. An instance variable is defined inside the class and outside the method and scope of the variables exist throughout the class. 18. What is a Class? Ans: All Java codes are defined in a class. A Class has variables and methods. Variables are attributes which define the state of a class. Methods are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the particular requirement. 19. What is an Object? Ans: An instance of a class is called object. The object has state and behavior. Whenever the JVM reads the “new()” keyword then it will create an instance of that class. 20. What is Encapsulation? Ans: Purpose of Encapsulation: • Protects the code from others. • Code maintainability. 21. What is Polymorphism? Ans: Polymorphism means many forms. A single object can refer the super class or sub-class depending on the reference type which is called polymorphism.Using Manipulation reference type we can call the Addition class “add()” method. This ability is known as Polymorphism.Polymorphism is applicable for overriding and not for overloading. 22. What is meant by Method Overriding? Ans: • Method name should be same • Argument should be same • Return type also should be same The key benefit of overriding is that the Sub class can provide some specific information about that sub class type than the super class. 23. What is meant by Interface? Ans: Multiple inheritance cannot be achieved in java. To overcome this problem Interface concept is introduced. An interface is a template which has only method declarations and not the method implementation. 24. What is meant by Abstract class? Ans: We can create the Abstract class by using “Abstract” keyword before the class name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a concrete class. Abstract method: The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called “abstract”. Declarations are the ends with a semicolon. • An abstract class may have a Non- abstract method also. • The concrete Subclass which extends the Abstract class should provide the implementation for abstract methods. 25. Difference between String, String Builder, and String Buffer. Ans: String: String variables are stored in “constant string pool”. Once the string reference changes the old value that exists in the “constant string pool”, it cannot be erased. Constant string pool Then the older value retains in the constant string pool. String Buffer: • Here string values are stored in a stack. If the values are changed then the new value replaces the older value. • The string buffer is synchronized which is thread-safe. • Performance is slower than the String Builder. Public: Public members are visible in the same package as well as the outside package that is for other packages.Public members in Class A are visible to Class B (Same package) as well as Class C (Different package). Private: Private members are visible in the same class only and not for the other classes in the same package as well as classes in the outside packages.Private members in class A is visible only in that class. It is invisible for class B as well as class C. 26. Difference between Abstract class and Interface. Ans: Abstract Class: • Abstract classes have a default constructor and it is called whenever the concrete subclass is instantiated. • Contains Abstract methods as well as Non-Abstract methods. • The class which extends the Abstract class shouldn’t require implementing all the methods, only Abstract methods need to be implemented in the concrete sub-class. • Abstract Class contains instance variables. Interface: • Doesn’t have any constructor and couldn’t be instantiated. • Abstract method alone should be declared. • Classes which implement the interface should provide the implementation for all the methods. • The interface contains only constants. 27. What is mean by Collections in Java? Ans: Collection is a framework that is designed to store the objects and manipulate the design to store the objects. Collections are used to perform the following operations: • Searching • Sorting • Manipulation • Insertion • Deletion A group of objects is known as collections. All the classes and interfaces for collecting are available in Java utile package. 28. What are all the Classes and Interfaces that are available in the collections? Ans: Given below are the Classes and Interfaces that are available in Collections: Interfaces: • Collection • List • Set • Map • Sorted Set • Sorted Map • Queue Classes: • Lists: • Array List • Vector • Linked List Sets: • Hash set • Linked Hash Set • Tree Set Maps: • Hash Map • Hash Table • Tree Map • Linked Hashed Map Queue: • Priority Queue • 29. What is meant by Ordered and Sorted in collections? Ans: Ordered: It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order. Sorted: Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects. 30. Explain about the different lists available in the collection. Ans: Values added to the list is based on the index position and it is ordered by index position. Duplicates are allowed. Types of Lists are: Array List: • Fast iteration and fast Random Access. • It is an ordered collection (by index) and not sorted. • It implements Random Access Interface. Vector: It is same as Array List. • Vector methods are synchronized. • Thread safety. • It also implements the Random Access. • Thread safety usually causes a performance hit. Linked List: • Elements are doubly linked to one another. • Performance is slow than Array list. • Good choice for insertion and deletion. • In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc. 31. Explain about Set and their types in a collection? Ans: Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not. Hash Set: • Unordered and unsorted. • Uses the hash code of the object to insert the values. • Use this when the requirement is “no duplicates and don’t care about the order”. Linked Hash set: • An ordered version of the hash set is known as Linked Hash Set. • Maintains a doubly-Linked list of all the elements. • Use this when the iteration order is required. Tree Set: • It is one of the two sorted collections. • Uses “Read-Black” tree structure and guarantees that the elements will be in an ascending order. • We can construct a tree set with the constructor by using comparable (or) comparator. TreeSet sorts the elements in an ascending order. And duplicates are not allowed. 32. Explain about Map and their types. Ans: Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses “equals ( )” method to determine whether two keys are same or different. Hash Map: • Unordered and unsorted map. • Hashmap is a good choice when we don’t care about the order. • It allows one null key and multiple null values. Hash Table: • Like vector key, methods of the class are synchronized. • Thread safety and therefore slows the performance. • Doesn’t allow anything that is null. • Duplicate keys are not allowed. Linked Hash Map: • Maintains insertion order. • Slower than Hash map. • Can expect a faster iteration. • Duplicate keys are not allowed. TreeMap: • Sorted Map. • Like Tree set, we can construct a sort order with the constructor. • It is sorted in ascending order based on the key. • Duplicate keys are not allowed. 33. Explain the Priority Queue. Ans: Priority Queue: Linked list class has been enhanced to implement the queue interface. Queues can be handled with a linked list. Purpose of a queue is “Priority-in, Priority-out”. Hence elements are ordered either naturally or according to the comparator. The elements ordering represents their relative priority. 34. What is mean by Exception? Ans: An Exception is a problem that can occur during the normal flow of an execution. A method can throw an exception when something wails at runtime. If that exception couldn’t be handled, then the execution gets terminated before it completes the task. If we handled the exception, then the normal flow gets continued. Exceptions are a subclass of java.lang.Exception. 35. What are the types of Exceptions? Ans: Checked Exception: These exceptions are checked by the compiler at the time of compilation. Classes that extend Throwable class except Runtime exception and Error are called checked Exception.Checked Exceptions must either declare the exception using throes keyword (or) surrounded by appropriate try/catch. Unchecked Exception: These exceptions are not checked during the compile time by the compiler. The compiler doesn’t force to handle these exceptions. It includes: • Arithmetic Exception • ArrayIndexOutOfBounds Exception 36. What are the different ways to handle exceptions? Ans: #1) Using try/catch: A risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block. #2) By declaring throws keyword: At the end of the method, we can declare the exception using throws keyword. 37. What are the Advantages of Exception handling? Ans: • The normal flow of the execution won’t be terminated if exception got handled • We can identify the problem by using catch declaration 38. What are Exception handling keywords in Java? Ans: try: When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory. catch: This is followed by try block. Exceptions are caught here. finally: This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here. 39. Explain about Exception Propagation. Ans: Exception is first thrown from the method which is at the top of the stack. If it doesn’t catch, then it pops up the method and moves to the previous method and so on until they are got. This is called Exception propagation. 40. What is a Thread? Ans: In Java, the flow of a execution is called Thread. Every java program has at least one thread called main thread, the Main thread is created by JVM. The user can define their own threads by extending Thread class (or) by implementing Runnable interface. Threads are executed concurrently. 41. How do you make a thread in Java? Ans: There are two ways available in order to make a thread. 1) Extend Thread class: Extending a Thread class and override the run method. The thread is available in java.lang.thread.The disadvantage of using a thread class is that we cannot extend any other classes because we have already extend the thread class. We can overload the run () method in our class. 2) Implement Runnable interface: Another way is implementing the runnable interface. For that we should provide the Q 42. Explain about join () method? Ans: Join () method is used to join one thread with the end of the currently running 43. Explain about wait () method. Ans: wait () method is used to make the thread to wait in the waiting pool. When a wait () method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool. Wait () method tells the thread to wait for a given amount of time. Then the thread will wake up after notify () (or) notify all () method is called.Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread completes the synchronized code. It is mostly used in Q 44. How to stop a thread in java? Explain about sleep () method in a thread? Ans: We can stop a thread by using the following thread methods. • Sleeping • Waiting • Blocked Sleep: Sleep () method is used to sleep the currently executing thread for the given amount of time. Once the thread is wake up it can move to the runnable state. So sleep () method is used to delay the execution for some period. It is a static method. 45. When to use Runnable interface Vs Thread class in Java? Ans: If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in java we can extend only one class. If we are not going to extend any class then we can extend the thread class. 46. Difference between start() and run() method of thread class. Ans: Start() method creates new thread and the code inside the run () method is executed in the new thread. If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method. 47. What is Multi-threading? Ans: Multiple threads are executed simultaneously. Each thread starts their own stack based on the flow (or) priority of the threads. 48. What is Synchronization? Ans: Synchronization makes only one thread to access a block of code at a time. If multiple thread accesses the block of code, then there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes. The synchronized keyword means that a thread needs a key in order to access the synchronized code.Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the thread can get the key to the objects lock. 49. What is meant by Serialization? Ans: Converting a file into a byte stream is known as Serialization. The objects in the file is converted to the bytes for security purposes. For this, we need to implement java.io.Serializable interface. It has no method to define. Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by using a transient keyword. 50. What is the purpose of a transient variable? Ans: Transient variables are not part of the serialization process. During deserialization, the transient variables values are set to default value. It is not used with static variables. -viraj mhashelkar SRIEIT]]>

Written by Anant K

Anant Krupa is a follower of lord vishnu, founder & CEO of Redicals. A Software Engineer and a passionate Web developer by heart. He just love – working with computers

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.