0% found this document useful (0 votes)
55 views29 pages

Java Question

The File class is used to create directories in Java. InputStream is for reading data from sources while OutputStream writes data to destinations. Common ways to read files include FileInputStream with BufferedReader and using Java NIO. FileReader and FileWriter allow reading from and writing to files. Buffered input streams allow reading large chunks of data at once. Serialization converts objects to byte streams for storage or network transmission.

Uploaded by

Sudeep Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views29 pages

Java Question

The File class is used to create directories in Java. InputStream is for reading data from sources while OutputStream writes data to destinations. Common ways to read files include FileInputStream with BufferedReader and using Java NIO. FileReader and FileWriter allow reading from and writing to files. Buffered input streams allow reading large chunks of data at once. Serialization converts objects to byte streams for storage or network transmission.

Uploaded by

Sudeep Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA

1. Which class is used to create a directory in Java?


This is tricky because there is no Directory class, File class is used to create both file and directory in
Java. You can see the linked answer for more details.

2. What is the difference between InputStream and OutputStream in Java?


InputStream is used to read data from sources like File, Socket, or Console, while OutputStream is used
to write data into a destination like a File, Socket, or Console.\

3. What are the different ways of reading a file in Java?


There are several ways to read a file in Java. The most common way is to use the FileInputStream
and BufferedReader classes. However, there are also other ways, such as using the Java NIO
package or the Apache Commons IO library.

4. How do you read from and write to files using Java code?
You can read from and write to files using Java code by using the FileReader and FileWriter classes.
These classes provide methods that allow you to read from and write to files, respectively. In order to
use these classes, you must first import the [Link] package.

5. Can you explain what buffered input streams are?


A buffered input stream is a type of input stream that allows a programmer to read data from a stream
in larger chunks, or buffers. This can be helpful in situations where a programmer wants to read a
large amount of data at once, or when they want to read data from a stream that is slow or unreliable.

6. When should we use serialization? Where is it useful?


Serialization is the process of converting an object into a byte stream. This is useful when we need to
store the state of an object or transmit it over a network. When we serialize an object, we can save it to
a file or send it over the network. The byte stream can then be used to recreate the object on the other
end.

7. What’s the usage of serialVersionUID in context with Serialization?


The serialVersionUID is a unique identifier for a particular version of a class. When a class is serialized,
the serialVersionUID is used to ensure that the receiving party is compatible with the sender’s version of
the class. If the serialVersionUIDs don’t match, then the receiving party will not be able to deserialize
the object.

8. Can you give me some examples of when to use Serialization?


Serialization is the process of converting an object into a byte stream, which can be stored in a file or
transmitted over a network. Some examples of when you might use Serialization would be if you were
creating a backup of an object, or if you were sending an object over a network to another application.

9. What is the difference between deep cloning and shallow cloning?


Deep cloning is the process of creating an entirely new object that is a copy of an existing object. This
new object will have all of the same properties and values as the original object. Shallow cloning, on the
other hand, only creates a new object that references the same data as the original object. So, if you
were to change a property on the new object, it would also change on the original object.

10. What is the significance of implementing Cloneable interface while creating a custom class?
The Cloneable interface is used as a marker interface, which indicates that the class which implements
it is cloneable. This is important because the clone() method is a protected method in the Object class,
and can only be accessed by subclasses of Object. Therefore, if a class wants to be cloneable, it must
implement the Cloneable interface.
JAVA
11. Which methods must be implemented by all subclasses of [Link]?
The methods that must be implemented by all subclasses of [Link] are: clone(), equals(),
finalize(), and hashCode().

12. What do you understand about the Object class in Java?


The Object class is the superclass of all classes in Java. It provides methods for object creation and
manipulation, and is the basis for the Object Oriented programming paradigm in Java.

13. Can you explain what the finalize() method does?


The finalize() method is a method that is called by the garbage collector when it determines that an
object is no longer needed. This method can be used to clean up any resources that the object may be
holding onto.

14. What are immutable objects?


Immutable objects are those objects whose state cannot be changed once they are created. In Java, all
primitive types (such as int, float, double, etc.) and String are immutable.

15. What are anonymous classes in Java? When would you use them?
Anonymous classes are classes that are not given a name. They are often used when you need to
create a class that is only going to be used once and then discarded. For example, if you need to create
a listener for a button press that is only going to be used that one time, you might create an anonymous
class.
16. What will be the output of following code ?

public static void main(String[] args){


String name = null;
File file = new File("/folder", name);
[Link]([Link]());
}
NullPointerException

17. Tell something about BufferedWriter ? What are flush() and close() used for ?
BufferedWriter is temporary source for data [Link] is used to write character data to the
[Link]() is method available in B.W which ensures that all data items are written to file including last
[Link]() is used to closes the character output stream.

18. How and when the Buffer is cleared when using Buffered Writer Classes ?
Buffer is cleared in 2 circumstances, i.e 1. naturally when the buffer is filled and 2. explicitly when the
method flush is called ( for flushing the residual )
Ideally we just need to call flush once at the end of file writing so that the residual content should be
dumped to file.

19. Have you ever tried compressing data using Java ?


Yes, we can use ZipInputStream class for compressing the FileInputstream object.

20. What is a stream and what are the types of Streams and classes of the Streams?
A Stream is an abstraction that either produces or consumes information. There are two types of
Streams :
Byte Streams: Provide a convenient means for handling input and output of bytes.
Character Streams: Provide a convenient means for handling input & output of characters.
JAVA
Byte Streams classes: Are defined by using two abstract classes, namely InputStream and
OutputStream.
Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.

[Link] two files with list of words, write a program to show the common words in both files

import [Link];
import [Link];
import [Link];
import [Link].*;
public class Common {
public static void main(String ar[])throws Exception
{
File f=new File("[Link]");
File f1=new File("[Link]");
[Link]([Link]());
FileInputStream fin = new FileInputStream(f);
FileInputStream fin1 = new FileInputStream(f1);

byte b[]=new byte[10000];


byte b1[]=new byte[10000];
[Link](b);
[Link](b1);
String s1 = new String(b);
String s2 =new String(b1);

String words1[] = [Link]().split(" ");


String words2[] = [Link]().split(" ");
Listlist1 = new ArrayList<>([Link](words1));
Listlist2 = new ArrayList<>([Link](words2));
[Link](list2);
[Link](list1);
}
}

22. Write code to create a folder if it doesn't exist.


File folder = new File(path);
if(![Link]()){
try {
[Link]();

} catch (Exception e) {}
}

[Link] is it important to close files and streams ?


Optimizing Resource utilization. When you open a file using any programming language , that is actually
a request to operating system to access the file. When such a request is made , resources are allocated
by the OS. When you gracefully close those files, those resources are set free.
JAVA
In Java if you don’t close the streams and files, Garbage collection identifies the open files which have
lost the reference and hence will close them.
24. What is the difference between exception and error in Java?
Errors typically happen while an application is running. For instance, Out of Memory Error occurs in
case the JVM runs out of memory. On the other hand, exceptions are mainly caused by the application.
For instance, Null Pointer Exception happens when an app tries to get through a null object.

25. What is unreachable catch block error?


When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to
most general ones. i.e sub classes of Exception must come first and super classes later. If you keep
super classes first and sub classes later, compiler will show unreachable catch block error.

26. What are run time exceptions in Java. Give example?


The exceptions which occur at run time are called as run time exceptions. These exceptions are
unknown to compiler. All sub classes of [Link] and [Link] are run time
exceptions. These exceptions are unchecked type of exceptions. For example,
NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOfBoundException,
StackOverflowError etc.

27. What is OutOfMemoryError in Java?


OutOfMemoryError is the sub class of [Link] which occurs when JVM runs out of memory.

28. What are checked and unchecked exceptions in java?


Checked exceptions are the exceptions which are known to compiler. These exceptions are checked at
compile time only. Hence the name checked exceptions. These exceptions are also called compile time
exceptions. Because, these exceptions will be known during compile time.

Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions
occur only at run time. These exceptions are also called as run time exceptions. All sub classes of
[Link] and [Link] are unchecked exceptions.

29. What is ClassCastException in Java?


ClassCastException is a RunTimeException which occurs when JVM unable to cast an object of one
type to another type.

30. What is StackOverflowError in Java?


StackOverflowError is an error which is thrown by the JVM when stack overflows.

31. Can we override a super class method which is throwing an unchecked exception with
checked exception in the sub class?
No. If a super class method is throwing an unchecked exception, then it can be overridden in the sub
class with same exception or any other unchecked exceptions but can not be overridden with checked
exceptions.

32. Give some examples to checked exceptions?


ClassNotFoundException, SQLException, IOException

33. Do you know try-with-resources blocks? Why do we use them? When they are introduced?
JAVA
Try-with-resources blocks are introduced from Java 7 to auto-close the resources like File I/O streams,
Database connection, network connection etc… used in the try block. You need not to close the
resources explicitly in your code. Try-with-resources implicitly closes all the resources used in the try
block.

[Link] Exceptions In Java :


Checked exceptions are the exceptions which are checked during compilation itself. They are also
called compile time exceptions. Compiler is aware of these exceptions and immediately throws the error
wherever it sees the statements which may throw checked exceptions.

All sub classes of [Link] (except sub classes of RunTimeException) are checked
exceptions. For example, FileNotFoundException, IOException, SQLException,
ClassNotFoundException etc…

Below code throws ClassNotFoundException which is a checked exception. But it is not handled, so it
gives compile time error.

public class CheckedException


{
public static void main(String[] args)
{
[Link]("AnyClassName");

//Compile time error because


//above statement throws ClassNotFoundException which is a checked exception
//this statement must be enclosed within try-catch block or declare main method with throws clause
}
}

35. What is a functional interface?


An Interface that contains exactly one abstract method is known as a functional interface. It can have
any number of default, static methods but can contain only one abstract method. It can also declare the
methods of the object class.
Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces. A functional
interface can extend another interface only when it does not have any abstract method.
Java 8 provides predefined functional interfaces to deal with functional programming by using lambda
and method references.

For example:
interface Printable {
void print(String msg);
}

public class JLEExampleSingleParameter {

public static void main(String[] args) {


// with lambda expression
Printable withLambda = (msg) -> [Link](msg);
[Link](" Print message to console....");
JAVA
}
}

36. Is it possible to define our own Functional Interface? What is @FunctionalInterface? What
are the rules to define a Functional Interface?
Yes, it is possible to define our own Functional Interfaces. We use Java 8 provides the
@FunctionalInterface annotation to mark an interface as a Functional Interface.
If you use @FunctionalInterface annotation then the compiler will verify if the interface actually contains
just one abstract method or not. It’s like the @Override annotation, which prevents you from accidental
errors.

We need to follow these rules to define a Functional Interface:


Define an interface with one and only one abstract method.
We cannot define more than one abstract method.
Use @FunctionalInterface annotation in the interface definition.
We can define any number of other methods like default methods, static methods.
If your functional interface meets the above rules then you no need to use @FunctionalInterface
annotation because the compiler will treat it as a functional interface.

The below example illustrates defining our own Functional Interface:

Let's create a Sayable interface annotated with @FunctionalInterface annotation.

@FunctionalInterface
interface Sayable{
void say(String msg); // abstract method
}

Let's demonstrate a custom functional interface via the main() method.


public class FunctionalInterfacesExample {

public static void main(String[] args) {

Sayable sayable = (msg) -> {


[Link](msg);
};
[Link]("Say something ..");
}
}

.
37. Name some of the functional interfaces in the standard library
In Java 8, there are a lot of functional interfaces are introduced in the [Link] package and the
more common ones include but are not limited to:

Function – it takes one argument and returns a result


Consumer – it takes one argument and returns no result (represents a side effect)
Supplier – it takes no argument and returns a result
Predicate – it takes one argument and returns a boolean
JAVA
BiFunction – it takes two arguments and returns a result
BiConsumer - it takes two (reference type) input arguments and returns no result
BinaryOperator – it is similar to a BiFunction, taking two arguments and returning a result. The two
arguments and the result are all of the same types
UnaryOperator – it is similar to a Function, taking a single argument and returning a result of the same
type
Runnable: use to execute the instances of a class over another thread with no arguments and no return
value.
Callable: use to execute the instances of a class over another thread with no arguments and it either
returns a value or throws an exception.
Comparator: use to sort different objects in a user-defined order
Comparable: use to sort objects in the natural sort order

38. What Is the Difference Between a Normal and Functional Interface in Java?
The normal interface in Java can contain any number of abstract methods, while the functional interface
can only contain just one abstract method.
We need to follow these rules to define a Functional Interface:
Define an interface with one and only one abstract method.
We cannot define more than one abstract method.
Use @FunctionalInterface annotation in the interface definition.
We can define any number of other methods like default methods, static methods.

39. What is a Predicate interface?


The Predicate is a functional interface that can be used as an assignment target for a lambda
expression.
The Predicate interface represents an operation that takes a single input and returns a boolean value.
This is the internal implementation of the Predicate interface:

@FunctionalInterface
public interface Predicate<T> {

/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
T – Type of the input to the predicate
Example:

Predicate < Integer > predicate = (t) -> {


if (t % 2 == 0) {
return true;
} else {
return false;
}
JAVA
};

[Link]([Link](10));
Output:
true

39. What is the Consumer interface?


A Consumer is a functional interface in JDK 8, which represents an operation that accepts a single input
argument and returns no result.

This is the internal implementation of the Consumer interface:


@FunctionalInterface
public interface Consumer < T > {

/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
Example:

Consumer < String > consumer = (t) -> [Link](t);


[Link]("Ramesh");
Output:
Ramesh

40. What is the Supplier interface?


The Supplier is a functional interface that represents an operation that takes no argument and returns a
result.

This is the internal implementation of the Supplier interface:


@FunctionalInterface
public interface Supplier<T> {
T get();
}
Example:
Supplier < LocalDateTime > supplier = () -> [Link]();
[Link]([Link]());
Output:
2020-04-30T[Link].628

41. What is BiFunction interface?


The BiFunction interface is a functional interface that represents a function that takes two arguments of
different types and produces a result of another type.
JAVA
This is the internal implementation of the BiFunction interface:
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T t, U u); // Other default and static methods
// ...
}
Example:

// And with a lambda expression:


BiFunction < Integer, Integer, Integer > biFunction = (t, u) -> (t + u);

BiFunction < Integer, Integer, Integer > substraction = (t, u) -> (t - u);

BiFunction < Integer, Integer, Integer > multiplication = (t, u) -> (t * u);

BiFunction < Integer, Integer, Integer > division = (t, u) -> (t / u);

[Link]([Link](10, 20));
[Link]([Link](200, 100));

[Link]([Link](200, 100));

[Link]([Link](200, 100));
Output:
30
900
20000
2

42. What are Marker Interfaces ? Name few Java marker interfaces ?

These are the interfaces which have no declared methods.


Serializable and cloneable are marker interfaces.

43. Why Garbage Collection is necessary in Java?


In programming languages such as C and C++, the developer programmatically reclaims the space that
is allocated to an object in the memory. In Java programming, the user is not responsible for managing
the space memory used by the objects. In JVM, a garbage collection routine is added as its part, which
is responsible for identifying and deleting objects that are no longer in use in memory.

44. What is the drawback to Garbage Collection?


The main drawback of Garbage Collection is that it freezes all those threads which are currently active
at the time of occurring memory recovery phase. The garbage collection algorithms take time in
seconds or minutes to run, and due to this, garbage collection routines can't be scheduled.

45. Explain PermGen space in Java.


JAVA
The internal representation of the Java classes held by JVM is included in the PermGen space.
PermGen space contains garbage data collected in the same way as the heap's other parts (Young
generation and Old generation) collected.

46. Explain the difference between a minor, major and full garbage collection.
There is no official documentation or specification which can define the difference between major, minor
and full garbage collection. We can define each one of them in the following way:

Full garbage collection works on the tenured space.


Major garbage collection works on the survivor space.
Minor garbage collection works on the Eden space to perform a mark-and-sweep routine.

47. How will you identify major and minor garbage collections in Java?
We can identify the major and minor garbage collections based on the output. If the garbage collection
logging is enabled by using -XX:PrintGCDetails or verbose:gc, the minor collection prints "GC", whereas
the major collection prints "Full GC".

Explain the use of the Finalize() method of the garbage collector.


The Finalize() method is called by the garbage collector before collecting any object that is eligible for
the garbage collector. The Finalize() method is used to get the last chance to object to cleaning and free
remaining resource.

48. Can we force the Garbage collector to run at any time?


No, we cannot force Garbage collection in Java. Although, we can request it by calling [Link]() or its
cousin [Link]().get(). It's not guaranteed that GC will run immediately as a result of
calling these methods.

[Link] does a Java object become available for garbage collection?


An object becomes available for garbage collection when:

It is marked as null.
It goes out of scope.
Within an application, if it is no longer referenced by any non-null objects.

[Link] do you mean by mark-and-sweep?


Mark and Sweep are the two states of garbage collection. In the Mark stage, JVM identifies whether an
object is still needed or not. The object is marked for garbage collection when the object is not needed.

In the Sweep stage, JVM performs memory reclamation and garbage collection algorithms.

51. What is a memory leak, and how does it affect garbage collection?
A situation where a garbage collector fails to identify and remove an unused object from memory is
referred to as a memory leak.

The memory consumption is increased by the memory leak. After increasing the memory consumption,
JVM is forced to clear more space for new objects. Mark and Sweep stages of garbage collection run
more frequently. It free up less memory each time these stages run until there is no heap space left.
JAVA
[Link] is a daemon thread? Is GC a daemon thread?
A thread which runs behind the application for performing background operations is referred to as a
daemon thread.

Yes, GC is a daemon thread which starts by JVM.

53. GC Implementations
JVM has five types of GC implementations:

Serial Garbage Collector


Parallel Garbage Collector
CMS Garbage Collector
G1 Garbage Collector
Z Garbage Collector

54. Serial Garbage Collector


This is the simplest GC implementation, as it basically works with a single thread. As a result, this GC
implementation freezes all application threads when it runs. Therefore, it's not a good idea to use it in
multi-threaded applications, like server environments.

However, there was an excellent talk given by Twitter engineers at QCon 2012 about the performance
of Serial Garbage Collector, which is a good way to understand this collector better.

The Serial GC is the garbage collector of choice for most applications that don't have small pause time
requirements and run on client-style machines. To enable Serial Garbage Collector, we can use the
following argument:

java -XX:+UseSerialGC -jar [Link]

55. Parallel Garbage Collector


It's the default GC of the JVM, and sometimes called Throughput Collectors. Unlike Serial Garbage
Collector, it uses multiple threads for managing heap space, but it also freezes other application threads
while performing GC.

If we use this GC, we can specify maximum garbage collection threads and pause time, throughput, and
footprint (heap size).

The numbers of garbage collector threads can be controlled with the command-line option -
XX:ParallelGCThreads=<N>.

The maximum pause time goal (gap [in milliseconds] between two GC) is specified with the command-
line option -XX:MaxGCPauseMillis=<N>.

The time spent doing garbage collection versus the time spent outside of garbage collection is called the
maximum throughput target and can be specified by the command-line option -XX:GCTimeRatio=<N>.

The maximum heap footprint (the amount of heap memory that a program requires while running) is
specified using the option -Xmx<N>.
JAVA
To enable Parallel Garbage Collector, we can use the following argument:

java -XX:+UseParallelGC -jar [Link]

56. CMS Garbage Collector


The Concurrent Mark Sweep (CMS) implementation uses multiple garbage collector threads for garbage
collection. It's designed for applications that prefer shorter garbage collection pauses, and can afford to
share processor resources with the garbage collector while the application is running.

Simply put, applications using this type of GC respond slower on average, but don't stop responding to
perform garbage collection.

A quick point to note here is that since this GC is concurrent, an invocation of explicit garbage collection,
such as using [Link]() while the concurrent process is working, will result in Concurrent Mode
Failure / Interruption.

If more than 98% of the total time is spent in CMS garbage collection, and less than 2% of the heap is
recovered, then an OutOfMemoryError is thrown by the CMS collector. If necessary, we can disable this
feature by adding the option -XX:-UseGCOverheadLimit to the command line.

This collector also has a mode known as an incremental mode, which is being deprecated in Java SE 8
and may be removed in a future major release.

To enable the CMS Garbage Collector, we can use the following flag:

java -XX:+UseParNewGC -jar [Link]

57. G1 Garbage Collector


G1 (Garbage First) Garbage Collector is designed for applications running on multi-processor machines
with large memory space. It's available from the JDK7 Update 4 and in later releases.

G1 collector will replace the CMS collector, since it's more performance efficient.

Unlike other collectors, the G1 collector partitions the heap into a set of equal-sized heap regions, each
a contiguous range of virtual memory. When performing garbage collections, G1 shows a concurrent
global marking phase (i.e. phase 1, known as Marking) to determine the liveness of objects throughout
the heap.

After the mark phase is complete, G1 knows which regions are mostly empty. It collects in these areas
first, which usually yields a significant amount of free space (i.e. phase 2, known as Sweeping). That's
why this method of garbage collection is called Garbage-First.

To enable the G1 Garbage Collector, we can use the following argument:

java -XX:+UseG1GC -jar [Link]

58. What distinguishes a collection from a stream?


A Collection contains its elements, whereas a Stream does not, and this is the primary distinction
between the two types of data structures. Unlike other views, Stream operates on a view whose
JAVA
elements are kept in a collection or array, but any changes made to Stream do not affect the original
collection.

59. What is the function map() used for? You use it, why?
In Java, functional map operations are performed using the map() function. This indicates that it can
apply a function to change one type of object into another.
Use map(), for instance, to change a List of String into a List of Integers if you have one already.
It will apply to all elements of the List and give you a List of Integer if you only supply a function to
convert String to Integer, such as parseInt() or map(). The map can change one object into another.

60. What is the function flatmap() used for? Why do you require it?
The map function has been expanded with the flatmap function. It can flatten an object in addition to
changing it into another.
If you already have a list of lists but wish to integrate them all into a single list, for instance. You can
flatten using flatMap() in this situation. The map() function can be used to transform an object at the
same time.
class GFG {

// Driver code
public static void main(String[] args)
{

// Creating a List of Strings


List<String> list = [Link]("Geeks", "GFG",
"GeeksforGeeks", "gfg");

// Using Stream flatMap(Function mapper)


[Link]().flatMap(str ->
[Link]([Link](2))).
forEach([Link]::println);
}
}

String[][] array = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};

// Java 8
String[] result = [Link](array) // Stream<String[]>
.flatMap(Stream::of) // Stream<String>
.toArray(String[]::new); // [a, b, c, d, e, f]

for (String s : result) {


[Link](s);
}

[Link] "Stream is lazy," what do you mean?


When we state that a stream is lazy, we mean that the majority of its methods, which are described in
the [Link]. [Link] classes, will not function if they are simply added to the stream pipeline.
JAVA
They only function when a terminal method on the Stream is called, and rather than searching through
the entire collection of data, and they stop as soon as they locate the data they are looking for.

62. To determine the lowest and greatest number in a stream, write a Java 8 program.
public class Java8{
public static void main(String args[]) {

Integer highest = [Link](1, 2, 3, 77, 6, 5)


.max([Link](Integer::valueOf))
.get();

/* We have used max() method with [Link]() method


to compare and find the highest number
*/

Integer lowest = [Link](1, 2, 3, 77, 6, 5)


.min([Link](Integer::valueOf))
.get();

/* We have used max() method with [Link]() method


to compare and find the highest number
*/

[Link]("The highest number is: " + highest);


[Link]("The lowest number is: " + lowest);
}
}

[Link] does Java 8's MetaSpace mean?


A new feature to store classes was added in Java 8. In Java 8, there is a place called MetaSpace where
all the classes are kept. The PermGen has been superseded by MetaSpace.

The Java Virtual Machine used PermGen to store the classes before Java 7. Java 8 replaced PermGen
with MetaSpace because MetaSpace is dynamic and has no size restrictions. It can also increase
dynamically.

64. What distinguishes a limit from a skip?


The Stream of the desired size is returned using the limit() method. As an illustration, if you mentioned
limit(5), there would be 5 output elements.

65. filter
public class Tester {
public static void main(String[] args){
List<String> lines = [Link]("java", "c", "python");

List<String> result = [Link]() // convert list to stream


.filter(line -> !"c".equals(line)) // we dont like c
.collect([Link]()); // collect the output and convert streams to a List
JAVA
[Link]([Link]::println);
}
}

Output:

java
python

66. map
public class Main
{
public static void main(String[] args)
{
List<String> listOfStrings = [Link]("1", "2", "3", "4", "5");

List<Integer> listOfIntegers = [Link]()


.map(Integer::valueOf)
.collect([Link]());

[Link](listOfIntegers);
}
}
Output:

[1, 2, 3, 4, 5]

67. distinct
public class Main {
public static void main(String[] args)
{
List<String> stringList = new ArrayList<>();

[Link]("one");
[Link]("two");
[Link]("three");
[Link]("one");

Stream<String> stream = [Link]();

List<String> distinctStrings = stream


.distinct()
.collect([Link]());

[Link](distinctStrings);
}
}
JAVA
Output:

[one, two, three]

public class Main {


68. limit
public static void main(String[] args)
{
List<String> stringList = new ArrayList<>();

[Link]("one");
[Link]("two");
[Link]("three");
[Link]("one");

Stream<String> stream = [Link]();

[Link](2)
.forEach( element -> { [Link](element); });
}
}
Output:

one
two

69. peek
public class Main {
public static void main(String[] args)
{
[Link]("one", "two", "three", "four")
.filter(e -> [Link]() > 3)
.peek(e -> [Link]("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> [Link]("Mapped value: " + e))
.collect([Link]());
}
}
Output:

Filtered value: three


Mapped value: THREE
Filtered value: four
Mapped value: FOUR

70. skip
class gfg{

// Function to skip the elements of stream upto given range, i.e, 3


JAVA
public static Stream<String> skip_func(Stream<String> ss, int range){
return [Link](range);
}

// Driver code
public static void main(String[] args){

// list to save stream of strings


List<String> arr = new ArrayList<>();

[Link]("geeks");
[Link]("for");
[Link]("geeks");
[Link]("computer");
[Link]("science");

Stream<String> str = [Link]();

// calling function to skip the elements to range 3


Stream<String> sk = skip_func(str,3);
[Link]([Link]::println);
}
}
Output :

computer
science

71. sorted
List<Integer> list = [Link](2, 4, 1, 3, 7, 5, 9, 6, 8);

List<Integer> sortedList = [Link]()


.sorted()
.collect([Link]());

[Link](sortedList);

[Link] is the difference between Iterator and ListIterator?


Iterator traverses the elements in the forward direction only whereas ListIterator traverses the elements
into forward and backward direction.

[Link] is the difference between Iterator and Enumeration?


No. Iterator Enumeration
The Iterator can traverse legacy and non-legacy elements.------Enumeration can traverse only legacy
elements.

[Link] is the difference between List and Set?


JAVA
The List and Set both extend the collection interface. However, there are some differences between the
both which are listed below.

The List can contain duplicate elements whereas -----Set includes unique items.

[Link] is the difference between Comparable and Comparator?


Comparable provides only one sort of sequence----The Comparator provides multiple sorts of
sequences.

[Link] we override equals() method?


The equals method is used to check whether two objects are the same or not. It needs to be overridden
if we want to check the objects based on the property.

For example, Employee is a class that has 3 data members: id, name, and salary. However, we want to
check the equality of employee object by the salary. Then, we need to override the equals() method.

[Link] to synchronize List, Set and Map elements?


Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

public static List synchronizedList(List l){}


public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

[Link] is hash-collision in Hashtable and how it is handled in Java?


Two different keys with the same hash value are known as hash-collision. Two separate entries will be
kept in a single hash bucket to avoid the collision. There are two ways to avoid hash-collision.

Separate Chaining
Open Addressing

[Link] do you understand by fail-fast?


The Iterator in java which immediately throws ConcurrentmodificationException, if any structural
modification occurs in, is called as a Fail-fast iterator. Fail-fats iterator does not require any extra space
in memory.

[Link] is the difference between the length of an Array and size of ArrayList?
The length of an array can be obtained using the property of length whereas ArrayList does not support
length property, but we can use size() method to get the number of objects in the list.
How to convert ArrayList to Array and Array to ArrayList?
We can convert an Array to ArrayList by using the asList() method of Arrays class. asList() method is
the static method of Arrays class and accepts the List object. Consider the following syntax:

[Link](item)

[Link] to convert ArrayList to Array and Array to ArrayList?


JAVA
We can convert an Array to ArrayList by using the asList() method of Arrays class. asList() method is
the static method of Arrays class and accepts the List object. Consider the following syntax:

[Link](item)

[Link] to use ArrayList and LinkedList?


LinkedLists are better to use for the update operations whereas ArrayLists are better to use for the
search operations.

[Link] Of Comaprable And Comparator


class Movie implements Comparable<Movie>
{
private double rating;
private String name;
private int year;

// Used to sort movies by year


public int compareTo(Movie m)
{
return [Link] - [Link];
}

// Constructor
public Movie(String nm, double rt, int yr)
{
[Link] = nm;
[Link] = rt;
[Link] = yr;
}

// Getter methods for accessing private data


public double getRating() { return rating; }
public String getName() { return name; }
public int getYear() { return year; }
}

// Driver class
class Main
{
public static void main(String[] args)
{
ArrayList<Movie> list = new ArrayList<Movie>();
[Link](new Movie("Force Awakens", 8.3, 2015));
[Link](new Movie("Star Wars", 8.7, 1977));
[Link](new Movie("Empire Strikes Back", 8.8, 1980));
[Link](new Movie("Return of the Jedi", 8.4, 1983));

[Link](list);
JAVA
[Link]("Movies after sorting : ");
for (Movie movie: list)
{
[Link]([Link]() + " " +
[Link]() + " " +
[Link]());
}
}
}
Output:

Movies after sorting :

Star Wars 8.7 1977

Empire Strikes Back 8.8 1980

Return of the Jedi 8.4 1983

Force Awakens 8.3 2015

class Movie implements Comparable<Movie>


{
private double rating;
private String name;
private int year;

// Used to sort movies by year


public int compareTo(Movie m)
{
return [Link] - [Link];
}

// Constructor
public Movie(String nm, double rt, int yr)
{
[Link] = nm;
[Link] = rt;
[Link] = yr;
}

// Getter methods for accessing private data


public double getRating() { return rating; }
public String getName() { return name; }
public int getYear() { return year; }
JAVA
}

// Class to compare Movies by ratings


class RatingCompare implements Comparator<Movie>
{
public int compare(Movie m1, Movie m2)
{
if ([Link]() < [Link]()) return -1;
if ([Link]() > [Link]()) return 1;
else return 0;
}
}

// Class to compare Movies by name


class NameCompare implements Comparator<Movie>
{
public int compare(Movie m1, Movie m2)
{
return [Link]().compareTo([Link]());
}
}

// Driver class
class Main
{
public static void main(String[] args)
{
ArrayList<Movie> list = new ArrayList<Movie>();
[Link](new Movie("Force Awakens", 8.3, 2015));
[Link](new Movie("Star Wars", 8.7, 1977));
[Link](new Movie("Empire Strikes Back", 8.8, 1980));
[Link](new Movie("Return of the Jedi", 8.4, 1983));

// Sort by rating : (1) Create an object of ratingCompare


// (2) Call [Link]
// (3) Print Sorted list
[Link]("Sorted by rating");
RatingCompare ratingCompare = new RatingCompare();
[Link](list, ratingCompare);
for (Movie movie: list)
[Link]([Link]() + " " +
[Link]() + " " +
[Link]());

// Call overloaded sort method with RatingCompare


// (Same three steps as above)
[Link]("\nSorted by name");
JAVA
NameCompare nameCompare = new NameCompare();
[Link](list, nameCompare);
for (Movie movie: list)
[Link]([Link]() + " " +
[Link]() + " " +
[Link]());

// Uses Comparable to sort by year


[Link]("\nSorted by year");
[Link](list);
for (Movie movie: list)
[Link]([Link]() + " " +
[Link]() + " " +
[Link]()+" ");
}
}
Output :

Sorted by rating
8.3 Force Awakens 2015
8.4 Return of the Jedi 1983
8.7 Star Wars 1977
8.8 Empire Strikes Back 1980

Sorted by name
Empire Strikes Back 8.8 1980
Force Awakens 8.3 2015
Return of the Jedi 8.4 1983
Star Wars 8.7 1977

Sorted by year
1977 8.7 Star Wars
1980 8.8 Empire Strikes Back
1983 8.4 Return of the Jedi
2015 8.3 Force Awakens

[Link] Hashmap works Internally


[Link](new Key("sachin"), 30);
Calculate hashCode of Key {“sachin”}. It will be generated as 115.
Calculate index by using index method it will be 3.
Create a node object as :

85. What do you understand by RESTful Web Services?


RESTful web services are services that follow REST architecture. REST stands for Representational
State Transfer and uses HTTP protocol (web protocol) for implementation. These services are
lightweight, provide maintainability, scalability, support communication among multiple applications that
are developed using different programming languages. They provide means of accessing resources
present at server required for the client via the web browser by means of request headers, request
body, response body, status codes, etc.
JAVA
86. What is a REST Resource?
Every content in the REST architecture is considered a resource. The resource is analogous to the
object in the object-oriented programming world. They can either be represented as text files, HTML
pages, images, or any other dynamic data.

The REST Server provides access to these resources whereas the REST client consumes (accesses
and modifies) these resources. Every resource is identified globally by means of a URI.

87. What is URI?


Uniform Resource Identifier is the full form of URI which is used for identifying each resource of the
REST architecture. URI is of the format:

88. What are the features of RESTful Web Services?


Every RESTful web service has the following features:

The service is based on the Client-Server model.


The service uses HTTP Protocol for fetching data/resources, query execution, or any other functions.
The medium of communication between the client and server is called “Messaging”.
Resources are accessible to the service by means of URIs.
It follows the statelessness concept where the client request and response are not dependent on others
and thereby provides total assurance of getting the required data.
These services also use the concept of caching to minimize the server calls for the same type of
repeated requests.
These services can also use SOAP services as implementation protocol to REST architectural pattern.
5. What is the concept of statelessness in REST?
The REST architecture is designed in such a way that the client state is not maintained on the server.
This is known as statelessness. The context is provided by the client to the server using which the
server processes the client’s request. The session on the server is identified by the session identifier
sent by the client.

89. What are HTTP Status codes?


These are the standard codes that refer to the predefined status of the task at the server. Following are
the status codes formats available:

1xx - represents informational responses


2xx - represents successful responses
3xx - represents redirects
4xx - represents client errors
5xx - represents server errors
Most commonly used status codes are:

200 - success/OK
201 - CREATED - used in POST or PUT methods.
304 - NOT MODIFIED - used in conditional GET requests to reduce the bandwidth use of the network.
Here, the body of the response sent should be empty.
400 - BAD REQUEST - This can be due to validation errors or missing input data.
401- UNAUTHORIZED - This is returned when there is no valid authentication credentials sent along
with the request.
JAVA
403 - FORBIDDEN - sent when the user does not have access (or is forbidden) to the resource.
404 - NOT FOUND - Resource method is not available.
500 - INTERNAL SERVER ERROR - server threw some exceptions while running the method.
502 - BAD GATEWAY - Server was not able to get the response from another upstream server.

90. What are the HTTP Methods?


HTTP Methods are also known as HTTP Verbs. They form a major portion of uniform interface
restriction followed by the REST that specifies what action has to be followed to get the requested
resource. Below are some examples of HTTP Methods:

GET: This is used for fetching details from the server and is basically a read-only operation.
POST: This method is used for the creation of new resources on the server.
PUT: This method is used to update the old/existing resource on the server or to replace the resource.
DELETE: This method is used to delete the resource on the server.
PATCH: This is used for modifying the resource on the server.
OPTIONS: This fetches the list of supported options of resources present on the server.
The POST, GET, PUT, DELETE corresponds to the create, read, update, delete operations which are
most commonly called CRUD Operations.

91. Differentiate between SOAP and REST?


SOAP - Simple Object Access Protocol --------- REST - Representational State Transfer
SOAP is a protocol used to implement web services.----REST is an architectural design pattern for
developing web services
SOAP cannot use REST as it is a protocol.----- REST architecture can have SOAP protocol as part of
the implementation.
SOAP specifies standards that are meant to be followed strictly------------REST defines standards but
they need not be strictly followed.
SOAP client is more tightly coupled to the server which is similar to desktop applications having strict
contracts.------ The REST client is more flexible like a browser and does not depend on how the server is
developed unless it follows the protocols required for establishing communication.
SOAP supports only XML transmission between the client and the server.---------REST supports data of
multiple formats like XML, JSON, MIME, Text, etc.
SOAP reads are not cacheable.----------REST read requests can be cached.
SOAP uses service interfaces for exposing the resource logic----REST uses URI to expose the resource
logic.
SOAP is slower.----REST is faster.
Since SOAP is a protocol, it defines its own security measures.---REST only inherits the security
measures based on what protocol it uses for the implementation.
SOAP is not commonly preferred, but they are used in cases which require stateful data transfer and
more reliability.----REST is commonly preferred by developers these days as it provides more scalability
and maintainability.

92. What are Idempotent methods? How is it relevant in RESTful web services domain?
The meaning of idempotent is that even after calling a single request multiple times, the outcome of the
request should be the same. While designing REST APIs, we need to keep in mind to develop
idempotent APIs. This is because the consumers can write client-side code which can result in duplicate
requests intentionally or not. Hence, fault-tolerant APIs need to be designed so that they do not result in
erroneous responses.
JAVA
Idempotent methods ensure that the responses to a request if called once or ten times or more than that
remain the same. This is equivalent to adding any number with 0.
REST provides idempotent methods automatically. GET, PUT, DELETE, HEAD, OPTIONS, and TRACE
are the idempotent HTTP methods. POST is not idempotent.
POST is not idempotent because POST APIs are usually used for creating a new resource on the
server. While calling POST methods N times, there will be N new resources. This does not result in the
same outcome at a time.

93. Categories Java Design patterns?


Based on problem analysis, we can categorize design patterns into the following categories.

Creational patterns
Play Video

Factory method/Template
Abstract Factory
Builder
Prototype
Singleton
Structural patterns

Adapter
Bridge
Filter
Composite
Decorator
Facade
Flyweight
Proxy
Behavioral patterns

Interpreter
Template method/ pattern
Chain of responsibility
Command pattern
Iterator pattern
Strategy pattern
Visitor pattern
J2EE patterns

MVC Pattern
Data Access Object pattern
Front controller pattern
Intercepting filter pattern
Transfer object pattern

94. What are the Creational Patterns?


JAVA
Creational design patterns are related to the way of creating objects. Creational design patterns are
used when a decision is made at the time of instantiation of a class.

EmpRecord e1=new EmpRecord();


Since new keyword is used to create an object in Java, So, here we are creating the instance using the
new keyword. In some cases, the nature of the object must be changed according to the nature of the
program. In such cases, we should use the creational design patterns to provide a more general and
flexible approach.

95. What Is Factory Pattern?


It is the most used design pattern in Java.
These design patterns belong to the Creational Pattern as this pattern provides one of the best ways to
create an object.
In the Factory pattern, we don't expose the creation logic to the client and refer the created object using
a standard interface.
Factory Pattern allows the sub-classes to choose the type of objects to create.
The Factory Pattern is also known as Virtual Constructor.
6) What Is Abstract Factory Pattern?
Abstract Factory Pattern states that define an abstract class or interface for creating families of related
objects but without specifying their concrete sub-classes. That means Abstract Factory allowed a class
to return a factory of classes. That is why the Abstract Factory Pattern is one level higher than the
Factory Pattern.

Abstract Factory patterns work around superclasses, which creates other classes.
The Abstract Factory Pattern comes under Creational Pattern as this pattern provides one of the best
ways to create an object.
In the Abstract Factory pattern, an interface is liable for creating a factory of related objects without
explicitly identifying their classes.
Each generated factory can give the objects according to the Factory pattern.
7) Explain Structural Patterns in Java?
Structural patterns are used to provide solutions and efficient standards regarding class compositions
and object structures. They depend on the concept of inheritance and interfaces to allow multiple
objects or classes to work together and form a single working whole.

Structural design patterns are responsible for how classes and objects can be composed to form larger
structures.

96. Explain the Singleton pattern?


Singleton pattern in Java is a pattern which allows a single instance within an application. One good
example of the singleton pattern is [Link].

Singleton Pattern states that define a class that has only one instance and provides a global point of
access to it.

In other words, it is the responsibility of the class that only a single instance should be created, and all
other classes can use a single object.

97. Illustrate the uses of Adapter Patterns?


JAVA
It is used in the following cases:

When an object requires to utilize an existing class with an incompatible interface.


In case we want to create a reusable class that collaborates with classes which don't have compatible
interfaces.

98. Can you write Thread-safe Singleton in Java?


There are many ways to write a Thread-safe singleton in Java.

Thread-safe Singleton can be written by writing singleton using double-checked locking.


Another way is, by using static Singleton instance initialized during class loading.
By using Java enum to create a thread-safe singleton, this is the most straightforward way.

99. Explain some different type of proxies?


There are many cases where the proxy pattern is beneficial. Let's have a look at some different proxies.

Protection proxy

It controls access to the real subject based on some condition.

Virtual proxies

Virtual proxies are used to instantiate the expensive object. The proxy manages the lifetime of the real
subject in the implementation.

It decides the need for the instance creation and when to reuse it. Virtual proxies optimize performance.

Caching proxies

Caching proxies are used to cache expensive calls to the real subject. There are many caching
strategies that the proxy can use.

Some of them are read-through, write-through, cache-aside, and time-based. The caching proxies are
used for enhancing performance.

Remote proxies

Remote proxies are used in distributed object communication. The remote proxy causes execution on
the remote object by invoking a local object method.

Smart proxies

Smart proxies are used to implement log calls and reference counting to the object.

100. What are the MVC patterns?


This pattern is one of the most-used patterns from J2EE Design pattern category. It is quite similar to
the concept of Model-View-Controller. The abbreviation MVC is taken from the Model-view-controller
concept.
JAVA
Models are objects, used as blueprints for all of the objects that will be used in the application.

Views contain the presentational aspect of the data and information located in the models.

Controllers control both model and view as they serve as a connection between the two objects. The
controller plays the role of an interface between View and Model and also intercepts all the incoming
requests.

[Link] Of singleton
class Singleton {
// Static variable reference of single_instance
// of type Singleton
private static Singleton single_instance = null;

// Declaring a variable of type String


public String s;

// Constructor
// Here we will be creating private constructor
// restricted to this class itself
private Singleton()
{
s = "Hello I am a string part of Singleton class";
}

// Static method
// Static method to create instance of Singleton class
public static synchronized Singleton getInstance()
{
if (single_instance == null)
single_instance = new Singleton();

return single_instance;
}
}

// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Instantiating Singleton class with variable x
Singleton x = [Link]();

// Instantiating Singleton class with variable y


JAVA
Singleton y = [Link]();

// Instantiating Singleton class with variable z


Singleton z = [Link]();

// Printing the hash code for above variable as


// declared
[Link]("Hashcode of x is "
+ [Link]());
[Link]("Hashcode of y is "
+ [Link]());
[Link]("Hashcode of z is "
+ [Link]());

// Condition check
if (x == y && y == z) {

// Print statement
[Link](
"Three objects point to the same memory location on the heap i.e, to the same object");
}

else {
// Print statement
[Link](
"Three objects DO NOT point to the same memory location on the heap");
}
}
}

You might also like