You are on page 1of 78

JAVA

MOCK INTERVIEW
Parinaaz Doctor
OOP
concepts-
Objects,
classes and
packages
Key • Platform Independence
• Compiler and Interpreter

Differences • Portability

Between • Memory Management


• Multiple Inheritance

C++ Vs • Overloading

Java • Pointers
• Documentation Comment
• Thread Support
WHAT ARE THE
DIFFERENT VERSIONS
OF JAVA? WHAT ARE
THE DIFFERENT
EDITIONS OF JAVA?
Release Extended
Version
date Support Until
JDK Beta 1995 ?
JDK 1.0 January 1996 ?
JDK 1.1 February 1997 ?
J2SE 1.2 December 1998 ?
J2SE 1.3 May 2000 ?
J2SE 1.4 February 2002 February 2013
J2SE 5.0 September 2004 April 2015
Java SE 6 December 2006 December 2018
Java SE 7 July 2011 July 2022

Java SE 8 (LTS) March 2014 December 2030

Java SE 9 September 2017 N/A


Java SE 10 March 2018 N/A

Java SE 11 (LTS) September 2018 September 2026

Java SE 12 March 2019 N/A


Java SE 13 September 2019 N/A
Java SE 14 March 2020 N/A
Java SE 15 September 2020 N/A
Editions of The Java Programming Language Platforms
• There are four platforms of the Java programming

Java language:
❑ Java Platform, Standard Edition (Java SE)
❑ Java Platform, Enterprise Edition (Java EE)
❑ Java Platform, Micro Edition (Java ME)
❑ JavaFX
WHAT IS THE
DIFFERENCE
BETWEEN JDK,
JVM AND JRE?
• JDK is a software development kit whereas JRE is a software bundle that
allows Java program to run, whereas JVM is an environment for executing
bytecode.
• The full form of JDK is Java Development Kit, while the full form of JRE is Java
Runtime Environment, while the full form of JVM is Java Virtual Machine.
• JDK is platform dependent, JRE is also platform dependent, but JVM is
platform independent.
• JDK contains tools for developing, debugging, etc. JRE contains class libraries
and other supporting files, whereas software development tools are not
included in JVM.
• JDK comes with the installer, on the other hand, JRE only contains the
environment to execute source code whereas JVM bundled in both software
JDK and JRE.
List the
features of
Java
Programming
language.
There are the following features in Java Programming Language.
Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.

Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the
combination of different type of objects that incorporates both data and behavior.

Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every
machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.

Platform Independent: Java is a platform independent programming language. It is different from other
programming languages like C and C++ which needs a platform to be executed. Java comes with its platform
on which its code is executed. Java doesn't depend upon the operating system to be executed.

Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode
and Exception handling which makes it more secured.
Robust: Java is a strong programming language as it uses strong memory management. The
concepts like Automatic garbage collection, Exception handling, etc. make it more robust.

Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C,


the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in
Java.

Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program
execution.

High Performance: Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++).
Multithreaded: We can write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for
each thread. It shares a common memory area. Threads are important for multi-media, Web
applications, etc.

Distributed: Java is distributed because it facilitates users to create distributed applications in


Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us
able to access files by calling the methods from any machine on the internet.

Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
What are
the various
access
specifiers in
Java?
What are • In Java, access specifiers are the keywords which are
used to define the access scope of the method, class,

the various
or a variable. In Java, there are four access specifiers
given below.

access • Public The classes, methods, or variables which are

specifiers in defined as public, can be accessed by any class or


method.

Java? • Protected Protected can be accessed by the class of


the same package, or by the sub-class of this class, or
within the same class.
• Default Default are accessible within the package
only. By default, all the classes, methods, and
variables are of default scope.
• Private The private class, methods, or variables
defined as private can be accessed within the class.
What is the
purpose of
static
methods
and
variables?
What is the • The methods or variables defined as static are shared
among all the objects of the class.

purpose of • The static is the part of the class and not of the
object.

static • The static variables are stored in the class area, and
we do not need to create the object to access such
methods variables.

and • Therefore, static is used in the case, where we need


to define variables or methods which are common to

variables? all the objects of the class.


• For example, In the class simulating the collection of
the students in a college, the name of the college is
the common attribute to all the students. Therefore,
the college name will be defined as static.
What is the
constructor?
How many
types of
constructors
are used in
Java?
What is the • The constructor can be defined as the special type of
method that is used to initialize the state of an object.
constructor? • It is invoked when the class is instantiated, and the
memory is allocated for the object.
How many • Every time, an object is created using the new
types of keyword, the default constructor of the class is called.

constructors
• The name of the constructor must be similar to the
class name.

are used in • The constructor must not have an explicit return


type.
Java? ❑ There are two types of constructors in Java:
• Default constructor (no-arg constructor)
• Parameterized constructor
What is
Encapsulation?
What is the
primary benefit
of
Encapsulation?
What is • It is the technique of making the fields in a class private
and providing access to the fields via public methods.

Encapsulation? • If a field is declared private, it cannot be accessed by


anyone outside the class, thereby hiding the fields

What is the within the class.


• Therefore encapsulation is also referred to as data
primary benefit hiding.

of • The main benefit of encapsulation is the ability to


modify our implemented code without breaking the

Encapsulation? code of others who use our code.


• With this Encapsulation gives maintainability, flexibility
and extensibility to our code.
What is
abstraction?
How do you
implement
it in Java?
What is • In Object-oriented programming, abstraction is a
process of hiding the implementation details from

abstraction? the user, only the functionality will be provided to the


user.

How do you • In other words, the user will have the information on
what the object does instead of how it does it.

implement
it in Java?
• In Java, abstraction is achieved using Abstract classes
and interfaces.
❑ Abstract Class
• A class which contains the abstract keyword in its
declaration is known as abstract class.
• Abstract classes may or may not contain abstract
methods, i.e., methods without body ( public void get(); )
• But, if a class has at least one abstract method, then the
class must be declared abstract.
• If a class is declared abstract, it cannot be instantiated.
• To use an abstract class, you have to inherit it from
another class, provide implementations to the abstract
methods in it.
• If you inherit an abstract class, you have to provide
implementations to all the abstract methods in it.
❑ Interface
• An interface is a reference type in Java.
• It is a collection of abstract methods.
• A class implements an interface, thereby inheriting the
abstract methods of the interface.
• Along with abstract methods, an interface may also
contain constants, default methods, static methods, and
nested types.
• Method bodies exist only for default methods and static
methods.
• But a class describes the attributes and behaviors of an
object. And an interface contains behaviors that a class
implements.
• Unless the class that implements the interface is
abstract, all the methods of the interface need to be
defined in the class.
Explain
Inheritance
in Java
Inheritance • Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a

in Java
parent object. It is an important part of OOPs (Object
Oriented programming system).

• The idea behind inheritance in Java is that you can


create new classes that are built upon existing
classes.
• When you inherit from an existing class, you can
reuse methods and fields of the parent class.
• Moreover, you can add new methods and fields in
your current class also.

• Inheritance represents the IS-A relationship which is


also known as a parent-child relationship.
What is
Polymorphism?
What is • Polymorphism is the ability of an object to take on
many forms.

Polymorphism? • The most common use of polymorphism in OOP


occurs when a parent class reference is used to refer
to a child class object.
• Any Java object that can pass more than one IS-A test
is polymorphic.
• In Java, all Java objects are polymorphic since any
object will pass the IS-A test for their own type and
for the class Object.
• Method Overloading and Method Overriding
Explain
Loops in
Java. Also
explain the
enhanced
for loop.
Explain Syntax :
while (boolean condition)
Loops in {

Java. Also }
loop statements...

explain the Syntax:

enhanced for (initialization condition; testing condition;


increment/decrement)
for loop. {
statement(s)
}
Explain Syntax:
for (T element:Collection obj/array)

Loops in {

Java. Also }
statement(s)

explain the Syntax:

enhanced do
{

for loop. statements..


}
while (condition);
Explain Set
Interface?
Explain
TreeSet?
Explain Set • It is a collection of element which cannot contain
duplicate elements.

Interface? • The Set interface contains only methods inherited


from Collection and adds the restriction that

Explain duplicate elements are prohibited.


• TreeSet: It is a Set implemented when we want
TreeSet? elements in a sorted order.
How to take
input from
console in
Java?
How to take
• Using Java Bufferedreader Class
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));

input from
String name = reader.readLine();
System.out.println(name);

console in • Scanner Class in Java


Scanner in = new Scanner(System.in);

Java? String s = in.nextLine();


System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b);

• Console Class in Java


String name = System.console().readLine();
System.out.println(name);
Difference
between
throw and
throws?
Difference • It includes:
▪ Throw is used to trigger an exception whereas throws

between is used in declaration of exception.


▪ Without throws, Checked exception cannot be handled
throw and whereas checked exception can be propagated with

throws?
throws.
What is
JAR file?
What is a
WAR file?
What is • JAR files is Java Archive fles and it aggregates many
files into one. It holds Java classes in a library. JAR files

JAR file? are built on ZIP file format and have .jar file extension.
• This is Web Archive File and used to store XML, java

What is a classes, and JavaServer pages. which is used to


distribute a collection of JavaServer Pages, Java

WAR file? Servlets, Java classes, XML files, static Web pages etc.
What is the
difference
between
Swing and
AWT
components
?
What is the • AWT components are heavy-weight, whereas Swing
components are lightweight.

difference • Heavy weight components depend on the local


windowing toolkit.

between • For example, java.awt.Button is a heavy weight


component, when it is running on the Java platform
Swing and for Unix platform, it maps to a real Motif button.

AWT
components
?
Difference
between
Vector and
ArrayList in
java?
Difference • All the methods of Vector is synchronized.
• But, the methods of ArrayList is not synchronized.

between • All the new implementations of java collection


framework is not synchronized.
Vector and • Vector and ArrayList both uses Array internally as

ArrayList in data structure. They are dynamically resizable.


• Difference is in the way they are internally resized.

java? • By default, Vector doubles the size of its array when


its size is increased. But, ArrayList increases by half
of its size when its size is increased.
What is the
Final
Keyword In
Java?
What is the • The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.

Final Final can be:


• Variable: If you make any variable as final, you cannot

Keyword In change the value of final variable(It will be constant).


• Method: If you make any method as final, you cannot
Java? override it.
• Class: If you make any class as final, you cannot
extend it.
Difference
between
String and
StringBuffer
?
String StringBuffer

String class is immutable. StringBuffer class is mutable.

String is slow and consumes more StringBuffer is fast and consumes


memory when you concat too many less memory when you cancat
strings because every time it creates strings.
new instance.

String class overrides the equals() StringBuffer class doesn't override


method of Object class. So you can the equals() method of Object class.
compare the contents of two strings
by equals() method.
What are
wrapper
classes?
What are
wrapper classes?
• Normally, when we work with Numbers, we use
primitive data types such as byte, int, long,
double, etc.
• However, in development, we come across
situations where we need to use objects instead
of primitive data types. In order to achieve this,
Java provides wrapper classes.
• All the wrapper classes (Integer, Long, Byte,
Double, Float, Short) are subclasses of the
abstract class Number.
Difference
between ==
and equals
in java?
Difference • In general both equals() and “==” operator in Java are
used to compare objects to check equality but here

between == are some of the differences between the two:


• Main difference between .equals() method and ==

and equals operator is that one is method and other is operator.


• We can use == operators for reference comparison
in java? (address comparison) and .equals() method
for content comparison. In simple words, == checks if
both objects point to the same memory location
whereas .equals() evaluates to the comparison of
values in the objects.
• If a class does not override the equals method, then
by default it uses equals(Object o) method of the
closest parent class that has overridden this method.
How many
types of
exception
can occur in
a Java
program?
How many
There are mainly two types of exceptions: checked and
unchecked. Here, an error is considered as the unchecked
exception. According to Oracle, there are three types of

types of exceptions:
Checked Exception: Checked exceptions are the one which

exception are checked at compile-time. For example, SQLException,


ClassNotFoundException, etc.

can occur in Unchecked Exception: Unchecked exceptions are the one


which are handled at runtime because they can not be
a Java checked at compile-time. For example, ArithmaticException,
NullPointerException, ArrayIndexOutOfBoundsException,

program?
etc.

Error: Error cause the program to exit since they are not
recoverable. For Example, OutOfMemoryError,
AssertionError, etc.
What is
finally
block?
What is • The "finally" block is used to execute the important
code of the program. It is executed whether an

finally exception is handled or not. In other words, we can say


that finally block is the block which is always executed.

block? • Finally block follows try or catch block. If you don't


handle the exception, before terminating the program,
JVM runs finally block, (if any).
• The finally block is mainly used to place the cleanup
code such as closing a file or closing a connection.
Here, we must know that for each try block there can
be zero or more catch blocks, but only one finally
block.
• The finally block will not be executed if program
exits(either by calling System.exit() or by causing a
fatal error that causes the process to abort).
What are
event
listeners?
What are • A source generates an Event and send it to one or
more listeners registered with the source.

event • Once event is received by the listener, they process


the event and then return.

listeners? • Events are supported by a number of Java packages,


like java.util, java.awt and java.awt.event.
• An event listener is a procedure or function in a
computer program that waits for an event to occur.
• Examples of an event are the user clicking or moving
the mouse, pressing a key on
the keyboard, disk I/O, network activity, or an
internal timer or interrupt.
• The listener is programmed to react to an input or
signal by calling the event's handler.
What are
JDBC
drivers?
What are JDBC drivers are client-side adapters (installed on the
client machine, not on the server) that convert requests

JDBC from Java programs to a protocol that the DBMS can


understand.

drivers? There are 4 types of JDBC drivers:


• Type-1 driver or JDBC-ODBC bridge driver
• Type-2 driver or Native-API driver
• Type-3 driver or Network Protocol driver
• Type-4 driver or Thin driver
What are
the
Interfaces of
JDBC API?
What are Interfaces of JDBC API
• Driver interface

the • Connection interface

Interfaces of • Statement interface


• PreparedStatement interface

JDBC API? • CallableStatement interface


• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Ways to
implement
multithread
ing in java
Ways to • Java’s multithreading system is built upon the Thread
class, its methods, and its companion

implement interface, Runnable.


• To create a new thread, your program will either

multithread extend Thread or implement the Runnable interfa


ce.

ing in java
What are
the Thread
class
methods?
Lifecycle of
Thread
What are Constructors:
• Thread()

the Thread • Thread(String name)

class • Thread(Runnable r)
• Thread(Runnable r,String name)

methods?
What are • public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread.JVM

the Thread calls the run() method on the thread.


• public void sleep(long miliseconds): Causes the currently

class executing thread to sleep (temporarily cease execution)


for the specified number of milliseconds.

methods? • public void join(): waits for a thread to die.


• public void join(long miliseconds): waits for a thread to
die for the specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of
the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of
the thread.
• public Thread currentThread(): returns the reference of currently executing thread.
• public int getId(): returns the id of the thread.
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been interrupted.
Thread class Multi extends Thread{
public void run(){

class System.out.println("thread is running...");


}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Runnable class Multi3 implements Runnable{
public void run(){

Interface System.out.println("thread is running...");


}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
What is the
super
keyword?
What is the • The super keyword refers to superclass (parent)
objects.

super • It is used to call superclass methods, and to access the


keyword? superclass constructor.

• The most common use of the super keyword is to


eliminate the confusion between superclasses and
subclasses that have methods with the same name.
Example • // Import required java libraries
• import java.io.*;

Servlet • import javax.servlet.*;


• import javax.servlet.http.*;

• // Extend HttpServlet class


• public class HelloWorld extends HttpServlet {

• private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}
Example
<html>
<head><title>First JSP</title></head>

JSP
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
</body>
</html>
All The Best!!!

You might also like