Loading
Java Interview Questions

Java Quick Notes

Refresh Your Java

We are Agile, believe in less Documentation - Only Quick notes of Java/J2ee Read more....


Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

"Click on other Tabs for more Questions"  

"RealTime "


This Section Focuses on Day to Day Real-Time Development issues including general exceptions like 'OutOfMemoryError','NoSuchMethodException','Not Enough Space', SystemParamters, 'External Config files', 'ThreadDumps', 'Thread Local', 'Template Frameworks' ,'Caching Techniques' , 'Jsp Pre-compilation' and much more.

1 )   Java Coding Best Practices ?


Ans)

Coding conventions (Best Practices) are a set of guidelines for a specific programming language
that recommend programming style, practices and methods for each aspect of a
piece program written in that language. These conventions usually cover file
organization, indentation, comments, declarations, naming conventions, programming
practices, programming principles, programming rules of thumb, etc. Software programmers
are highly recommended to follow these guidelines to help improve the readability of
their source code and make software maintenance easier.

Some of the Best Practices for Java development are as follows.
• A class should not have more 2000 lines or so.
• Line Size should be fixed, usually that could be either 80 or 120 chars.
• Every Class and method should have the JavaDoc comments to give an idea on
    the purpose of that method or class.
• Method name should be started with a lower case alphabet.
• Use "StingBuffer ()" instead of concatenating the Strings like "xyz+abc".
• Use "String literals" like "abc" instead of using new String("abc").
• Avoid using System.gc() or Runtime.gc().
• Should not have any System.out statements in your code.
• Should not have any exception.PrintStackTrace () statements in your code.
• Should not catch the Runtime Exceptions like "NullPointers".
• Make sure the Exceptions will be propagated to Invoker class without dropping them
    in the middle.
• Use ArrayList instead of Vector , in the same way use HashMap instead of HashTable.
• Try to create the Collections such as ArrayList, HashMap with proper initial Size to
    avoid unnecessary delaying in Object creation.
• Avoid using Static in MultiThreaded Env.
• Avoid having Static methods in your Business logic layer,  if not you may lose the
    advantages of OOPs such as inheritance, runtime polymorphism.
• You need to use either Synchronized or Read/Write locks for your business methods
    in Multi Threaded ENV.
Close all external Connections such as Database-Connections, IO-Stream Connections
     in finally block.
• Check if you have any additional "For loops" or unnecessary Object Creation.
• Use Prepared Statements.
• Use Batch processing for Bulk Updates.
Clone (Prototype pattern) the Objects instead of creating New objects by using
    "new" operator.
• Use Object Pooling instead of creating unlimited new Objects.
• "SetTimeouts" for the DB Transactions as well as external Web Service or RMI calls.
• Use "ASYNC process" if you are performing a task that would not impact the User such
    as sending emails or running some Time-Consuming Reports.
• Use "Lazy Loading" while loading the Object Graph (which has Child Parent relation)
    into memory.
• Use Singleton classes or Caching APIs for storing the Static Data.
• Follow the Layered Structures, do not propagate the Web-Layer Objects like HTTPRequests,
    HTTPSessions ect., in Business-Logic-layer.
• Use the DTOs or VOs for Data Transfer between the Layers.



Back to top

2 )   What is a Singleton class ?


Ans)

Single class is a class for which only one Instance will be created per JVM. Singleton
classes would have Private Constructors so that instances will not be created from other
classes. In general Singleton classes are used to hold the static data like Properties
or some Constants in memory.

One difficulty you may face with the Singleton classes is keeping them in SYNC among all
the JVMs in a clustered ENV, you have to have your own mechanism for accomplish this.
Or you could avoid using singleton classes by using some popular In-Memory cache APIs
such as EHCache, which give you the opportunity of using their built-in Distributed Cache
features for clustered ENV.

Here is the sample:

class PropertyManager {
    private static PropertyManager propManager;
    private PropertyManager()  {
    }

    public static PropertyManager getInstance()  {
        if (null == propManager) {
            propManager = new PropertyManager();
        }
        return propManager;
    }
}



Back to top

3 )   What is the Use of ThreadLocal ?


Ans)

A thread-local variable effectively provides a separate copy of its value for each thread
that uses it.
 Each thread can see only the value associated with that thread, and is unaware
that other threads may be using or modifying their own copies.

Because thread-local variables are implemented through a class, rather than as part of the
Java language itself, the syntax for using thread-local variables is a bit more clumsy than for
language dialects where thread-local variables are built in.

To create a thread-local variable, you instantiate an object of class ThreadLocal. In following
Example "userName" is stored in a ThreadLocal.

Please note this really useful to Cache Some Data per a Request.

public class YourDataHolder {
   private static ThreadLocal dataVariable = new ThreadLocal();
   private static YourDataHolder dataHolderVar ;
   private YourDataHolder() {
   }
   public void storeDataToThreadLocal (String userName) {
    dataVariable.set(userName);
   }
   public String readDataFromThreadLocal ()  {
    if (dataVariable.get() != null) {
        return (String) dataVariable.get();
    }
   }
   public static ServiceVersionHolder getInstance () {
    if (dataHolderVar == null) {
     dataHolderVar = new YourDataHolder();
    }
    return dataHolderVar;
   }
}



Back to top

4 )   What is Thread Dump?, How to Take Thread Dump in Unix , Linux, Solaris, Windows?


Ans)


  • Thread Dump ?
    Sample Img 4

Thread Dump is nothing but a snap shot of your JVM process at a Given Point of Time.
Usually we take Thread Dump to pinpoint the issue (identifying the root cause) when the
Application hung or unresponsive or the performance of the application is unexpectedly low.
Thread Dump provides you the list of Threads with a stacktarce of operations currently
they are performing.

Should do the following to capture the Thread Dump:

Unix:
Find process id as follows
             ps -ef | grep java
 Perform Kill -3 on java process.
            Kill -3 <java process id>

Windows:
      Press ctrl+break



Back to top

5 )   How to solve "OutofmemoryError" ?


Ans)


  • OutofmemoryError ?
    Sample Img 5

"OutofmemoryError" error occurs when JVM is unable to allocate Memory for creating any
new variables while performing some task.

This could be solved in by following steps:

i) First and foremost, check the memory settings of your application (JVM), if there is
any scope to increase the Memory settings, please change those, if not you may need to
tune the application. So first please review the Memory Parameters i.e. "-Xmx. -Xmx" values,
usually you could find these in SetEnv bat (or .sh) file or you could also  provide these as
System (-D) parameters to JVM.

-Xmn512M -Xms1024M

ii) Tune the application by using some Profilers such as JProfilier or Optimize it and make sure
all Unused objects are reachable to Garbage Collectors by setting the NULL value to
garbage-collect them.

iii) Use soft Or Weak references to avoid this as shown below.
     private  SoftReference<byte[]> bufferRef;

iv) Close all Database Connections and File IO streams properly in Finally block as
shown below and avoid connection leaks.
     try{
        } finally {
          con.close();
     }
v) Close all IO streams which are used for performing File operations such as filinputsteam
 or filinputsteam.
          FileInputStream fin = null;
     try{ 
         fin = new FileInputStream(file)
        } finally {
          fin.close();
     }
vi) See if you could use Object Pool instead of creating unlimited new Objects.

 



Back to top

6 )   How to set -D Or System parameter ?


Ans)


  • System Parameter ?
    Sample Img 6

-D parameters are also called as the System Parameters. "System Parameters" are really
useful especially in Real-Time projects, where it requires you to input some parameters
to your App whose values could vary from one JVM to JVM (Env to ENV) dynamically,

e.g. "PropertyFile Names" , that could be varied from one ENV to another because the DEV
property file should not be used for Prod Environment.
 
Here are some additional cases in which we use these, most of these are related to
application "Configuration" such as “Property File Names” or “paths” or “Hibernate Config file path”
or some special “Lib paths” or Memory Settings, all of these could be varied based on ENVs.
 
This is how to set these parameters:
-Djava.util.logging.config.file=%CATALINA_BASE%\conf\logging.properties

Read this as following in your App :
System.getParamter (“java.util.logging.config.file”);

 



Back to top

7 )   What is Profiling , name some profiling Tools ?


Ans)


  • Memory Profiling ?
    Sample Img 7

Profiling is nothing but memory tuning, some cases you may encounter
"OutOfMemoryErrors" due to "Connection Leaks" Or "Memory Leaks" Or “Unnecessary Object
creation”, in order to Identify the root cause you may need to run your application by
using some Memory profiling tools such as "JProfiler" or "OptimizeIT" etc.,

Please take a look at the Question "How to solve OutOfMemoryErrors" for more details.



Back to top

8 )   Java Caching Techniques


Ans)

Caching plays vital role in real time development, Caching is nothing but storing Static
or very rarely changed data in memory or on disk to avoid unnecessary delays for fetching
data from different sources.

This one of the very important Technique that people to use improve performance

of your application.

Here are some examples for caching .

i) User Data and Roles :
In most of the applications, every User is associated with a set of different roles based
on which they are allowed to perform certain tasks.This User-Role data will not be changed
very frequently so this could be loaded into-memory (Cached) upon sever start up.  Whenever
it is required to check if the User is authorized to perform certain task , we could get the
Role data from Cache instead of getting from DataBase, this could avoid unnecessary Trips
to DataBase and improves the Performance.

ii)  Product And Offer Data:
In same way in most of the Sales-Ordering systems , Productions and Offer Data would not be
changed very frequently , so SKU data and Pricing data etc, could be cached
for better performance .

Techniques:

Singleton classes:
Just create the Singleton classes and cache the static data by using Java Collection APIs
such as Hashmap or List .

Java Caching APIs:
Use the Caching APIs such as EHCache, JCache etc.,

HttpSession:
You could store the data in user Session.



Back to top

9 )   EhCache Example ?


Ans)

 

Step 1: Get the EhCache Manager

     File f = new File(EHCACHE_CONFIG_FULL_PATH);
     BufferedInputStream bis = new BufferedInputStream(
      new FileInputStream(f));
     CacheManager cacheManager = CacheManager.create(bis);

  
Step 2 : Putting Data in Cache   
cacheManager.getCache(YOUR_CACHE).get(key));
Object valeu = element.getValue();
  
Step 3 : Getting Data From Cache
cacheManager.getCache(YOUR_CACHE).put(new Element(key, value));

Configuration : Ehcache.xml

 <cache name="YOUR_CACHE"
        maxElementsInMemory="1000"
        eternal="true"
        timeToLiveSeconds="0"
  timeToIdleSeconds="0"
        diskPersistent="false"
        overflowToDisk="false"
        memoryStoreEvictionPolicy="LRU"
    > 

 



Back to top

10 )   Java Template Engine ? Velocity Engine ?


Ans)


  • Velocity Engine
    Sample Img 10

A template engine is software that is designed to process the templates and

content information to produce output web documents. It runs in the context of a template system.

Some of the Popular Java Based Templating Egines are "FreeMarker","Velocity"

Quick example of Velocity Template :

Step 1: Create a .vm file

sayHello.vm:
  Hello $name !  How are you ?

Sample : input this to ve.getTemplate()
 
import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class HelloWorld
{
    public static void main( String[] args )
        throws Exception
    {
        /* initialize an engine  */
        VelocityEngine ve = new VelocityEngine();
        ve.init();
 
        /*  get the Template  */
        Template t = ve.getTemplate( "sayHello.vm" );
      
  /*  create a contex */
        VelocityContext context = new VelocityContext();
        context.put("name", "John");
 
        StringWriter writer = new StringWriter();
      
  t.merge( context, writer );
 
        System.out.println( writer.toString() );   
    }
}


Output : Please see below Name is replaced with "John"

Hello John !  How are you ?



Back to top

11 )   What is Pre-Compilation of JSPs , why do we need that?


Ans)

As we all know JSP will be compiled and converted into Servlets upon their First time access,
this degrades the Performance. So to avoid this in Real Time Applications, JSP are compiled
and converted into Servlets Classes while deploying the Application.

Weblogic :
Place the following in weblogic.xml. precompile

<jsp-descriptor>
  <jsp-param>
    <param-name>precompile</param-name>
    <param-value>true</param-value>

  </jsp-param>
</jsp-descriptor>

Tomcat :
Use this in your Build.xml
 
 <taskdef classname="org.apache.jasper.JspC" name="jasper" >
     <classpath>
         <pathelement location="${java.home}/../lib/tools.jar"/>
         <fileset dir="${ENV.CATALINA_HOME}/lib">
             <include name="*.jar"/>
         </fileset>
         <path refid="myjars"/>
      </classpath>
 </taskdef>

 <jasper verbose="0"
          package="my.package"
          uriroot="${webapps.dir}/${webapp.name}"
          webXmlFragment="${build.dir}/generated_web.xml"
          outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" />



more info...       Back to top

12 )   What is the purpose of an External Config file, how to set that in Classpath ?


Ans)

In Real Time applications, the "External Config" files play very important role.
Externalizing the Property files could ease your build and deployment process.
As these are placed in an external location (not included in WAR file) any change
to these would not require a new build and deployment.

In order to externilize the property files, you just need to place the property files in
an external folder and make that folder accessible to JVM by putting that in Classpath
as shown below. Assume that you place your propety files in "C:\conf"

i) Add this Folder to Set ENV or server Start Up script like this.
set "CLASSPATH=%CLASSPATH%%CATALINA_HOME%\bin\bootstrap.jar;C:\conf

ii) Or Add this right after Java Cmd as below.
java -cp c:\conf yourClass

 



Back to top

13 )   What is a Cluster ?


Ans)

A cluster is a group of servers running a Web application simultaneously, appearing to the world
as if it were a single server. To
balance server load, the system distributes requests to
different nodes within the server cluster, with the goal of optimizing system performance.
This results in higher availability and scalability -- necessities in an enterprise,
Web-based application.

High availability - if a single Web server fails, then another server takes over, as transparently
as possible, to process the request.

Scalability  - Scalability is an application's ability to support a growing number of users.

 



Back to top

14 )   What is Load Balancing ?


Ans)


  • Load Balancing/Cluster ?
    Sample Img 14

Load balancing is a computer networking methodology to distribute workload across multiple
computers or a computer cluster or other resources, to achieve optimal resource utilization,
maximize throughput, minimize response time, and avoid overload.

Some of the Features of a Load Balancer :


Asymmetric load: A ratio can be manually assigned to cause some backend servers to get a greater
share of the workload than others. This is sometimes used as a crude way to account for some
servers having more capacity than others and may not always work as desired.

Priority activation: When the number of available servers drops below a certain number, or load gets too
high, standby servers can be brought online

HTTP caching: the load balancer can store static content so that some requests can be handled without
 contacting the web servers.

Firewall: direct connections to backend servers are prevented, for network security reasons Firewall
 is a set of rules that decide whether the traffic may pass through an interface or not.

Content-aware switching: most load balancers can send requests to different servers based on the URL being requested.

The following two are important methods to balance a server load:

DNS round robin
Hardware load balancers.



Back to top

15 )   Sticky session ?


Ans)

Sticky session refers to the feature of many commercial load balancing solutions for web
to route the requests for a particular session to the same physical machine that serviced
the first request for that session.
This is mainly used to ensure that the in-progress session
is not lost as a result of requests for a session being routed to different servers.

Since requests for a user are always routed to the same machine that first served the request
for that session, sticky sessions can cause uneven load distribution across servers. If the
first accessed server is down for any reason User may lose the Session Data no Session
Replication happens in Sticky Session.

Here is the Sample load balancer Set up with apache MOD_PROXY 

   ProxyPass / balancer://mycluster/ stickysession=JSESSIONID nofailover=On
        ProxyPassReverse / ajp://yourcompany.com:8009
        ProxyPassReverse / ajp://yourcompany.com:8009
        <Proxy balancer://mycluster>
          BalancerMember ajp://yourcompany.com:8009 loadfactor=20
          BalancerMember ajp://yourcompany.com:8009 loadfactor=5
          ProxySet lbmethod=byrequests
        </Proxy>



more info...       Back to top

16 )   Consideration for making your application Clusterable ?


Ans)


  • Making your app Clusterable ?
    Sample Img 16

When you want to make your application Clusterable, you have to first identify what are thing 
(which holds the State data)should be synchronized among all the Machines in the Cluster for
supporting High avialblity Without impacting the application functionality.
Here are the list of things you should look at.

HTTP Session (Session Replication) :
     In a Clustered ENV, your application server keep the HttpSession state in Sync among all
  the Servers in Cluster, this could be by using different communication technique
  like IP MultiCast etc. So for better performance you have to do the following.


        i) Try to keep little data in HttpSession, do not keep pretty big Object graphs in
  HttpSession, becase each change to Session Data would triggers  session replication
  which serializes the Session state and transport that to all the Servers in cluster.

     ii) All the Objects stored in Session should be Seriazable , if not Session
   replication would be failed.

Stateful session beans :
   You should take the same considetaions as above, even in StateFul Session Beans case.

Singleton classes :
     By design as Singleton classes would be maintained as One Instance per JVM, so making
  a Singleton class Custable is a little Chanllenging as all the JVMs in any given Clusttered
  ENV would have their own Instance of Singleton classes.  So you have to manually keep 
  the  One possible solution for this issue is below.


i)  Serialize the First Instance of a singleton class and store in Database. Serialize the
    First Instance of a singleton class which is created on any JVM and store that in Database,
 let all other JVMs check in Database if a singleton class was already created before
 Creating their own Instance, this way we can make sure that the same Instance is being used
 by all the Servers.

JMS Queues:
You may need to use Distributed Queues or Topics.



Back to top

17 )   SSL VS VPN ?


Ans)

VPN :
A virtual private network (VPN) is a private network that interconnects remote
(and often geographically separate) networks through primarily public communication
infrastructures such as the Internet.VPNs provide security through tunneling protocols and
security procedures [1] such as encryption.


SSL:
SSL (Secure Sockets Layer) is the accepted protocol used to protect data that is sent between a
web site and a web browser. An encrypted SSL connection requires that all data passed between
the browser and the web site server be encrypted by the sender and decrypted by the receiver.
SSL can prevent unauthorized parties from gaining access to sensitive, confidential, or personal
information such as a phone numbers or addresses.

SSL is used to encrypt a web session only, and is needed for e-commerce. VPN permits secure
remote access to your network (protocols other than WWW), so that people working from home can
"dial-in" to access corporate resources (databases, source-code control systems, email, etc)



Back to top

18 )   java.io.IOException: Not enough space During JSP compile ?


Ans)


  • No enough space?
    Sample Img 18

This Exception occurs if the Linux or Solaris box in which you host your Web App does
not have enough space to perform any task which requires some Disk Space
such as compiling
a Jsp or adding log statements to Log files as Disk is full.

You could check if the Disk is full by using the following Command
    df –h

Solve this by freeing some space on disk by deleting or moving the old log files.



Back to top

19 )   When do you encounter "NoClassDefFound" Exception ?


Ans)

NoClassDefFoundError exception occurs when Java Virtual Machine is not able to find a
particular class at runtime which was available during compile time. for example if
we have a method call from a class or accessing any static member of a Class and that
class is not available during run-time then JVM will throw NoClassDefFoundError.

It is important to understand that this is different than ClassNotFoundException which
comes while trying to load a class (by using Class.forName()) at run-time only and name
was provided during runtime not on compile time.

To solve this :
• Please check if the required Jar file is there in classpath by printing the classpath
 as follows"system.getParamter("classpath");" Or ECHO classpath in Server start up file.
 
• Please get and add the Jar file to class path as shown in above question.

java -cp yourJar.jar yourClass



Back to top

20 )   If you are not able read a file, what could be done to solve this issue ?


Ans)

Solution depends upon the way you read the file.

i) If you are using Java IO package, please make sure that File exists in given file Path
and also share the Folder (if that is on a remote system) in which you have the file
and make sure that is accessible to JVM.
 
ii) If you are trying to read a File as Resource, please follow the following two steps.

 a) Add the file (Folder which contains the Folder) to the class path.

 b) Use getClassLoader to load this class as shown below.
 getClass().getClassLoader().getResource("Configuration.properties").getFile();



Back to top

21 )   File Not Found 404 Error


Ans)

"404 File Not Found Error" occurs when the web Container unable to find the file
or unable to perform the requested activity
with the given URL which may refer to
a Service or a HTML file or a JSP.
 
If you get this Exception while making a Web Service call as a Soap Fault Exception,
make sure the Web Service is up and Running (by accessing the Web Service END Point).

If you encounter this while accessing a Servlet, please make sure Servlet loaded
properly in your web server
by giving some debug statements in  init() method of
the Servlet.

If you get this error while accessing the Static file such as HTML or Images , make
sure these are there in your Web folder of your deployable artifacts.



Back to top

22 )   500 Internal Server Error ?


Ans)

500 Internal Server Error occurs while you’re the HTTP Client (browser) is able to make
successful call to the Server (web container) , but your Web Container unable to build
the response due to some Runtime Error such as NullPointer or ArrayIndexBound etc.

Unlike “404 File Not Found Exception”, in this case the Web Container is able to find
the Service or a File.

To address this issue, please take a look at the server Log Files, get the full stacktarce
and resolve the issue.

If get this exception while accessing a JSP, meaning web container unable to compile the
Jsp due to above mentioned Runtime exceptions.



Back to top

23 )   How to solve SocketTimeoutException ?


Ans)

Socket Timeout would occur if the Client Socket (may be Tcp/Http/Soap clients) does not get
the response in configured timeframe for any given request, in order to avoid this you need
to change the Client Socket Timeout settings as shown below.

If you encounter this issue while making a Web Service call, the APIs like Axis, CFX etc.,
have some default Socket Timeout settings, you may need to override those.

If you create your own HTTP you need to have that set up on your own.

Either way setting SocketTimeout is really important, if not the Client may wait for an
undefined amount of time for the response which may hung your applications.

HTTP Client:
httpclient.getParams().setParameter("http.socket.timeout", new Integer(1000));

In Axis 1.4
Override the Default Value as shown below in the ServicePort class.

AxisProperties.setProperty(org.apache.axis.components.net.
   DefaultCommonsHTTPClientProperties.CONNECTION_DEFAULT_SO_TIMEOUT_KEY, '10000');
 

AxisProperties.setProperty(org.apache.axis.components.net.
        DefaultCommonsHTTPClientProperties. CONNECTION_DEFAULT_CONNECTION_TIMEOUT_KEY,

10000');


Please note if this Timeout happens due to network issues or Performance issue , you may need
to handle them separately.



Back to top

24 )   Transaction TimedOut ?


Ans)

"Transaction TimedOut" exception occurs when your Transaction Manager which could be a
Session Bean, Hibernate Session, or a JDBC connection unable to perform the given Database
operations in configured time frame
, possible reasons would be long running Database Queries.

In case of Container managed Transaction this Timeout is managed by JTA.

In order to avoid this you need to do the following
i) Increase the JTA Timeout value in your Application Server by using Admin console.
ii) Tune your code as well as Database queries, as a first Step towards the Tuning add indexes
to all required Databases tables
. Also set appropriate DB PAGE_SIZE.



Back to top

25 )   Got "JDBC Connection Already Closed" Exception ?


Ans)

"JDBC Connection Already Closed " exception occurs when you try to use the JDBC Statement
or ResultSet of a Connection which has been already Closed
. To avoid this please review
the code and see where you are closing the Connection.



Back to top

26 )   java.lang.NoSuchMethodError


Ans)

"NoSuchMethodError" is thrown if an application tries to call a specified method of a class
(either static or instance), and that class no longer has a definition of that method.

One of the possible reasons for this could be the Jar or Class conflicting, this may
happen due to having the old Versions of Jar files or classes (_JspServlets classes
in Temp Directory) files in the Classpath.

Now a days most of the Web Applications are loaded with Tons of Jar files, as a result
there are chances that the same Class file could reside in multiple Jars files. As per
design JVM picks up (ClassLoader loads) the Class from the Jar which it reads first in
Classpath, which could be a wrong version of the Class which does not have the specified
method definition.

To avoid this, you need to remove all Older Versions of the Classes and Jars, and make
sure you have the Lasted Jar file first in Classpath.

If you encounter this while accessing the JSP, please clean the Temp folder of your
App server.



more info...       Back to top

27 )   DB Connections Max out ?


Ans)

"DB Connections Max out" Error occurs when all available connections are in use and
the Database is unable to accept any more new Connections. 

To address this issue, DBA has to do the following:
i) Increase the number of allowed Connections.
ii) Kill some of the long living connections or restart the DB.

Dev Team has to do the following:
i) Review the Code and make sure returning the unused DB connections properly back to
Connection Pools. Avoid Connection Leaks.



Back to top

28 )   When you could encounter "FileNotFound" Exception? How to solve ?


Ans)

Solution depends upon the way you read the file.

i) If you are using Java IO package, please make sure that File exists in given file Path
and also share the Folder (if that is on a remote system) in which you have the file
and make sure that is accessible to JVM.
 
ii) If you are trying to read a File as Resource, please follow the following two steps.

 a) Add the file (Folder which contains the Folder) to the class path.

 b) Use getClassLoader to load this class as shown below.


 getClass().getClassLoader().getResource("Configuration.properties").getFile();



Back to top

29 )   How to find the Java Process Id in Unix ?


Ans)

You may need to find the Java Process Id in Server Box for taking Thread Dump or
restarting the App Server without using Stop server script.

Simply use ps command to get the process id as follows:

ps aux | grep Java

 



Back to top

30 )   Are you not able to read a file ?, how to solve ?


Ans)

There are two possible solutions for this.

i) If you want to do this by using java.IO package , you just need share the Folder and make sure that this file (the folder from which you are reading
   that file)is accessible to JVM.

ii) If not , you want to do this by reading this file a resource, please do the following.
       a) Add the file(Folder which contains the Folder) to the class path and read using file API.
       b) Use getClassLoader() method of "Class" to load the File as a resource as shown below, this method looks for the file in Classpath.
   
   getClass().getClassLoader().getResource("Configuration.properties").getFile();



Back to top

31 )   What is Java De-compilation ?


Ans)

In real time development, sometimes it may require you to do reversing engineering i.e.
generating the Java Files from the Class files to nail down some of the issues.
The process of generating the Java Files from the Class files is called De-compilation.

Please do the following for De-compilation.
i) Use JAD or some other popular de-compilers, there are GUIs such as JD-GUI are available.



Back to top

32 )   When you get "ClassNotFound" Exception?


Ans)

This Exception will be thrown when an application tries to load in a class through its string name using:

    The forName method in class Class.
    The findSystemClass method in class ClassLoader .
    The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

To solve make sure the required class in class path by using class path , could be done in two ways . Also Make sure you're using your platforms classpath separator. ':' in Unix, and ';' in Windows.

i) set claspath = yourJar.jar;%classpath%

ii)   java -cp c:\home\ann\src;c:\home\ann\public_html\classes\compute.jar
     -Djava.rmi.server.codebase=file:/c:/home/ann/public_html/classes/compute.jar
     -Djava.rmi.server.hostname=mycomputer.example.com
     -Djava.security.policy=server.policy
        engine.ComputeEngine
 



Back to top

33 )   Tail the Log Files ?


Ans)

To tail the logs in Unix or Linux please use the following command. The following
command prints the last 1000 lines of the given log file.

Tail -1000f  test.log



Back to top

34 )   Search For a String in all the Folder ?


Ans)

find . -type f -exec grep -l "yourword" {} +

Or
 
find . -exec grep "yourword" '{}' \; -print

Or
 
find /path/to/dir -type f | xargs grep -l "yourword"



Back to top

35 )   How to use SUDO in unix ?


Ans)

sudo -u druser -s



Back to top

36 )   How to Check the Disk Space in Unix Or Linux ?


Ans)

Use DF command for checking Disk Space.

df - k



Back to top

37 )   Starting Tomcat in Debug Mode ?


Ans)

 

Use the following command to start the Tomcat in debug mode.

Catalina jpda start



Back to top

38 )   java connection reset error ?


Ans)

JDBC Connection Reset error occurs when your current DB connections was aborted due to
Network issues
and your connection manager starts a new connection to DB.
 



Back to top

39 )   java.net.ConnectException: Connection refused ?


Ans)

This exception usually occurs when there is no service listening on the port you are
trying to connect to.

The following are also possible reasons.
- The port is wrong
- Firewall is stopping your request.

To avoid please make sure use the correct Port or get the Port opened.



Back to top

40 )   How to generate a Private/Public Key ?


Ans)

Create a Key Pair Generator:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");

Initialize the Key-Pair Generator

ecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);

Generate the Pair of Keys

KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();



more info...       Back to top

41 )   How to create a Jar file ?


Ans)

Make sure you have   jdk/bin  in class.

jar -cvf test.jar  *.*

If you want to create a WAR file use

jar -cvf test.war  *.*



Back to top

42 )   Log4J Appenders ?


Ans)

Step 1:

You need to create a Log4J property files , take a look at a sample below.

log = C://logs//log

log4j.rootLogger = INFO, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.File=${log}/ServiceResult.html

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=HTML Layout Example
log4j.appender.FILE.layout.LocationInfo=true

 Step 2:

static {

PropertyConfigurator.configure("C://ServiceTestNew//conf//log4j.properties");

}

Step 3:

Get the Log as shown below.

private final static Logger log = Logger.getLogger(ValidateLogger.class);

You want to create own Appender ? For example you want to logs the statements into a

HTML file ? Please take a look at MISC tab.



Back to top

43 )   java.lang.IncompatibleClassChangeError


Ans)

This Error occurs  when you compile a class with Different Version of JRE other than
the one on which it is run (the Server where you deploy this class files).

For example, you compile a Java file by using Eclips which is using JRE 1.6, create a
Jar file these class, and you deploy this Jar in a Env which is using JRE 1.4, this
exception will be thrown.
 
Solution :
 
Please recompile this file with the correct version of JRE, in above case you have re-compile
with JRE 1.4

 



Back to top

44 )   javax.naming.NameNotFoundException


Ans)

You get this Exception during the JNDI look up, if the Bean or the Resource is not available with the
given JNDI name , this will be thrown.
 

In order to fix do the following.
 

i) Firstly review the way you do JNDI look up is incline with your App Server Specification.
 

J2ee Server (sun) :
Context subcontext = (Context) ic.lookup("java:comp/env");
DataSource dataSource = (DataSource)
subcontext.lookup("jdbc/default-datasource");

Weblogic :
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,
"t3://localhost:7001");
try {
ctx = new InitialContext(ht);
ctx.bind("my_object", MyObect);
ServiceBean bean = (ServiceBean)ctx.lookup("ejb.serviceBean");
}
catch (NamingException e) {
// a failure occurred
}

WebSphere:
Properties p = new Properties();
p.put("org.omg.CORBA.ORBClass","com.sun.CORBA.iiop.ORB");
p.setProperty( javax.naming.Context.INITIAL_CONTEXT_FACTORY,
"com.ibm.websphere.naming.WsnInitialContextFactory" );
p.setProperty( "java.naming.provider.url", "iiop://HOSTNAME:PORT" );

String connectionfactoryjndi="jms/testQCF";
Context jndiContext = new InitialContext();
jndiContext = new InitialContext( p );

 

ii) Secondly please restart your Application Server like Welogic or WebSphere beacuse unless
you restart some of the App Services will not BIND the resource .
 

iii) Then  take a look at JNDI tree in App Server if it has one built in if not print the resource names as shown below and search for your Resource.
 

Print JNDI Tree :
Context ic = new InitialContext(properties);
context.list(ct);


Browse JNDI Tree:
http://servername:port_number/jndiTree/index.html



Back to top

45 )   How to perform one-time activities in a java Class ?


Ans)

You have to use

i) Static block to perform one-time activities in a java Class as shown below.

  public class YourJavaClass
{
static{
      baseDir = AppConfigManager.getAppConfigManager().getClientConfig("basedir").trim();
      if(!baseDir.endsWith("/")){
        baseDir = baseDir + "/";
      }
    }

 
}

ii) Use Singleton class as shown above.

 



Back to top

Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet
Not Included Yet

This Portal is intended to put all Java/J2ee related topics at one single place for quick referance, not only Technical , but also the Project Management Related thing such as Development Process methodoogies build process, unit testing etc.,

This Portal has More than 500 Java Interview Questions (also could be Considered as Quick Notes) very neatly separated topic by topic with simple diagrams which makes you easily understandable. Importantly these are from our Realtime expericance.




Face Book

Get a PDF

Face Book
Same look (Read) on any device, this is Ads free

Go To Site Map