Java Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

How can we make String upper case or lower case?

We can use String class's toUpperCase and toLowerCase methods to get the String in all upper case or lower case.

What is the difference between Collection and Collections?

Collection is an interface while Collections is a java class, both are present in the java.util package.

How to reverse the List in Collections?

Collections.reverse(listobject);

How will you make Collections readOnly?

Collections.unmodifiableCollection(Collection c)

What is a final class?

A Final class can't be inherited.

What is a Class?

A class is the blueprint from which individual objects are created.

What is Collection? What is the Collections Framework?

A collection is an object that groups multiple elements into a single unit. The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures.

What is a Constructor?

A constructor is a method whose name is the same as the class name whose task is to initialize an object of its class. It does not have a return type and they cannot return values. They cannot be inherited, though a derived class you can call the base class constructor. The constructor is invoked when you create an object of its class.

Race condition

A state where two subjects can access the same object without proper mediation A Race condition is when programming bugs happen in concurrent execution environments. A race condition occurs due to a race between multiple threads.

What is a Thread in Java?

A thread is a lightweight sub process, it is a separate way. They are indepedent, if any exception occurs in one thread, another thread will not affect it.

What is a static variable?

A variable declared with the static keyword that is outside a method and inside a class is called a static variable.

What is Abstraction?

Abstraction is the concept of hiding the internal details and showing functionality in a simple manner. A Java program is also an example of abstraction.

What are the 7 concepts of OOP?

Abstraction, Encapsulation, Polymorphism, Inheritance, Association, Composition, and Aggregation.

What are access modifiers?

Access modifiers determine the scope of the method or variables that can be accessed from other various objects or classes. There are 4 types of access modifiers , and they are as follows:. Private. Protected. Public. Default Protected Friend.*

Which is the final class in these three classes - String, StringBuffer and StringBuilder?

All are final classes. But String is immutable and StringBuffer and StringBuilder are mutable.

What is an Object?

An Object is a runtime entity and it has state( as a field) and behavior(method).

What is an abstract class?

An abstract class cannot be instantiated. It can be inherited but the creation of an object is not possible with an abstract class. It may or may not include abstract methods. An abstract class is used to provide abstraction.

What is an interface?

An interface is a collection of abstract methods. It is similar to a class. An interface is not extended by a class, it is implemented by a class. An interface can extend multiple interfaces. The interface cannot be instantiated. An interface does not contain any constructors.

What is an iterator?

An iterator is an interface. It is present in the java.util.package. It gives methods to iterate over any Collection.

What is the difference between Array and ArrayList in Java?

Array is static in size while the ArrayList is dynamic in size. Arrays can contain primitive data types while ArrayList can not contain primitive data types.

What is the difference between ArrayList and Vector?

ArrayList is not synchronized. ArrayList is not a legacy class. Vector is a legacy class. Vector is synchronized.

What is the difference between ArrayList and LinkedList?

ArrayList uses a dynamic array. ArrayList is not good for manipulation because a lot of shifting is required. ArrayList is better to store and get data. LinkedList uses doubly linked list. LinkedList is good for manipulation. It is also better to used to manipulate data.

How do you share data between two threads in Java?

By using a shared object you can share data, or using concurrent data structures like BlockingQueue.

What is the difference between Checked Exception and Unchecked Exception?

Checked Exception: Checked exceptions are checked at compile-time. Unchecked Exception: Unchecked exceptions are not checked at compile-time. It comes at runtime.

What is Encapsulation?

Encapsulation is a mechanism of wrapping data as a single unit. In Encapsulation, variables of a class are hidden from other classes, and can be accessed from there methods of the same class. Therefore, it is also called Data Hiding. We can achieve encapsulation using setter and getter methods.

What is Exception in Java?

Exception is an error that can come during the execution of a program and stop its normal flow. Exception can be of different type such as wrong data entered by the user, hardware failure, network connection failure etc.

What is finally block?

Finally block is a block that is always executed.

What is the difference between HashMap and HashTable?

HashMap allows one null key and any number of null values while HashTable does not allow null keys and null values. HashMap is not synchronized or thread-safe while Hashtable is synchronized aka thread-safe.

What is the difference between HashSet and TreeSet?

HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order. HashSet can store null object while TreeSet can not store null objects.

How does a Java default constructor be provided?

If a class does not have any constructor, the compiler will automatically provide a default constructor.

What is ThreadInterruption in Java?

If any thread is in sleeping or waiting state, then calling the interrupt() method on the thread, breaks out the sleeping or waiting state and it will throw an InterruptedException.

What happens when an Exception occurs in a thread?

If you are not catching, threads will die. If an uncaught exception handler is presented then it will get a call back.

Why are wait() and notify() methods called from a synchronized block?

If you dont call the wait or notify methods from a synchronized context, your code will throw an (IllegalMonitorStateException). Its also to avoid the race condition between the wait and notify calls.

What is a final variable?

If you make a variable as a final, you cannot change the value of the final variable, it will be constant.

What is the advantage of generic collection?

If you use generic class, you don't need typecasting. It is typesafe and checked at compile time.

What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can't modify them once they are created. They are final. Whereas mutable objects can be modified.

What is the difference between Java strings and C, C++ strings?

In C and C++, strings are terminated with the null character. But in Java, strings are not terminated with a null character. Strings are treated as objects in Java.

What is Composition?

In composition two classes are highly dependent on each other. For example a bike and engine. Without an engine the bike cannot work.

How to Split a String in Java?

In the String class, there is a split method, split(String rgx) method can use to split the String into String array based on the given regular expression.

What is inheritance?

Inheritance is an object oriented programming concept where one class inherits the property of another class or interface.

What is an instance variable?

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

What is Association?

It defines the relation between objects. An aggregation is a special form of association which is a one-way relationship between classes.

What is the advantage of java multithreading?

It doesn't stop the user because threads are independent and you can perform multiple tasks at the same time. You can perform many operations at the same time so it saves time.

Why is String immutable or final in Java?

It increases security for storing sensitive information such as database username, password etc.

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 final block.

What is an abstract method?

Its methods that are declared without a body within an abstract class are called abstract methods.

How to compare two Strings in a java program?

Java String implements Comparable interface and it has two variants of compareTo() methods. Like compareTo(String str2) method compares the String object with the String argument passed lexicographically. If the String object precedes the argument passed, it returns the negative integer and if the String object follows the argument the string passed, it returns a positive integer. It returns zero when both the String have the same value.*

When do we use Runnable and Thread in Java?

Java programming doesn't support multiple inheritances of a class, but it allows you to implement multiple interfaces. Which means, its good to implement Runnable then extends Thread if you have to extend another class.

What do you mean by access modifier?

Java provides access modifiers to access classes, variables, methods, and constructors.

What are wrapper classes?

Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are example: Integer, Character, Double etc.

What is the difference between List and Set?

List can contain duplicate elements whereas Set contains only unique elements. Set stores elements in an unordered way while List is ordered. List maintains the order in which the objects are added.

What is Compile time polymorphism?

Method overloading is an example of compile time polymorphism. Method overloading is also known as Static polymorphism. It is also known as static binding. It happens at compile time.

What is multitasking?

Multitasking is a process to execute multiple tasks simultaneously. There are two ways of doing it. By multiprocessing and multithreading.

What is multithreading?

Multithreading is a process of executing multiple threads simultaneously. Its main advantage is: Threads share the same address space. Multithreading is used to achieve multitasking.

Can I have multiple main() methods in the same class?

No the program fails to compile.

Can a constructor be inherited?

No, a constructor cannot be inherited.

Can we declare a constructor final?

No, because a constructor is never inherited.

Can we define private and protected modifiers for variables in interfaces?

No, by default they are public.

What is Polymorphism?

Polymorphism is a concept in java to achieve the same action by many ways. Two types of polymorphism in java are Runtime Polymorphism(aka method overriding) and Compile time Polymorphism(aka method overloading)

Can an interface be final?

No. Because it is implemented by another class. If you will declare an interface as a final, you cannot use it.

Do I need to import java.lang package any time? Why ?

No. It is loaded internally by the JVM.

Can we start a thread twice?

No. It will throw an exception. (IllegalThreadStateException).

Is String a keyword in Java?

No. String is not a keyword in java. It is a Class.

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

Object based programming languages follow all the features of OOP's except for Polymorphism or Inheritance. Examples of object-based programming languages are JavaScript, VBScript.

What is OutOfMemoryError in Java?

OutOfMemoryError in Java is a sub-class of java.lang.VirtualMachineError and its thrown by the JVM when it ran out of heap memory. We can solve this error by giving more memory to run the java program.

What is platform independent?

Platform independent means the java source code can run on all operating systems. "Write once and run anywhere" is called platform independent.

Whats the difference between preemptive scheduling and time slicing?

Preemptive scheduling is when the highest priority task will execute until it enters the waiting state. In time slicing, a task executes for a predefined slice of time.

What is the difference between Queue and Stack?

Queue is FIFO and a Stack is LIFO.

What is the difference between Runnable and Callable in Java?

Runnable and Callable both represent a task which is executed in a separate thread. The difference between these two is that Callables call() method can return the value and throw an Exception, which is not possible with Runnables run() method.

What is Runtime polymorphism?

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 super class. The determination of the method to be called is based on the object being referred to by the reference variable.

How many types of memory is allocated by the JVM?

Stack, Heap, Class Area, Native Method Stack, Program Counter Register.

Which collection classes are synchronized or thread-safe?

Stack, Properties, Vector and Hashtable are synchronized classes. (aka thread safe)

What is the difference between static binding and dynamic binding?

Static binding type of object is determined at compile time. But a dynamic binding type of object is determined at runtime.

What are static variables?

Static variables that have only one copy per class. They are declared by using the static keyword as a modifier.

What is a String Pool?

String Pool is a pool of Strings stored in Java heap memory.

What is String in Java? Is String a data type?

String is a Class in java and defined in java.lang package. Its not a primitive data type like int and long, char, and float.

Is String a primitive type or a derived type?

String is a derived type.

Whats the difference between String, StringBuffer, and StringBuilder?

String is immutable and final in Java, so whenever we use String manipulation, it creates a new String. Java provides two utility classes for String manipulations: -StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe.

Which class will you recommend among String, StringBuffer and StringBuilder classes if I want mutable and thread safe objects?

StringBuffer

Is String thread-safe in Java?

Strings are immutable, so we can't change its value. Hence it's thread-safe and can be used in the multi-threaded environment.

What is the Daemon Thread?

The Daemon thread is a service provider thread that provides services to the user thread. Its life depends on the mercy of the user threads like when all the user threads dies, the JVM terminates this thread automatically.

What is the difference between Map and Set?

The Map object has unique keys that each contain values, while Set contains only unique values.

What is the root interface in the collection hierarchy?

The Root interface in the collection hierarchy is a Collection interface.

Why is a string immutable?

The String class is immutable so that once a String object is created, it cannot be changed. A string is immutable so it can safely be shared between many threads, which is very important for multi-threaded programming.

What do you think about string constant pool? Why have they provided this pool? Why have they provided this pool as we can store string objects in the heap memory itself?

The String constant pool increases the re-usability of existing string objects. When you are creating a string object using a string literal, the JVM first checks the string constant pool. If that object is available, it returns a reference to that object rather than creating a new object. This will also speed up your application and also saves the memory, because here no two objects with the same content are created.

Why use the clone() method?

The clone() method saves the extra processing task for creating the same copy of an object. An advantage of object cloning is less processing tasks.

What is the CurrentThread method?

The currentThread() method returns a reference to the currently executing or running thread object.

What is the Dictionary class?

The dictionary class provides the capability to store key-value pairs.

Is there any case when finally will not be executed?

The finally block will not be executed if the program exits. (whether its either calling System.exit() or by causing a fatal error.

What is the Join() method?

The join() method waits for a thread to die. In other words we can say, it causes the currently running threads to stop executing until the thread it joins with completes its task.

What is the difference between Iterator and Enumeration?

The main difference between Iterator and Enumeration is that Iterator has the remove() method while Enumeration doesn't. Using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration can only traverse the objects and fetch the objects.

What is the difference between notify and notifyAll in Java?

The notify() method only notifies one thread. But the notifyAll() sends a notification to all threads and allows them to compete for locks, which ensures that at least one thread will proceed further.

What is the sleep() method in Java?

The sleep() method of the Thread class is used to sleep a thread for the certain amount of time.

Explain the life cycle of a thread or explain the state of a thread.

There are 4 states in a thread lifecycle in Java. Which are "new", "runnable", "non-runnable" and "terminated".

What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling: Throw Throws try-catch finally

In how many ways can you create string objects in Java?

There are two types of ways to create string objects in java. One is using the "new" keyword and the other is by using string literals. The objects created using the "new" keyword are stored in the heap memory and objects created using string literals are stored in the string constant pool. Ex. String s1 = new String("preparing for java"); String s2 = "doing well";

How do you check if a Thread holds a lock or not?

There is a method called holdsLock() in java.lang.thread. It returns true if the current thread holds the monitor lock on the specified object.

What is thread-safety? Is Vector a thread-safe class?

Thread-safety is a property of an object which guarantees that if executed it will behave as expected. Vector is a thread-safe class and it is achieved by synchronizing methods which modify the state of Vector, ArrayList is not thread-safe.

What is the difference between throw and throws?

Throw is used to explicitly throw an exception. Throws is used to declare an exception. The throw is followed by an instance. Throws is followed by a class.

What is the base class for Error and Exception?

Throwable

How many ways are there to create a thread?

Two ways to create a thread: 1. You extend a Thread class. 2. You implement a Runnable interface.

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.

How do you create mutable string objects?

Using StringBuffer and StringBuilder classes. These classes provide mutable string objects.

How do you check if two Strings are equal in Java?

Using the equals() method. When we use the == operator, it checks for the value of a String as well as the reference. However we use the equals() method to check if two Strings are equal or not.

How do you convert given string to char array?

Using toCharArray() method.

What are class variables?

Variables that are declared within a class, outside of any method, with the static keyword are called class variables.

What is a Volatile variable in Java?

Volatile is used to indicate that a variables value will be modified by different threads.

Can we have an empty catch block?

We can have an empty catch block, but if we use it in our program, and if any exception occurs at this point then how can we know that exception has occurred at this point? So that we dont use empty catch block.

How to convert a String to a byte array and vice versa?

We can use String getBytes() method to convert a String to a byte array and we can use the String constructor new String(byte[] arr) to convert byte array to a String.

What is Overriding?

When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

What is method overriding?

When a derived class has the same method with the same no. of arguments as its superclass's method, this is called method overriding. It is achieved by inheritance.

What is static import?

When you import static, you can access the static members directly.

Is a final method inherited?

Yes, a final method is inherited but you cannot override it.

Can finally block be used without catch?

Yes, by try block. finally must be followed by either try or catch.

Will a program run when you write static public void instead of public static void?

Yes. It doesn't matter what comes first. You can write static first and then public.


Ensembles d'études connexes

18-9 Organs With Secondary Endocrine Functions

View Set

Personal Fiance Exam 2 Questions

View Set

Assignment: Chapter 11: Managing Organization Design

View Set

Chpt. 2/3 Social Media Marketing Vocabulary Words

View Set