Java interview Question, Exercises of Java Programming

Java interview Questions for job seek

Typology: Exercises

2019/2020

Uploaded on 04/08/2020

mannd
mannd 🇻🇳

5

(1)

1 document

1 / 13

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Interview Questions in Core Java
Question-1:
Difference between abstract and interface?
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated. But there are many differences
between abstract class and interface that are given below.
Abstract class Vs Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods.
2) Abstract class doesn't support multiple inheritances. Interface supports multiple inheritances.
3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and
final variables.
4) Abstract class can have static methods, main method and constructor. Interface can't have static
methods, main method or constructor.
5) Abstract class can provide the implementation of interface. Interface can't provide the
implementation of abstract class.
6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.
Question-2:
Explain keywords - final, finalize, finally, super, this?
Final: final is a keyword. The variable declared as final should be initialized only once and cannot be
changed. Java classes declared as final cannot be extended. Methods declared as final cannot be
overridden.
Finally: finally is a block. The finally block always executes when the try block exits. This ensures that the
finally block is executed even if an unexpected exception occurs. But finally is useful for more than just
exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a
return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when
no exceptions are anticipated.
Finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize()
method. You can write system resources release code in finalize() method before getting garbage
collected.
this: this is used for pointing the current class instance. It can be used with variables or methods. The
variables is used to differentiate the method scope variable and class scope variable. This can be used
with constructor to call the other version constructor of the same class.
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Java interview Question and more Exercises Java Programming in PDF only on Docsity!

Interview Questions in Core Java

Question-1:

Difference between abstract and interface?

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated. But there are many differences between abstract class and interface that are given below.

Abstract class Vs Interface

  1. Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods.
  2. Abstract class doesn't support multiple inheritances. Interface supports multiple inheritances.
  3. Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
  4. Abstract class can have static methods, main method and constructor. Interface can't have static methods, main method or constructor.
  5. Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
  6. The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

Question-2:

Explain keywords - final, finalize, finally, super, this?

Final: final is a keyword. The variable declared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden.

Finally: finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected.

this: this is used for pointing the current class instance. It can be used with variables or methods. The variables is used to differentiate the method scope variable and class scope variable. This can be used with constructor to call the other version constructor of the same class.

Super: super keyword is used for two purposes. The first one is to call the overloaded constructor of the base class from the derived class. The second one is to differentiate the super class member variable to the subclass member variable if they are same.

Question-3 :

What is Encapsulation and Abstraction?

Abstraction

Abstraction is "To represent the essential feature without representing the back ground details."

Abstraction lets you focus on what the object does instead of how it does it.

Abstraction provides you a generalized view of your classes or object by providing relevant information.

Abstraction is the process of hiding the working style of an object, and showing the information of an object in understandable manner.

Encapsulation

It says wrapping of data member and code members which act upon the data member will be in a single unit. And in any object oriented programming class is the basis for encapsulation.

Question-4 :

What are the Benefits of Object Oriented Programming?

OOP provides a clear modular structure for programs.

It is good for defining abstract data types.

Implementation details are hidden from other modules and other modules has a clearly defined interface.

It is easy to maintain and modify existing code as new objects can be created with small differences to existing ones.

Objects, methods, instance, message passing, inheritance are some important properties provided by these particular languages

Encapsulation, polymorphism, abstraction are also counts in these fundamentals of programming language.

It implements real life scenario.

In OOP, programmer not only defines data types but also deals with operations applied for data structures.

class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. callingClass.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.

Question-9:

Explain try and catch block.

Try Block

The try block contains a block of program statements within which an exception might occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block.

Catch Block

A catch block must be associated with a try block. The corresponding catch block executes if an exception of a particular type occurs within the try block.

Question-10:

Difference between ArrayList and Linkedlist

ArrayList internally uses dynamic array to store the elements. LinkedList internally uses doubly linked list to store the elements.

Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.

ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.

ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Question-11:

What is string and string buffer?

Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable where as StringBuffer/StringBuilder objects are mutable. By immutable, we mean that the value stored in the String object cannot be changed.

What is generics and collections?

Generics are a facility of generic programming that was added to the Java programming language in 2004 within J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety." This feature specifies the type of objects stored in a Java Collection.

The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures. Although referred to as a framework, it works in a manner of a library. The JCF provides both interfaces that define various collections and classes that implement them.

Question-13:

What is Multiple Inheritance?

Multiple inheritances is the ability of a single class to inherit from multiple classes. Java does not have this capability.

The designers of Java considered multiple inheritance to be too complex, and not in line with the goal of keeping Java simple. Multiple inheritances can cause the diamond problem

One specific problem that Java avoids by not having multiple inheritances is called the diamond problem. Java’s alternative to multiple inheritance – interfaces

What a Java class does have is the ability to implement multiple interfaces – which is considered a reasonable substitute for multiple inheritance, but without the added complexity

Question-14:

Difference between inner class and nested class.

An inner class is a specific type of nested class that occurs when a nested class is non-static. And that is the “difference” between an inner class and a nested class – in other words, inner classes are subsets of nested classes. So, be careful, because the terms “inner class” and “nested class” are NOT interchangeable. You can say that an inner class is also a nested class, but you can NOT say that a nested class is also an inner class. This is because nested classes are part of the larger set that includes both inner classes and static nested classes.

Extensions Class Loader

JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment property java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.

System Class Loader

Java classes that are available in the java classpath are loaded using System class loader.

Question-18:

What is the relation between Oracle and java db?

Java DB is a relational database management system that is based on the Java programming language and SQL. Java DB is the Oracle release of the Apache Derby project, the Apache Software Foundation's (ASF) open source relational database project.

Question-19:

What is an exception and error, different kinds of exceptions?

Definition: An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

Checked exceptions: A checked exception 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.

Runtime exceptions: A runtime exception 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 compilation.

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Question-20:

Does Java have destructors?

By having to use a destructor, the developer states exactly when the object will be destroyed, whereas in a language that uses the garbage collection method (like Java), the existing garbage collector does everything by itself.

What are native methods? How do you use them?

Simply put, a native method is the Java interface to non-Java code. It is Java's link to the "outside world." More specifically, a native method is a Java method whose implementation is provided by non-Java code, most likely C. This feature is not special to Java. Most languages provide some mechanism to call routines written in another language.

Question-22:

Can Java thread object invoke start method twice?

After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception

Question-23:

What is transient variable?

A transient variable is a variable that cannot be serialized. The transient keyword can be used to indicate the Java virtual machine that the variable is not part of the persistent state of the object.

Question-24:

What is daemon thread?

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. You can use the setDaemon() method to change the Thread daemon properties

Question-25:

Does each thread in java uses separate stack?

In Java every thread maintains its own separate stack. It is called Runtime Stack but they share the same memory.

Question-26:

What is casting?

Casting really means is taking an Object of one particular type and “turning it into” another Object type. This process is called casting a variable. This topic is not specific to Java, as many other programming languages support casting of their variable types.

What is the purpose of garbage collection?

Every time you create an Object memory is allocated from your computers f to store that object. If you never got rid of these objects then your program would use more and more memory as the more it allocated objects.

In order to fix this you need some way of deleting objects when you don't need them anymore. In older languages like C++ the programmer was responsible for deleting objects manually. The programmer would have to use some method to determine when an object was no longer needed and then manually remove that object.

This is a pain and can lead to memory leaks when programmers fail to do it correctly. When the Java language was designed its creators decided that the computer should take responsibility for removing objects when they were no longer necessary rather than the programmer.

Java therefore contains a garbage collector. This is an automatic memory management system that detects when objects are no longer necessary and removes them. It does this by checking if there is anyway the programmer could get a reference to that object. If there are no accessible references to the object left the garbage collector marks the object as trash and deallocates it at the next opportunity.

Question-

What difference is between wait and sleep methods in java?

sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable" state for specified amount of time. During this time, the thread keeps the lock (monitors) it has acquired. wait (): It is a method on Object class. causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

Question-

What happens if one of the members in a class does not implement Serializable interface?

When you try to serialize an object which implements Serializable interface, incase if the object includes a reference of an non serializable object then NotSerializableException will be thrown.

Question-35:

What is race condition?

A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs.

What is strictfp keyword?

strictfp is a keyword in the Java programming language that restricts floating-point calculations to ensure portability. The strictfp command was introduced into Java with the Java virtual machine (JVM) version 1.2 and is available for use on all currently updated Java VMs.

Question-37:

What is java static import?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined.

Question-38:

What is local class in java?

A local class is declared locally within a block of Java code, rather than as a member of a class. Typically, a local class is defined within a method, but it can also be defined within a static initializer or instance initializer of a class.

Question-39:

What is pass by value and pass by reference?

Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself). Pass by value means the called functions' parameter will be a copy of the callers' passed argument.

Question-40:

Can you serialize static fields of a class?

Static fields (methods are irrelevant since they are part of the class definition so they aren't serialized ) will be reinitialized to whatever value they are set to when the class is loaded. If you have a mutable static field , then the changes made to that value will be lost.

Question-41:

Where can we use serialization?

Serialization is simply turning an existing object into a byte array. This byte array represents the class of the object, the version of the object, and the internal state of the object. This byte array can then be used between JVM's running the same code to transmit/read the object.

Can we have private constructor in java?

We can make constructor as private. So that We can not create an object outside of the class. This property is useful to create singleton class in java. Singleton pattern helps us to keep only one instance of a class at any time.

Question-49:

Why do we need generics in java?

Generics are a facility of generic programming that were added to the Java programming language in 2004 within J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety." This feature specifies the type of objects stored in a Java Collection.

Question-50:

What is a singleton class?

The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.

The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().

The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance