Interview Material

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

1. Which of the following matches regexp /[a-z]+[\.\?!

]/
1) battle!
2) Hot
3) green
Script Using MongoDB4) swamping.
5) jump up.
6) undulate?
7) is.?
Ans: 1,4,6

2. Which of the following pair of regular expression are not equivalent?


a) 1(01)* and (10)*1
b) x(xx)* and (xx)*x
c) (ab)* and a*b*
d) x+ and x*x+
Ans: c
3. Which of the following matches regexp /[a-zA-Z]*[^,]=/
1) Butt=
2) BotHEr,=
3) Ample
4) ok Other.=
Ans: 1,5,6

4. What is sudo? What is su? Explain how they differ. What does sudo su do?
Ans: The su command switches to the super user – or root user – when you execute it with
no additional options. You’ll have to enter the root account’s password. This isn’t all the su
command does, though – you can use it to switch to any user account. If you execute the su
bob command, you’ll be prompted to enter Bob’s password and the shell will switch to Bob’s
user account.

Once you’re done running commands in the root shell, you should type exit to leave the root
shell and go back to limited-privileges mode.

Sudo runs a single command with root privileges. When you execute sudo command, the
system prompts you for your current user account’s password before running command as the
root user. By default, Ubuntu remembers the password for fifteen minutes and won’t ask for a
password again until the fifteen minutes are up.

sudo su

means run the command su as sudo which means as root. Here the system will ask you for
your password since you are a sudoer. So when you offer your password then you are now
working with root ability so when you run now su by the time you are using root abilities so
you don't need any password. It's same as if you are a root then su to any other user will not
ask for password because you are a root.

when you just run the command su the system is not dealing with you that you are a sudo
and deals with you as a normal user to it will ask for the root password since su means
switch to root user

5. What is a server? What is ping? How does it differ from http get request?
Ans: server is an instance of a computer program that accepts and responds to requests
made by another program, known as a client.
Ping is a basic Internet program that allows a user to verify that a particular IP address exists
and can accept requests.Ping is used diagnostically to ensure that a host computer the user is
trying to reach is actually operating.

Ping only checks if the remote host is answering ICMP packets, which (usually) means it's
up and running; but this doesn't give you any information about which services the host is
actually offering.

An HTTP GET request checks that there is a web server running on the host, that it
answers to a given IP/port/hostname combo, that you asked it for a valid URL and that the
web site is able to answer your request.

6. In linux file system, what does group signify? Root user is a part of which group in your
system? How would you change the file permission for a group?
Ans:
(Allow them to check which groups root user belong to in their system)
If we do “groups root” then it tells which all group root user belongs to.
But generally root user belongs to “root” group so if they give that as an answer, then
accept that.

7. What is dns? How do you assign a domain name to an ip address? Why does it matter
what dns server I set in my computer’s internet settings?
Ans: Domain name system. Domain name can be assigned with the help of domain
providers like google, godaddy etc.

The process begins when you ask your computer to resolve a hostname, such as visiting
http://google.com. The first place your computer looks is its local DNS cache, which stores
information that your computer has recently retrieved.f your computer doesn’t already know the
answer, it needs to perform a DNS query to find out.
If the information is not stored locally, your computer queries (contacts) your ISP’s recursive
DNS servers or other public dns servers which you have set in your system. These specialized
computers perform the legwork of a DNS query on your behalf. Recursive servers have their
own caches, so the process usually ends here and the information is returned to the user.
Therefore when you change the dns servers matters.

If the recursive servers don’t have the answer, they query the root nameservers. A nameserver
is a computer that answers questions about domain names, such as IP addresses. The thirteen
root nameservers act as a kind of telephone switchboard for DNS. They don’t know the answer,
but they can direct our query to someone that knows where to find it.

8. Explain scp, ftp , ssh ,tcp

9. Which commands can be used to open the contents of a text file one screen at a
time? Explain their differences.
Ans: Less and more
10. What is the difference between git pull and git fetch? Explain.
11. What are the advantages of oops?
Ans: Basic object oriented programming benefits like code reuse , encapsulation, easy
code maintenance etc

12. Which of these method is given parameter via command line arguments?
a) main().
b) recursive() method.
c) Any method.
d) System defined methods.

Ans ( a)

13. Can command line arguments be converted into int automatically if required?
a) Yes
b) No
c) Compiler Dependent
d) Only ASCII characters can be converted.

Ans (b)

14. What are the differences between interface and abstract classes? When would you
prefer to use interface over abstract class and vice versa?

15. What is method overriding and overloading? Explain with example.


16. What is the output of the following program?
class Derived
{
protected final void getDetails()
{
System.out.println("Derived class");
}
}

public class Test extends Derived


{
protected final void getDetails()
{
System.out.println("Test class");
}
public static void main(String[] args)
{
Derived obj = new Derived();
obj.getDetails();
}
}
a) Derived class
b) Test class
c) Runtime error
d) Compilation error
Ans (d) final cannot be overridden

17. In Java, what are primitive data types and what are reference data types? Are the
parameters passed by reference or value? Is it same for both primitive and reference
data types?
Ans : by value

18. Based on your previous answer, explain what would be the output here.
public class Circle {
int x; int y;
Circle(int x,int y){
this.x=x;
this.y=y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
}

public class Main {

public static void moveCircle(Circle circle, int deltaX, int deltaY) {


circle.setX(circle.getX() + deltaX);
circle.setY(circle.getY() + deltaY);
circle = new Circle(0, 0);
}

public static void main(String[] args) {


Circle myCircle=new Circle(1,1);
moveCircle(myCircle, 23, 56);
System.out.println(myCircle.getX() + " , "+myCircle.getY() );

}
}
Ans: 24 , 57

19. What is builder pattern and what is decorator pattern?

20. When should you make a class singleton? Explain with example.
You are given a string S consisting of N brackets, opening "(" and/or closing ")". The goal is to split S
into two parts (left and right), such that the number of opening brackets in the left part is equal to the
number of closing brackets in the right part. More formally, we are looking for an integer K such that:

● 0 ≤ K ≤ N, and
● the number of opening brackets in the K leading characters of S is the same as the
number of closing brackets in the N−K trailing characters of S.

Write a function:

class Solution { public int solution(String S); }

that, given string S, returns a value for K that satisfies the above conditions. It can be shown that
such a number K always exists and is unique.

For example, given S = "(())", the function should return 2, because:

● the first two characters of S, "((", contain two opening brackets, and
● the remaining two characters of S, "))", contain two closing brackets.

In other example, given S = "(())))(", the function should return 4, because:

● the first four characters of S, "(())", contain two opening brackets, and
● the remaining three characters of S, "))(", contain two closing brackets.

In other example, given S = "))", the function should return 2, because:

● the first two characters of S, "))", contain zero opening brackets, and
● there are no remaining characters, so they contain also zero closing brackets.

Assume that:

● N is an integer within the range [0..100,000];


● string S consists only of the characters "(" and/or ")".

Complexity:

● expected worst-case time complexity is O(N);


● expected worst-case space complexity is O(1) (not counting the storage required for
input arguments).
Messaging queues:

A queue is a line of things waiting to be handled - in sequential order starting at the


beginning of the line. A message queue is a queue of messages sent between applications.
It includes a sequence of work objects that are waiting to be processed.
A message is the data transported between the sender and and the receiver application, it's
essentially a byte array with some headers on top. A message example could be anything
that tells one system to start processing a task, information about a finished task or a plain
message.

The basic architecture of a message queue is simple, there are client applications called
producers that create messages and deliver them to the message queue. An other
application, called consumer, connect to the queue and get the messages to be
processed. Messages placed onto the queue are stored until the consumer retrieves
them.

Message queues
A message queue provide an asynchronous communications protocol, a system that
puts a message onto a message queue does not require an immediate response to
continue processing. Email is probably the best example of asynchronous messaging.
When an email is sent can the sender continue processing other things without an
immediate response from the receiver. This way of handling messages decouple the
producer from the consumer. The producer and the consumer of the message do not
need to interact with the message queue at the same time.

DECOUPLING AND SCALABILITY


Decoupling is used to describe how much one piece of a system relies on another piece
of the system. Decoupling is the process of separating them so that their functionality
will be more self contained.
A decoupled system are achieved when two or more systems are able to communicate
without being connected. The systems can remain completely autonomous and
unaware of each other. Decoupling is often a sign of a computer system that is well
structured. It is usually easier to maintain, extend and debug.
If one process in a decoupled system fails processing messages from the queue, other
messages can still be added to the queue and be processed when the system has
recovered. You can also use a message queue to delay processing; A producer post
messages to a queue. At the appointed time, the receivers are started up and process
the messages in the queue. Messages in queue can be stored-and-forwarded and the
message be redelivered until the message is processed.
Instead of building one large application, is it beneficial to decouple different parts of
your application and only communicate between them asynchronously with messages.
That way different parts of your application can evolve independently, be written in
different languages and/or maintained by separated developer teams.
A message queue will keep the processes in your application separated and
independent of each other. The first process will never need to invoke another process,
or post notifications to another process, or follow the process flow of the other
processes. It can just put the message on the queue and then continue processing. The
other processes can also handle their work independently. They can take the messages
from the queue when they are able to process them. This way of handling messages
creates a system that is easy to maintain and easy to scale.

Message queuing - a simple use case


Imagine that you have a web service that receives many requests every second, where
no request is afford to get lost and all requests needs to be processed by a process that
is time consuming.
Imagine that your web service always has to be highly available and ready to receive
new request instead of being locked by the processing of previous received requests. In
this case it is ideal to put a queue between the web service and the processing service.
The web service can put the "start processing"-message on a queue and the other
process can take and handle messages in order. The two processes will be decoupled
from each other and does not need to wait for each other. If you have a lot of requests
coming in a short amount of time, the processing system will be able to process them
all anyway. The queue will persist requests if their number becomes really huge.
You can then imagine that your business and your workload is growing and you need to
scale up your system. All that is needed to be done now is to add more workers,
receivers, to work off the queues faster.

RabbitMQ
If you do start to consider a queue-based solution, CloudAMQP offers hosting of the
message queue RabbitMQ.RabbitMQ is open source message-oriented middleware that
implements the Advanced Message Queuing Protocol (AMQP). AMQP have features like
queuing, routing, reliability and security. You can read more about CloudAMQPhere.

FREE EBOOK
"Get started with
RabbitMQ"
Download your copy

Multi threading in java?

Can we start a thread twice


No. 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.

What if we call run() method directly instead


start() method?
● Each thread starts in a separate call stack.

● Invoking the run() method from main thread, the run() method goes onto the

current call stack rather than at the beginning of a new call stack.

Design patterns
1. When to use Strategy Design Pattern in Java?
Strategy pattern in quite useful for implementing set of related algorithms e.g. compression
algorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes,
which uses Strategy implementation classes for applying business rules. This pattern follows
open closed design principle and quite useful in Java.

One of a good example of Strategy pattern from JDK itself is a Collections.sort() method and
Comparator interface, which is a strategy interface and defines a strategy for comparing objects.
Because of this pattern, we don't need to modify sort() method (closed for modification) to
compare any object, at the same time we can implement Comparator interface to define new
comparing strategy (open for extension).

2. What is Observer design pattern in Java? When do you use Observer pattern in Java?
This is one of the most common Java design pattern interview questions. Observer pattern is
based upon notification, there are two kinds of object Subject and Observer. Whenever there is
change on subject's state observer will receive notification. See What is Observer design
pattern in Java with real life example for more details.

3. Difference between Strategy and State design Pattern in Java?


This is an interesting Java design pattern interview questions as both Strategy and State pattern
has the same structure. If you look at UML class diagram for both patterns they look exactly
same, but their intent is totally different.

State design pattern is used to define and manage the state of an object, while Strategy pattern
is used to define a set of an interchangeable algorithm and let's client choose one of them. So
Strategy pattern is a client driven pattern while Object can manage their state itself.

4. What is decorator pattern in Java? Can you give an example of Decorator pattern?
Decorator pattern is another popular Java design pattern question which is common because of
its heavy usage in java.io package. BufferedReader and BufferedWriter are a good example of
decorator pattern in Java. See How to use Decorator pattern in Java for more details.

5. When to use Composite design Pattern in Java? Have you used previously in your project?
This design pattern question is asked on Java interview not just to check familiarity with the
Composite pattern but also, whether a candidate has the real life experience or not.

The Composite pattern is also a core Java design pattern, which allows you to treat both whole
and part object to treat in a similar way. Client code, which deals with a Composite or individual
object doesn't differentiate between them, it is possible because Composite class also
implement the same interface as their individual part.

One of the good examples of the Composite pattern from JDK is JPanel class, which is both
Component and Container. When the paint() method is called on JPanel, it internally called
paint() method of individual components and let them draw themselves.

On the second part of this design pattern interview question, be truthful, if you have used then
say yes, otherwise say that you are familiar with the concept and used it by your own. By the
way, always remember, giving an example from your project creates a better impression.

6. What is Singleton pattern in Java?


Singleton pattern in Java is a pattern which allows only one instance of Singleton class available
in the whole application. java.lang.Runtime is a good example of Singleton pattern in Java.
There are lot's of follow up questions on Singleton pattern see 10 Java singleton interview
question answers for those followups.

7. Can you write thread-safe Singleton in Java?


There are multiple ways to write thread-safe singleton in Java e.g by writing singleton using
double checked locking, by using static Singleton instance initialized during class loading. By
the way using Java enum to create thread-safe singleton is the most simple way. See Why
Enum singleton is better in Java for more details.

8. When to use Template method design Pattern in Java?


The Template pattern is another popular core Java design pattern interview question. I have
seen it appear many times in real life project itself. Template pattern outlines an algorithm in
form of template method and lets subclass implement individual steps.

The key point to mention, while answering this question is that template method should be final,
so that subclass can not override and change steps of the algorithm, but same time individual
step should be abstract, so that child classes can implement them.

9. What is Factory pattern in Java? What is the advantage of using a static factory method to
create an object?
Factory pattern in Java is a creation Java design pattern and favorite on many Java
interviews.Factory pattern used to create an object by providing static factory methods. There
are many advantages of providing factory methods e.g. caching immutable objects, easy to
introduce new objects etc. See What is Factory pattern in Java and benefits for more details.

10. What is the difference between Decorator and Proxy pattern in Java?
Another tricky Java design pattern question and trick here is that both Decorator and Proxy
implements the interface of the object they decorate or encapsulate. As I said, many Java
design pattern can have similar or exactly same structure but they differ in their intent.

Decorator pattern is used to implement functionality on an already created object, while a Proxy
pattern is used for controlling access to an object.

One more difference between Decorator and the Proxy design pattern is that Decorator doesn't
create an object, instead, it get the object in its constructor, while Proxy actually creates objects.
You can also read Head First Analysis and Design to understand the difference between them.

11. When to use Setter and Constructor Injection in Dependency Injection pattern?
Use Setter injection to provide optional dependencies of an object, while use Constructor
iInjection to provide a mandatory dependency of an object, without which it can not work. This
question is related to Dependency Injection design pattern and mostly asked in the context of
Spring framework, which is now become a standard for developing Java application.

Since Spring provides IOC container, it also gives you a way to specify dependencies either by
using setter methods or constructors. You can also take a look my previous post on the same
topic.

12. What is difference between Factory and Abstract Factory in Java


I have already answered this question in detail with my article with the same title. The main
difference is that Abstract Factory creates factory while Factory pattern creates objects. So both
abstract the creation logic but one abstract is for factory and other for items. You can see here
to answer this Java design pattern interview question.
13. When to use Adapter pattern in Java? Have you used it before in your project?
Use Adapter pattern when you need to make two class work with incompatible interfaces.
Adapter pattern can also be used to encapsulate third party code so that your application only
depends upon Adapter, which can adapt itself when third party code changes or you moved to a
different third party library.

By the way, this Java design pattern question can also be asked by providing an actual
scenario. You can further read Head First Design Pattern to learn more about Adapter pattern
and its real world usage. The book is updated for Java 8 as well so you will learn new, Java 8
way to implement these old design patterns.

Java 8 Design pattern interview questions

14. Can you write code to implement producer consumer design pattern in Java?
The Producer-consumer design pattern is a concurrency design pattern in Java which can be
implemented using multiple ways. If you are working in Java 5 then its better to use
Concurrency util to implement producer-consumer pattern instead of plain old wait and notify in
Java. Here is a good example of implementing producer consumer problem using
BlockingQueue in Java.

15. What is Open closed design principle in Java?


The Open closed design principle is one of the SOLID principle defined by Robert C. Martin,
popularly known as Uncle Bob in his most popular book, Clean Code. This principle advises that
a code should be open for extension but closed for modification.

Java Design Pattern Interview Questions Answers

At first, this may look conflicting but once you explore the power of polymorphism, you will start
finding patterns which can provide stability and flexibility of this principle.

One of the key examples of this is State and Strategy design pattern, where Context class is
closed for modification and new functionality is provided by writing new code by implementing a
new state of strategy. See this article to know more about Open closed principle.

16. What is Builder design pattern in Java? When do you use Builder pattern?
Builder pattern in Java is another creational design pattern in Java and often asked in Java
interviews because of its specific use when you need to build an object which requires multiple
properties some optional and some mandatory. See When to use Builder pattern in Java for
more details
17. Can you give an example of SOLID design principles in Java?
There are lots of SOLID design pattern which forms acronym SOLID e.g.
1. Single Responsibility Principle or SRP
3. Open Closed Design Principle or OCD
3. Liskov Substitution Principle
4. Interface Segregation Principle
5. Dependency Inversion Principle.

You can further read this list of SOLID design principles for Java programmer to answer this
Java interview question.

18. What is the difference between Abstraction and Encapsulation in Java?


Even though both Abstraction and Encapsulation looks similar because both hide complexity
and make the external interface simpler there is a subtle difference between them. Abstraction
hides logical complexity while Encapsulation hides Physical Complexity.

What are global variables? Why is the use of global variables considered evil?
Usertable - userId pk
Bus - busid pk
Foregin Key - UserBus
---------------------------------------

TIcket booking system:


The ticket "covers" stops through TICKET_STOP table, For example, if a ticket covers 3
stops, then TICKET_STOP will contain 3 rows related to that ticket. If there are 2 other
stops not covered by that ticket, then there will be no related rows there, but there is nothing
preventing a different ticket from covering these stops.

Liberal usage or natural keys / identifying relationships ensures two tickets cannot cover the
same seat/stop combination. Look at how LINE.LINE_ID "migrates" alongside both edges of
the diamond-shaped dependency, only to be merged at its bottom, in the TICKET_STOP
table.

This model, by itself, won't protect you from anomalies such as a single ticket "skipping"
some stops - you'll have to enforce some rules through the application logic. But, it should
allow for a fairly simple and fast determination of which seats are free for which parts of the
trip, something like this:

SELECT * FROM STOP CROSS JOIN SEAT WHERE STOP.LINE_ID = :line_id AND
SEAT.BUS_NO = :bus_no AND NOT EXIST ( SELECT * FROM TICKET_STOP WHERE
TICKET_STOP.LINE_ID = :line_id AND TICKET_STOP.BUS_ID = :bus_no AND
TICKET_STOP.TRIP_NO = :trip_no AND TICKET_STOP.SEAT_NO = SEAT.SEAT_NO AND
TICKET_STOP.STOP_NO = STOP.STOP_NO )

(Replace the parameter prefix : with what is appropriate for your DBMS.)

This query essentially generates all combinations of stops and seats for given line and bus,
then discards those that are already "covered" by some ticket on the given trip. Those
combinations that remain "uncovered" are free for that trip.

You can easily add: STOP.STOP_NO IN ( ... ) or SEAT.SEAT_NO IN ( ... ) to the


WHEREclause to restrict the search on specific stops or seats.
Computer Science questions
● What does a Just in Time compiler have to offer? Do you know of any
programming language runtimes that use one?
● How is preemptive threading model different from the cooperative
threading model?
● What tools & practices would you consider necessary for a
Continuous Delivery solution?
● How is a code point related to a code unit in Unicode?
● What do you think makes a unit test good? What about functional
ones?

Role-specific questions
● Do arguments in Java get passed by reference or by value?
● Why would it be pointless for a static or final method to use dynamic
binding?
● How is Java SE related to Java EE?
● How are Runtime exceptions different from Checked exceptions?
● What are the most important features introduced in Java 5, 7 and 8
respectively?
● Is ForkJoinPool introduced in Java 7 always a better alternative to
ThreadPoolExecutor?
● What is the difference between HashMap, ConcurrentHashMap and
Map returned by Collections.synchronizedMap
● You want to synchronize 5 threads to start at the same time. Describe
a solution.
● What is a weak reference and how could it be useful to us?
● Choose a Java EE platform API and give a short description of it.
● In a 3-tier application running a Java application server you notice
freezes for several seconds during high load. What are the most likely
reasons? How would you troubleshoot them?
● Servlets 3.0 introduced async support. Describe a use case for it.
● Why do you think lambda expressions are considered such a big thing
for Java 8?
● What do you know about the Java Scripting API? Can you think of a
use case?
● Is this possible in Java?
○ A extends B, C
You are given a string S consisting of N brackets, opening "(" and/or closing ")". The goal is to split S
into two parts (left and right), such that the number of opening brackets in the left part is equal to the
number of closing brackets in the right part. More formally, we are looking for an integer K such that:

● 0 ≤ K ≤ N, and
● the number of opening brackets in the K leading characters of S is the same as the
number of closing brackets in the N−K trailing characters of S.

Write a function:

class Solution { public int solution(String S); }

that, given string S, returns a value for K that satisfies the above conditions. It can be shown that
such a number K always exists and is unique.

For example, given S = "(())", the function should return 2, because:

● the first two characters of S, "((", contain two opening brackets, and
● the remaining two characters of S, "))", contain two closing brackets.

In other example, given S = "(())))(", the function should return 4, because:

● the first four characters of S, "(())", contain two opening brackets, and
● the remaining three characters of S, "))(", contain two closing brackets.

In other example, given S = "))", the function should return 2, because:

● the first two characters of S, "))", contain zero opening brackets, and
● there are no remaining characters, so they contain also zero closing brackets.

Assume that:

● N is an integer within the range [0..100,000];


● string S consists only of the characters "(" and/or ")".

Complexity:

● expected worst-case time complexity is O(N);

You might also like