When preparing for an interview, knowledge of Advanced Java is essential for standing out in today’s competitive IT landscape. Advanced Java goes beyond the basics and delves into enterprise-level development, server-side applications, frameworks like Spring and Hibernate, and more.
In this blog, we'll explore some of the most frequently asked Advanced Java interview questions and their answers to help you confidently approach your next interview.
What is a DataSource in JDBC?
A Data Source object enables JDBC applications to obtain a DBMS connection from a connection pool. Each Data Source object binds to the JNDI tree and points to a connection pool or MultiPool. Applications look up the Data Source on the JNDI tree and then request a connection from the Data Source.
How many ways can you update a result set?
The following ways to update a result set
updateRow()
deleteRow()
refreshRow()
cancelRowUpdates()
insertRow()
How to set the attribute Concurrency in ResultSet?
CONCUR_READ_ONLY – It is only for reading.
CONCUR_UPDATABLE − It is for both read and updated.
What are the methods available in HttpServlet class?
public void service(ServletRequest req,ServletResponse res)
protected void service(HttpServletRequest req, HttpServletResponse res)
protected void doGet(HttpServletRequest req, HttpServletResponse res)
protected void doPost(HttpServletRequest req, HttpServletResponse res)
protected void doHead(HttpServletRequest req, HttpServletResponse res)
protected void doOptions(HttpServletRequest req, HttpServletResponse res)
protected void doPut(HttpServletRequest req, HttpServletResponse res)
protected void doTrace(HttpServletRequest req, HttpServletResponse res)
protected void doDelete(HttpServletRequest req, HttpServletResponse res)
protected long getLastModified(HttpServletRequest req)
What is HTTPFilter?
Filters typically run on multithreaded servers,so be aware that a filter must handle concurrentrequests and be careful to synchronize access to shared resources.Shared resources include in-memory data such asinstance or class variables and external objectssuch as files, database connections, and networkconnections.
How servlet filter configuration in web.xml?
Syntax:
<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>
What are the methods available in filter interfeace in servlet?
public void init(FilterConfig config)
public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)
public void destroy()
What is the difference between war file and jar file?
JAR files are used for packaging and distributing standalone Java applications or libraries, where as WAR files are used for packaging and distributing web applications.
How to create war file?
It needs jar tool of JDK
Go inside the project directory of your project (outside the WEB-INF), then write the following command
jar -cvf projectname.war *
Here, -c is used to create file, -v to generate the verbose output and -f to specify the arhive file name.
The * (asterisk) symbol signifies that all the files of this directory.
What is ServletInputStream?
ServletInputStream is a class which provides to read binary data as image from the request object.
The getInputStream() method of ServletRequest interface returns the instance of ServletInputStream.
it is having only one method called as
int readLine(byte[] b, int off, int len)
Example:
ServletInputStream input =request.getInputStream();
What is ServletOutputStream?
ServletOutputStream is a class used to write binary data into the response.
The getOutputStream() method of ServletResponse interface returns the instance of ServletOutputStream class.
Example:
ServletOutputStream out=response.getOutputStream();
What are the methods available in ServletOutputStream class?
void print(long l)
void print(boolean b)
void print(int i)
void print(char c)
void print(String s)
void print(float f)
void println(long l)
void println
void print(double d)
void println(boolean b)
void println(double d)
void println(int i)
void println(float f)
void println(String s)
void println(char c)
Explain SingleThreadModel interface?
SinglrThreadModel is used to handle single request at a time. If the programmer wants single request at a time must be implementing this interface. It is a marker interface so does not have any methods.
It is recommended to use other means to resolve these thread safety issues such as synchronized block etc.
Sample Program:
public class TestServlet extends HttpServlet implements SingleThreadModel {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("Welcome to ");
try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}
out.print("Nareh I Technologies");
out.close();
}
}
What are the methods available in ServletContext Interface?
public String getInitParameter(String name)
public Enumeration getInitParameterNames()
public Enumeration getInitParameterNames()
public void removeAttribute(String name)
public void setAttribute(String name,Object object)
public Object getAttribute(String name)
How to get the object of ServletContext interface?
getServletContext() method used to returns the object of ServletContext.
Syntax:
public ServletContext getServletContext()
Example:
ServletContext serv=getServletContext();
What are Techniques of Session Tracking?
The following techniques are used for session tracking
Hidden Form Field
URL Rewriting
Cookies
HttpSession
Explain JDBCURL connection for oracle expression addition using connection class object?
JDBC URL of Oracle connection is jdbc:oracle:thin:@localhost:1521:xe
where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port number and XE is the Oracle service name.
How to establish connection using connection class Object?
For establish the connection by using connection class object of oracle expression addition is
Connection con = DriverManager.getConnection(url,user,password)
The URL is connection which of database URL example oracle and MYSQL.
UserName: username of oracle database.
Password: Password of oracle database related to username
Explain JDBCURL connection for MYSQL expression addition using connection class object?
The url for MYSQL JDBC connection using connection class object is jdbc:mysql://localhost:3306/test
where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and test is the database name.
What are the different types of drivers in jdbc?
Type 1: JDBC-ODBC bridge.
Type 2: Native-API driver(partial Java driver).
Type 3: Network Protocol driver(pure Java driver for database middleware).
Type 4: Thin driver(pure Java driver for direct-to-database).
Type 5: highly-functional drivers with superior performance.
What is “oracle.jdbc.driver.OracleDriver”?
This is driver class for oracle database and by using Class.ForName to load the oracle driver first
For class.ForName
Class.forName("oracle.jdbc.driver.OracleDriver");
What is “com.mysql.jdbc.Driver”?
This is driver class for MYSQL database by using Class.ForName to load the MYSQL driver first.
Class.ForName(“com.mysql.jdbc.Driver”);
Which data types are used for storing the image and file in the database table?
BLOB: it is a data type is used to store the image in the database. We can also store videos and audio by using the BLOB data type. It stores the binary type of data.
CLOB: it is a data type is used to store the file in the database. It stores the character type of data.
What is stored procedure? What are the parameter types in stored procedure?
Stored procedure is a group of SQL queries that are executed as a single logical unit to perform a specific task. Name of the procedure should be unique since each procedure is represented by its name.
For example, operations on an employee database like obtaining information about an employee could be coded as stored procedures that will be executed by an application.
What is the difference between oracle.jdbc.driver.OracleDriver and oracle.jdbc.OracleDriver?
For Oracle 9i onwards you should use oracle.jdbc.OracleDriver rather than oracle.jdbc.driver.OracleDriver as Oracle have stated that oracle.jdbc.driver.OracleDriver is deprecated and support for this driver class will be discontinued in the next major release.
What is JDBC-ODBC bridge driver?
JDBC bridge is used to access ODBC drivers installed on each client machine and it converts JDBC method calls into the ODBC function calls. This driver does not support from java 8 or later.
What is Native API driver?
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.
What is Network Protocol driver?
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol and inotherwords it is three-tier approach is used to access databases. The JDBC clients use standard network sockets to communicate with a middleware application server. It is fully written in java.
Advantage is No client-side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.
What is thin driver?
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language and it is called as pure java-based driver. For this you don't need to install special software on the client or server.
What is ResultSetMetaData interface in jdbc?
ResultSetMetaData interface provides methods to get metadata from the ResultSet object and count the number of columns, column name, column type etc by using getMetaData() method of ResultSet.
Syntax:
public ResultSetMetaData getMetaData()throws SQLException
What are the commonly used methods in ResultSetMetaData?
public int getColumnCount()throws SQLException
public String getColumnName(int index)throws SQLException
public String getColumnTypeName(int index)throws SQLException
public String getTableName(int index)throws SQLException
Explain DatabaseMetaData interface?
DatabaseMetaData is used for database driver name,product version, name of total number of tables, name of total number of views etc.By using getMetaData() method of Connection interface returns the object of DatabaseMetaData.
Syntax:
public DatabaseMetaData getMetaData()throws SQLException
What are the commonly used methods in DatabaseMetaData?
public String getDriverName()throws SQLException
public String getDriverVersion()throws SQLException
public String getUserName()throws SQLException
public String getDatabaseProductName()throws SQLException
public String getDatabaseProductVersion()throws SQLException
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)throws SQLException
Explain ACID properties of Transaction management in JDBC?
ACID stands for Atomicity, Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the event of errors, power loss etc.
What is BatchProcessing in JDBC?
Instead of executing a single query, we can execute a batch (group) of queries and when one statement sends multiple statements of SQL at once to the database, the communication overhead is reduced significantly, as one is not communicating with the database frequently, which in turn results to fast performance.The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.
What are the steps for batch processing in JDBC?
The following steps used to create batch processing in JDBC
Load the driver class
Create Connection
Create Statement
Add query in the batch
Execute Batch
Close Connection
If you’re aiming to master the intricacies of Advanced Java and be interview-ready, Naresh IT offers the perfect platform. Our comprehensive Advanced Java Online Training provides:
At Naresh IT, we not only teach you Advanced Java but also help you sharpen your problem-solving skills with interview-focused training sessions.
Stay tuned for the rest of the blog where we dive into more interview questions for all technologies
Ready to upskill? Enroll in Naresh IT's Advanced Java Online Training today and take your career to the next level!
----------------------------------------------------------------------------------------------------
For More Details About Full Stack Courses : Visit Here
Register For Free Demo on UpComing Batches : Click Here
When preparing for an interview, knowledge of Advanced Java is essential for standing out in today’s competitive IT landscape. Advanced Java goes beyond the basics and delves into enterprise-level development, server-side applications, frameworks like Spring and Hibernate, and more.
In this blog, we'll explore some of the most frequently asked Advanced Java interview questions and their answers to help you confidently approach your next interview.
Statement stmtement = null;
try {
stmtement = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .// without close connection
}
PreparedStatement pstmt = null;
try {
String SQL = ""; //SQL Query
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . . // without close connection
}
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Connection con = null;
CallableStatement callstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
callstmt = con.prepareCall (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .// without close connection
}
index.html
index.htm
index.jsp
Example:
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>Name-of-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>90</session-timeout>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
public static Class<T> forName(String className) throws ClassNotFoundException
Sample Program:
public class InterviewTest {
public static void main(String[] args) throws ClassNotFoundException{
Class strcls = Class.forName("java.lang.String");
System.out.print(strcls.toString());
}
}
If you’re aiming to master the intricacies of Advanced Java and be interview-ready, Naresh IT offers the perfect platform. Our comprehensive Advanced Java Online Training provides:
At Naresh IT, we not only teach you Advanced Java but also help you sharpen your problem-solving skills with interview-focused training sessions.
Stay tuned for the rest of the blog where we dive into more interview questions for all technologies
Ready to upskill? Enroll in Naresh IT's Advanced Java Online Training today and take your career to the next level!
----------------------------------------------------------------------------------------------------
For More Details About Full Stack Courses : Visit Here
Register For Free Demo on UpComing Batches : Click Here
Java happens to be one of the most powerful yet flexible programming languages, known for its involvement in data processing, application development and large-scale systems generally. It gives developers solid frameworks and tools that enable them to do complex computations and create sophisticated management models that are useful in data management and analysis.
Why Choose Java?
Can class have private and protected as access modifier?
No, class does not have private and protected as access modifier, class can be default and public.
Example:
private class NIT{ //error
}
protected class NIT1 // error
{
}
What is the difference between Abstraction and Encapsulation?
Abstraction is the method of hiding the unwanted information. Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside.
In abstraction, implementation complexities are hidden using abstract classes and interfaces. While in encapsulation, the data is hidden using methods of getters and setters.
Why final and abstract cannot be used at a time?
If we declare class as abstract it must be extended by another class but if we declare final class it cannot be extended by other class.
Example:
final class NIT{
}
class NIT1 extends NIT // error because final class cannot be extended
{
}
What is Object Cloning?
Object cloning means exact copy of Object by using Cloneable interface must be implemented by class and if you not implemented it throws cloneNotSupportedException
Example:
public class InterviewTest implements Cloneable {
int id;
String name;
public InterviewTest(int id, String name) {
this.id=id;
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
InterviewTest nit = new InterviewTest(1,"NIT");
System.out.println(nit.id+" "+nit.name);
try {
InterviewTest nit1 = (InterviewTest)nit.clone(); // Object cloning
System.out.println(nit1.id+" "+nit1.name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Define Wrapper Classes in Java?
Wrapper class is a mechanism which contains primitive data types of class and it converts to primitive data type to object and object to primitive data type by using Autoboxing and unboxing technique.
For example Primitive data type ‘char’ and wrapper class is ‘Character’
Example 1: Autoboxing
public class InterviewTest {
public static void main(String[] args) {
int id = 25;
short sh = 10;
byte by = 15;
char letter ='N';
boolean tr = true;
float fdes = 5.25F;
double ddes = 6.27D;
long lon = 43L;
//Autoboxing
Integer i = id;
Short s = sh;
Byte b = by;
Character c = letter;
Boolean bol = tr;
Float f = fdes;
Double d = ddes;
Long l = lon;
//print object values
System.out.println("Integer: "+i);
System.out.println("Short: "+s);
System.out.println("Byte: "+b);
System.out.println("Charater: "+c);
System.out.println("Boolean: "+bol);
System.out.println("Float: " +f);
System.out.println("Double: "+d);
System.out.println("Long: "+l);
}
}
Example 2: Unboxong
public class InterviewTest {
public static void main(String[] args) {
Integer i = 25;
Short s = 10;
Byte b = 15;
Character c = 'N';
Boolean bol = true;
Float f = 5.25F;
Double d = 6.27D;
Long l = 43L;
//Unboxing
int id = i;
short sh = s;
byte by = b;
char letter =c;
boolean tr = bol;
float fdes = f;
double ddes = d;
long lon = l;
//print primitive values
System.out.println("int: "+id);
System.out.println("short: "+sh);
System.out.println("byte: "+by);
System.out.println("char: "+letter);
System.out.println("boolean: "+tr);
System.out.println("float: " +fdes);
System.out.println("double: "+ddes);
System.out.println("long: "+lon);
}
}
Can you implement pointers in a Java Program?
No, Pointers are not available in java so, we cannot implement pointers.
Define System.out.println()?
System. out. println() that prints any argument you pass and adds a new line after it. println() is responsible for printing the argument and printing a new line. System.out refers to the standard output stream.
System: this is a final class and it is found at java.lang package.
Out: it is static and public modifier field of System class and it is instance of PrintStream.
Println(): it is an instance of PrintStream class and it prints output and printing new line
How to create an object in Java?
Java is Object Oriented programming language so, without creating an object we cannot execute the program.
In java we provide fives ways to create an object
1. Using new keyword
2. Using newInstance method of class
3. Using newInstance method of Constructor
4. Using clone()
5. Using Deserilization
We use Class.forName(String className) method it returns new instance of class object
How to access class data members and methods in Java?
Class data members and methods into another class by using object in java but we have Instance data members and static data members and similar to methods
Example:
class NIT {
int id = 5;
public void test()
{
System.out.println("NareshIT");
}
}
public class InterviewTest {
public static void main(String[] args) {
NIT nit = new NIT();
System.out.println(nit.id);
nit.test();
}
}
Can we declare a static variable inside a method?
No we cannot declare a static variable inside a method and only final method is allowed.
Example:
class NIT {
public void test()
{
final int t = 10;
static String name = "Naresh"; // error
}
}
What is the difference between a static and a non-static inner class?
Nested or inner static class doesn’t need a reference of Outer class but a non static nested class or Inner class requires Outer class reference.
Example:
class NIT {
//non static
class Test
{
public void print() {
System.out.println("NON - Static inner or nested class");
}
}
//static
static class Program
{
void print() {
System.out.println("Static inner or nested class");
}
}
}
public class InterviewTest {
public static void main(String[] args) {
NIT nit = new NIT();
NIT.Test test = nit.new Test(); // for non static inner class
test.print();
NIT.Program prog = new NIT.Program(); // for static inner class
prog.print();
}
}
What is the difference between a constructor and a method?
Constructor
Constructor does not have return type and it is used to initialize the object.
Default constructor is available
Method
Method has return type if you declare void it does not return any value and we access by using object.
We don’t have default method
What is the difference between java.util.Date and java.sql.Date?
Both dates are storing date and time information but java.sql.Date is used to communication of java applications with the database but java.util.Date get time and date from the system.
Sometimes we need to convert sql date into util date and vice versa based on date formate
What are the inner class?
We have two types of inner classes one is static inner class and non static inner class
Inner class is defined as class provides another class inside that class or group of classes in one place it is more reliable to maintain.
Example:
class NIT {
//static inner class
static class Staticclass
{
}
//Non static inner class
class NonStatic
{
}
}
What is the anonymous class?
Anonymous class is nothing but without a class name of inner class which is only create single object and a anonymous class must be defined inside another class
Anonymous class may have to create in two ways like class and interface.
Syntax:
Class Outerclass
{
//define anonymous class
object = new Type(parameterlist) // parameter list is optional
{
body
};
}
Example:
class NIT {
public void test() {
System.out.println("This is Normal class");
}
}
public class InterviewTest {
public void testAnonymous()
{
NIT nit = new NIT() // Anonymous class
{
@Override
public void test() {
System.out.println("This is Anonymous class");
}
};
nit.test(); // must be class inner class method by using object
}
public static void main(String[] args) {
InterviewTest inter = new InterviewTest();
inter.testAnonymous();
}
}
What is the difference between thread and process?
process takes more time to create or terminate when compared to thread because thread communication is more efficient and thread have segment of process
We have multi programs holds multiple process but each process have multiple threads.
Process involved in system calls but thread is created by API’s
What is Daemon thread?
In java Daemon thread is service provider thread it provides service to the user threads and the life of the Daemon thread depends on user crated threads.
Daemon thread contains two methods setDaemon(Boolean status) and isDaemon(), if user thread converts to Daemon thread use setDaemon(true) method and if current thread to check Daemon thread or not use isDaemon() method.
Example:
public class InterviewTest extends Thread{
@Override
public void run() {
if(Thread.currentThread().isDaemon())// check if the thread is Daemon or not
System.out.println("Thread is Daemon");
else
System.out.println("User thread");
}
public static void main(String[] args) {
InterviewTest inter = new InterviewTest();// create new thread
InterviewTest inter1 = new InterviewTest();
InterviewTest inter2 = new InterviewTest();
inter.setDaemon(true); // first thread i.e user thread convert into Daemon
inter.start();
inter1.start();
inter2.start();
}
}
What is the difference between user thread and Deamon thread?
A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM.
User threads are created by application but Deamon threads are created by JVM and user threads are foreground threads ant Deamon threads are background threads
User threads are high priority and Deamon threads are low priority
How can we create daemon threads?
By using setDeamon(Boolean status) method is used to create deamon threads or convert user threads into daemon thread
Example:
Test test = new Test() // user thread
Test.setDeamon(true) // create deamon thread
What is the difference between notify() and notifyAll() methods?
In cache memory a group of threads are waiting for notification in the form of object, if you want notifies into one thread by using notify() method and if you want to notifies all the threads by using notifyAll() method.
According to performance notify() is better performance compares to notifyAll() method
According to risk notify() has more risk compared to notifyAll() because if any thread is missing another does not take request.
What is thread pool?
Thread pool is nothing but to manage collection of threads and it provides multiple tasks to increase the performance and reduce the per task invocation overhead.
What is the difference between Thread and Thread pool?
Thread pool having reuse threads because it has multiple threads but Thread class contains only one thread. We have checking process in Thread pool and no checking process in Thread.
What is the lifecycle of Thread?
We have various stages in lifecycle of Thread.
What is the difference between Runnable and Callable interface?
Callable interface is checked exception so it returns value otherwise it throws exception but Runnable interface is unchecked exception so it does not return any value.
Callable interface is call() method but Runnable interface have run() method
Syntax of Runnable interface
public interface Runnable
{
public abstract void run();
}
Syntax of callable interface
public interface Callable<E>
{
E call() throws exception ;
}
Example for callable interface
public class InterviewTest implements Callable<String>{
@Override
public String call() throws Exception {
return "Welcome to NareshIT";
}
public static void main(String[] args) throws Exception {
ExecutorService service = Executors.newFixedThreadPool(3);
InterviewTest test = new InterviewTest();
Future<String> thread = service.submit(test);
System.out.println(thread.get().toString());
//test.call();
}
}
Example for Runnable interface
public class InterviewTest implements Runnable{
@Override
public void run() {
System.out.println("Runnable Thread");
}
public static void main(String[] args) throws Exception {
InterviewTest test = new InterviewTest();
Thread thread = new Thread(test);
thread.start();
}
}
How can we handle deadlock?
There are four ways to Handling the deadlock situation
1. Prevention
2. Avoidance
3. Detection and Recovery
4. Ignorance
What is the purpose of join() method?
In java join() method found in java.lang.Thread class which permits one thread to wait until the other thread to finish its execution. If more than one thread invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to mention the waiting period.
There are three overloaded join() methods
Join() : current thread stops and goes into wait state
Syntax:
public final void join() throws InterruptedException
Join(long mls) : this method is used to current thread is goes to wait state upto specified time that is in milliseconds.
Syntax:
public final synchronized void join(long mls) throws InterruptedException, where mls is in milliseconds
Join(long mls, int nanos) : this method is used to current thread is goes to wait state upto specified time that is in milliseconds plus nano seconds.
Syntax:
public final synchronized void join(long mls, int nanos) throws InterruptedException, where mls is in milliseconds.
Example:
public class InterviewTest{
public static void main(String[] args) throws Exception {
Thread thread = new Thread();
thread.start();
System.out.println(thread.isAlive());
thread.join();
System.out.println(thread.isAlive());
}
}
What is Thread Scheduler?
Thread Scheduler means the JVM thread using preemptive and priority based scheduling algorithm.
All Java Threads have a priority and the thread with the height priority is scheduled to run by JVM.
In case of two threads have the same priority it follows FIFO order.
What is the use of super keyword?
The super keyword is used for refers to superclass (parent) objects and It is used to call superclass methods, and to access the superclass constructor.
Example:
class NIT {
int a = 10;
public NIT() {
System.out.println("Super class");
}
public void test() {
System.out.println("test method");
}
}
class NIT1 extends NIT
{
//super keyword implicitly by constructor
public NIT1() {
super();
System.out.println("Child class");
}
//super keyword explicitly by constructor
/*
* public NIT1() { System.out.println("Child class"); }
*/
// method
public void process() {
super.test(); //call parent class method
System.out.println(super.a); // call parent class variable
}
}
public class InterviewTest{
public static void main(String[] args) throws Exception {
NIT1 nit = new NIT1();
nit.process();
}
}
Can Static method be overridden?
NO, static method is not overridden in java because static method of parent class is hidden in child class but static overloaded methods are possible but different parameters
Example:
class NIT {
// static method of base class
public static void test() {
System.out.println("Base class static test method");
}
// Non-static method of base class
public void display() {
System.out.println("Base class of display non static method");
}
}
public class InterviewTest {
public static void main(String[] args) throws Exception {
NIT nit = new NIT1();
nit.test();
nit.display();
}
}
What is classLoader?
ClassLoader in java is located at JRE(Java Runtime Environment) and it is dynamically loads java class into JVM(Java Virtual Machine). Java classes aren’t loaded into memory all at once, but when required by an application and ClassLoader loads class dynamically into memory.
By using getClassLoader() method to know classLoader loads the class or not and if any class is not available it return NoClassDefFoundError or ClassNotFoundException.
There are three types of classLoaders.
What is exception handling?
Exception handling in java is a process to handle the runtime errors by using throw and throws keywords or try, catch and finally keywords.
Java.lang.Throwable is a parent class of Java Exception
There are Checked and UnChecked exceptions in java.
What is the difference between Exception and error in java?
Error is a result from system resources but all errors are comes at run time and unchecked so we cannot handle errors. Exceptions are checked or unchecked exception but we handle Exception at compile time or runtime.
What is the difference between throw and throws in java?
In Java throw keyword is used to throw an exception explicitly in the code, inside the function or the block of code.
In Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.
Example 1: for throw keyword
public class InterviewTest {
void test(int num)
{
if(num<0)
{
throw new ArithmeticException("number must be positive");
//System.out.println("number must be positive");
}
else
{
System.out.println(num);
}
}
public static void main(String[] args) throws Exception {
InterviewTest nit = new InterviewTest();
nit.test(-5);
}
}
Example 2: for throws keyword
public class InterviewTest {
int test(int q, int r) throws ArithmeticException
{
int div = q/r;
return div;
}
public static void main(String[] args) throws Exception {
InterviewTest nit = new InterviewTest();
nit.test(5, 0);
/*
* try { System.out.println(nit.test(5, 0)); } catch (ArithmeticException e) {
* System.out.println("Number cannot be divisible by zero"); }
*/
}
}
What is the difference between checked and unchecked exceptions?
Checked exceptions are compile time exceptions like IOException and SQLException but unchecked exceptions are runtime exceptions like ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
How can we handle checked exception?
Checked exceptions are compile time exceptions and these exceptions are handle by using try and catch method or by using throws keyword.
Example: throws Checked Exception at compile time
public class InterviewTest {
public static void main(String[] args) throws Exception {
FileInputStream file = new FileInputStream("D:/input.txr"); // throws FileNotFoundException
}
}
Example: handle checked exception
public class InterviewTest {
public static void main(String[] args) throws Exception {
try {
FileInputStream file = new FileInputStream("D:/input.txr"); // FileNotFoundException
} catch (FileNotFoundException e) {
System.out.println("This file not found");
}
}
}
What is runtimeException?
Runtime exception is a unchecked exception. Runtime exceptions are might be throw during the execution process it might not be catch.
public class InterviewTest {
public static void main(String[] args) throws Exception {
String name = null;
System.out.println(name.length());// NullPointerException
}
}
What is Custom exception?
Custom Exception is nothing but user defined exceptions or own exception derived from exception class.
What is the difference between final, finally, and finalize keywords?
In java final is a keyword used to restrict the modification of a variable, method, or class. finally keyword is a block used to ensure that a section of code is always executed, even if an exception is thrown. finalize is a method used to perform cleanup processing on an object before it is garbage collected.
What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when looking up a class that is not found classpath or using an invalid name to look up a class that not found on the runtime classpath. NoClassDefFoundError occurs when a compiled class references another class that isn't on the runtime classpath.
What is the use of printStackTrace() in exception handling of java?
It is used to print exception or error in console with other details like class name along with where exception occured and it if found at java.lang.Throwble class to handle exception or error.
It used to understand easy handle the exception
Syntax:
public void printStackTrace()
Example:
public class InterviewTest {
public static void main(String[] args) {
try
{
String name = null;
name.length();
}catch (Throwable e) {
e.printStackTrace();
}
}
}
Execution:
NullPointerException : Cannot invoke "String.length()" because "name" is null.
The Core Java Online Training program at NareshIT is a comprehensive hands-on learning experience through which the student gets exposed to front-end, middleware and back-end technologies. These phase-end projects are designed to provide practical solutions to real world problems so that the students are equipped with up-to-date skills that meet industry requirements.
Industry experts teach the program and its content is based on current market trends. You will learn about end-to-end application development that not only makes robust but also feature-laden applications.
At the end of this course, you will be awarded an industry recognized completion certificate that serves as testimony to your knowledge in Core Java development thus increasing your chances of employment.