1. What is this Keyword in Java In Java, “this” Keyword is a reference variable that refers to the current object. You can refer to any member of the current object from within an instance method or a constructor by using “this”. You can refer a field of a class also. The main purpose of using “this” keyword is to differentiate the class attributes and parameters with the same name. Top 50 C Questions and Answers
Various use of this Keyword in Java
1. this can be used to refer current object.
2. this can be used to refer current class instance variable.
3. this can be used to invoke current class method.
4. this can be used to invoke current class constructor.
5. this can be passed as an argument in the method call.
6. this can be passed as argument in the constructor call.
7. this can be used to return the current class instance from the method.
8. this can be used to call one constructor within the another constructor without creation of objects multiple time for the same class.
2. What is Constructor in Java The constructor is a block of codes similar to the method. It has the same name as its class. It is a special type of method which is used to initialize the object. The constructor automatically calls a default constructor when there is no constructor available in the class. In such case, Compiler provides a default constructor by default. A Java constructor cannot be abstract, static, final, and synchronized. There are 3 Types of Java constructors.
Types of Java constructors:
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
1. No-Arg Constructor:
If a constructor does not accept any parameters. It is known as a no-argument constructor.
2. Java Parameterized Constructor:
A Java constructor can also accept one or more parameters. It is known as parameterized constructors.
3. Java Default Constructor:
If there is no constructor available in the class. In such case, Java compiler provides a default constructor. It is called default constructor.
3. What is ArrayList in Java In Java , Array List class is used to extend Abstract List and implements the List interface. Java Array List class uses a dynamic array for storing the elements. In normal Array there is a size limit. In Array List the size automatically increase or decrease when add or remove the elements. The ArrayList maintains the insertion order and it can have the duplicate elements also. The Java Array List is a re-sizable array.
Points To Remember:
Array List is a re-sizable array.
Array Lists can be immutable.
Array List can dynamically grow and shrink.
Array List internally uses an array to store the elements.
Array List holds only object types and not primitive types.
Array List class can contain duplicate elements and null values.
Array List class maintains insertion order.
Array List class is non synchronized.
Array List allows random access also.
4. What is Exception Handling in Java In Java, The Exception Handling means it’s a mechanism to handle the runtime errors and to maintain the normal flow of the application. An exception is an event that disrupts the normal flow of the program at runtime. When an error occurs within a method, the method creates an object that is called an exception object. It contains information about the errors, including its type and the state of the program.
There are three main categories of exceptions:
1. Checked exceptions: Checked exceptions are checked at compile-time e.g. IOException, SQLException etc..
2. Unchecked exceptions / Runtime exceptions: Unchecked exceptions are not checked at compile-time, but they are checked at runtime e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc..
3. Errors: Errors are some logical mistakes e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Handling Keywords:
Try: The “try” keyword is used to specify a block of exception code followed by either catch or finally.
Catch: The “catch” block is used to handle the exception.
Finally: The “finally” block is used to execute the particular code of the program.
Throw: The “throw” keyword is used to throw an exception.
Throws: The “throws” keyword is used to declare exceptions. It doesn’t throw an exception.
5. What is An Interface in Java An interface is a mechanism it is used to achieve abstraction. An interface is a group of related methods with empty bodies. Interfaces are similar to classes. It can have only abstract methods and static fields but default and static methods are added in Java 8 and private methods are added in Java 9. To implement an interface you must override all of its methods.
Points To Remember:
Interface methods are by default abstract and public.
An Interface attributes are by default public, static and final.
It supports multiple inheritances.
It supports to achieve abstraction.
It supports to achieve loose coupling.
It can extend one or more other interface.
It can be nested inside another interface.
6. What is Garbage Collection in Java Garbage Collection in java is process of reclaiming the runtime unused (Objects) memory automatically. The garbage means un-referenced objects. The objects are created on the heap memory and some objects will no longer be needed. So the garbage collector finds these unused objects and it performs automatically when java programs are run on a Java Virtual Machine. We can also request JVM to run Garbage Collector.
Advantage of Garbage Collection:
It is a best memory management because garbage collector removes the unreferenced objects from the heap memory.
It is automatically done by the garbage collector.
It makes Java memory-efficient.
Faster memory allocation.
Increased cache performance.
Disadvantages of Garbage Collection:
GC stops the entire program while seeking and collecting garbage objects.
Additional process to run.
Increase in memory needs.
Degrades cache performance.
Degrades page locality.
Types of garbage collectors:
Serial Garbage Collector (GC).
Parallel/throughput GC.
CMS Collector.
G1 Collector.
ZGC.
7. What is Abstract Class in Java The Abstract Class is mainly used for abstract and non-abstract methods and to achieve abstraction in Java. A class which is declared as abstract is known as an abstract class. It can have Constructors and static methods also.
What is “Abstraction”? Abstraction is a process of hiding the implementation details and showing only functionality to the user. For example filling the contact form. It will show only the particular details of the contact form not internal process details. It’s called Abstraction in Java.
Points To Remember :
It can have abstract and non-abstract methods.
It cannot be instantiated.
It is used for abstraction.
It provides 100% abstraction because it can have concrete methods.
An abstract class must be declared with an abstract keyword.
An Abstract methods can either be hidden or overridden, but non abstract methods can only be hidden.
Abstract method:
A method which is declared as abstract and does not have implementation is known as an abstract method. Methods are declared without body within an abstract class is also called abstract method.
8. What is LinkedList in Java Java Linked List is a linear data structure used for storing collection of data and each element is a separate object that is called Node. The Linked List elements are not stored in contiguous locations.The Linked List acts like a dynamic arrays, there is no need to increase or decrease the size of the list and the size of the Linked List automatically increases when we dynamically add and remove lists.
There are three types of Linked Lists :
Singly Linked List: Singly linked lists contain nodes which have a data part as well as an address part. The operations we can perform on singly linked lists are insertion, deletion and traversal.
Doubly Linked List: In a doubly linked list, each node contains two links the first link points to the previous node and the next link points to the next node in the sequence order.
Circular Linked List : In the circular linked list the last node of the list contains the address of the first node and forms a circular chain.
Points To Remember:
Java Linked List class can contain duplicate elements.
Java Linked List class maintains insertion order.
Java Linked List class is non synchronized.
End of the Linked List must be pointing to NULL.
Java Linked List class can be used as a list, stack or queue.
Linked Lists are used to create trees and graphs.
Methods:
GetFirst():Get the item at the beginning of the list.
GetLast():Get the item at the end of the list.
AddFirst():Adds an item to the beginning of the list.
AddLast():Add an item to the end of the list.
RemoveFirst():Remove an item from the beginning of the list.
RemoveLast():Remove an item from the end of the list.
9. What is Stack in Java In Java, Stack is a data structure that is used to store the collection of objects. It represents a last-in-first-out (LIFO) stack of objects. Objects can be added or stored in a stack by using push method and Objects can be removed by using pop method. Stack class is a Collection framework that extends the Vector class it also implements interfaces like Collection, List, Iterable, Cloneable and Serializable. When an item is removed, it can be removed from the topmost of the stack. The items are removed from the top is considered a “LIFO” (Last In, First Out) stack. When an item is added, it can be added top of the stack.
Stack in Java? Methods:
Empty (): Tests if this stack is empty.
Peek (): Looks at the object at the top of this stack without removing it from the stack.
Pop (): Removes the object at the top of this stack and returns that object as the value of this function.
Push (E item): Pushes an item onto the top of this stack.
Search (Object O): Returns the 1-based position where an object is on this stack.
10. Encapsulation in Java Encapsulation is a mechanism to wrapping the data (variables) and the code (methods) together into a single unit. For example: Vehicle Class in this, Vehicle has number of variables and methods and interlinked with each other. So the variable of a class is hidden from any other class and can be accessed only through any member function of its own class. It provides setter and getter methods to make the class read-only or write-only. To create a fully encapsulated class in Java by making all the data members of the class has private.
Advantages of Encapsulation in Java:
It provides control over the data.
It is a way to achieve data hiding.
It makes programming flexible.
It makes the application simple and easy to debug.
It is easy to test so it is better for unit testing.
It supports Re-usability.
It supports read-only or write-only.
It helps to achieve loose coupling.
11. throw vs throws in Java In Java the keyword throw used to exception handling explicitly from a method or a block of code. Whereas the throws keyword is used in signature of the method.
throw vs throws:
1. Throw keyword is used to explicitly throw an exception.It can throw only one exception at a time.
2. Checked exception cannot be propagated using throw only.
3. Throw is followed by an instance.
4. Throw is used within the method.
5. You cannot throw multiple exceptions.
1. Throws keyword is used to declare multiple exceptions, separated by comma.
2. Checked exception can be propagated with throws.
3. Throws is followed by class.
4. Throws is used with the method signature.
5. You can declare multiple exceptions.
12. Difference between Abstract class vs Interface Abstract class and interface both are used to achieve abstraction. Abstract class achieves partial abstraction 0 to 100% whereas interface achieves 100% abstraction.
Abstract class vs Interface in Java:
Abstract class can have abstract and non-abstract methods. Whereas interface can have only abstract methods. Since Java 8, it can have default and static methods. Since Java 9, it can have private methods also. Abstract class doesn’t support multiple inheritances. Whereas interface supports multiple inheritance. Abstract class can have final, non-final, static and non-static variables.
Whereas interface has only static and final variables. Abstract class can provide the implementation of interface. Whereas interface can’t provide the implementation of abstract class.
Abstract keyword is used to declare abstract class. Whereas interface keyword is used to declare interface. An abstract class can extend another Java class and implement multiple Java interfaces. Whereas interface can extend another Java interface only. Abstract class can be extended using keyword “extends”. Whereas interface can be implemented using keyword “implements”.
Abstract class can have class members like private, protected, etc. Whereas members of a Java interface are public by default. Abstract class can have protected and public abstract methods. Whereas interface can have only public abstract methods.
In abstract class keyword “abstract” is mandatory to declare a method as an abstract. Whereas interface keyword “abstract” is optional to declare a method as abstract. Abstract class can extend only one class or one abstract class at a time. Whereas an interface can extends any number of interfaces at a time.
13. What is Polymorphism in Java Polymorphism means “Many forms” The Polymorphism is one of the core concepts in OOPs languages and describes the concept where you can use different classes with the same interface.
The Polymorphism has two types Runtime polymorphism (dynamic binding) and Compile time polymorphism (static binding).
We can perform polymorphism in java by method overloading and method overriding. Method overriding is an example of dynamic polymorphism, while method overloading is an example of static polymorphism.
Types of Polymorphism:
1.Method Overriding
2.Method Overloading
3.Operator Overloading
14. What is Method Overloading in Java In Java, Method overloading means a class has more than one method of the same name but different in parameters is known as Method Overloading. In other words, When two or more methods in the same class have the same name but different in parameters is known as Method Overloading. There are two ways to Overload the method in java. By changing the number of arguments.
By changing data types.
Method Overloading Rules and Advantage:
1. Method overloading increases the readability of the program.
2. Method overloading is also used on constructors to create new objects given different amounts of data.
3. Method overloading occurs between the methods in the same class and makes the code look clean.
4. Method overloading reduces the execution time because the binding is done in compilation time itself.
5. Method overloading minimizes the complexity of the code.
6. Method Overloading implements Compile time polymorphism.
7. we can use the Method overloading code again, which saves memory.
Method Overloading Rules and Disadvantage:
1. The return type cannot be overloaded.You must define a return type for each overloaded method.
2. Member function declarations with the same name and the same parameter types cannot be overloaded.
15. What is Method Overriding in Java If subclass has the same method as declared in the parent class is known as method overriding in Java. In other words, When the Method signature (name and parameters) are the same in the superclass and the child class is known as method overriding in Java.
Method Overriding Rules and Advantages:
1. Method Overriding is the concept which implements Code binding.
2. Method overriding must be an IS-A relationship (inheritance).
3. Method Overriding occurs between super class and subclass.
4. In Method overriding method must have the same parameter as in the parent class.
5. Return type must be same in method overriding.
6. Method overriding occurs in two classes that have inheritance (IS-A) relationship.
7. Method Overriding implements Runtime Polymorphism.
Method Overriding Rules and disadvantages:
1. The final method does not support the method overriding.
2. Static method cannot be Override.
3. Contractors cannot be Override.
16. ArrayList vs LinkedList in Java In Java, Lists are data structures used for storage. These are ordered collections which allow duplicate elements also. ArrayList and LinkedList are two different implementations of the List interface and both classes are non-synchronized. ArrayList internally contains an array of values. If an element is added, the size is increased. If an element is removed, the size is decreased.
Whereas LinkedList is a doubly-linked list it supports “Queue” implementation to connect the elements instead. ArrayList search operation is fast compared to the LinkedList search operation. ArrayList implements only List. LinkedList implements List as well as Queue. ArrayList is better for sorting and accessing the data. LinkedLilst is better for manipulating data. Manipulation with ArrayList is slow because it internally uses dynamic array. Manipulation with LinkedList is faster than ArrayList because it uses a doubly LinkedList.
17. What is List Interface in Java The List is a generic Interface it extends Collection and declares the behavior of a Collection that stores a sequence of elements. A List may contain duplicate elements. The elements can be inserted or accessed by their position in the List (Zero-based index). The List implementation classes are ArrayList, LinkedList, Stack and Vector.
Methods of the List Interface:
add(int index, element) – This method is used to add an element at a particular index in the list.
addAll (int index, Collection collection) – This method is used to add all the elements in the given collection to the list.
get(int index) – This method returns elements at the specified index.
set(int index, element) – This method replaces elements at a given index with the new element.
remove(element) – This method is used to remove the first occurrence of the given element in the list.
isEmpty() – This method is used to check if the list is empty or not.
18. What is Set Interface in Java In Java the Set Interface extends collection and declares the behaviour of a collection.
A set collection provides the features of a mathematical set. It does not allow duplicate elements.
Set is a generic interface.
Some of the important points:
The set interface is a part of the java.util package and part of the Java Collections Framework.
The set interface allows unique values.
It does not allow duplicate elements.
It can have at most one null value.
Java 8 provides a default method for the set interface.
The set interface supports generics.
Some Methods:
add ( E e ) – Adds the element e to the set if it is not present in the set
remove ( Object o ) – Deletes the given element o from the set.
isEmpty () – Checks if the set is empty or not.
toArray () – Converts the set to array representation that contains all the elements in the set.
19. Vector Class in Java Vector Class implements a dynamic array which means it can grow or shrink as required same Like an array. Vector is synchronized and has some legacy methods that are not part of the collections framework.
It maintains an insertion order like an ArrayList.
It gives a poor performance in adding, searching, deleting, and updating its elements.
It throws the ConcurrentModificationException when concurrent modification.
20. What is Queue in Java Queue is a linear data structure. you can handle an ordered collection of elements. It extends Collection interface. Java Queue supports all methods of Collection interface. It follows the First In First Out (FIFO). It is an ordered list of objects, where insertion of elements occurs at the end of the list, and removal of elements occur at the beginning of the list. Most frequently used Queue implementations are LinkedList, ArrayBlockingQueue and PriorityQueue. BlockingQueues do not accept null elements. BlockingQueues are thread-safe.
Advantages of Queue:
A large amount of data can be managed efficiently.
We can access both ends and they are fast and flexible.
Queue can handle multiple data.
21. What are the differences between this and super keyword In Java, “this” Keyword is a reference variable that refers to the current object. You can refer to any member of the current object from within an instance method or a constructor by using “this”.
The “super” keyword is a reference variable in Java that is used to refer to the immediate parent class object. It is used to call superclass methods, and to access the superclass constructor. The super can also be used to invoke the immediate parent class method. The super is used to invoke parent class constructor. It can also be used to access the fields of the parent class.
22. What is Lambda expression Lambda expression is a new feature. It was interduced in Java 8. Lambda expression is an anonymous function without name(anonymous function). It can’t extend abstract and concrete class.
The Lambda expression is used to provide the implementation of an interface which has functional interface. And it has only one abstract method That is called functional interface. It is very useful in collection library. It helps to iterate, filter and extract data from collection. Lambda expression provides an annotation @FunctionalInterface, which is used to declare an interface as functional interface.
23. What is Synchronization in Java In Java Synchronization is the process to control the access of multiple threads to any shared resource.
Thread Synchronization allows only one thread to use the object when multiple threads are trying to use the particular object at the same time.
Types of Synchronization:
There are two types
Process Synchronization
Thread Synchronization
24. What is object cloning in Java In Java, The Object cloning is the process of creating an exact copy of an object. It is defined in the object class. And it creates a new instance class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
25. What are the local variables in Java A variable declared within the body of a method is a local variable. These variables need to be initialized before use.
1. Local variables are declared in methods or blocks.
2. Access modifiers cannot be used for local variables.
3. There is no default value for local variables
4. Local variables are visible only within the declared method or block.
5. Local variables are implemented at stack level internally.
26. Can you declare the main() method as final Yes, we can declare the main() method as final in Java. The main use of the final method in Java is they are not overridden. The compiler does not throw any error. If we declare any method as final by placing the final keyword then that method becomes the final method.
27. Can we override static method in Java No, The static methods in Java cannot be overridden. Because static methods are not associated with the instance of a class, but with the class itself. The reason when a subclass inherits a static method from its parent class, it cannot modify the behavior of the static method in any way.
#Tags: | Java | Java Keywords | Java Methods | Java Questions | Java FAQs | Java questions and answers |
*Disclaimer: We have published the above images and information for reference purpose only, for any changes on the content we refer to visit the Official Website to get the latest info.
NOTE: Naukri9.Com Employees will not call any candidates towards Job Offer or Job assistance. We never charge any candidates for Jobs. Please be aware of fraudulent Calls or Emails.