Thursday 19 February 2015

Adopting Real Time Communication: Openfire vs Tigase

There is a growing trend right now to add real time communication to your enterprise collaboration solution. Companies are taking a page from the play books of Facebook and Yahoo (who copied Twitter) and are adding Instant Messaging to their service offerings. When it comes to IM, consider XMPP which is the protocol designed from day one for IM.
When setting up your own chat server, there are two open source projects that you should seriously consider; Openfire and Tigase.
Sponsored by such corporate leaders in IM as Jive, IBM, Apple, and Google, Openfire is an XMPP server written in Java and stewarded by Ignite Realtime.
Tigase has more humble and open source traditional origins where an engineer, seasoned in server development, had an “itch to scratch” and started building this XMPP server.
How are Tigase and Openfire similar? They both fully support the XMPP standard and many of the more popular extensions to that standard. They both parallel the high extensibility of the protocol with their own pluggable architecture. They are both written in Java.
You can extend the chat server functionality by writing your own plugins and components. The heart of the XMPP is in its three main stanzas; IQ, presence, and message. IQ is mostly about roster management. Presence is how those away and available notifications get delivered. Messages are what you text back and forth with your friends. If you want to add new functionality to those stanzas, or create your own, then you should write a plugin.If you want to write a chat bot (i.e. a robot that you can exchange messages with), then you should write a component.
A JID (Jabber IDentifier) is how you log in to the server and how you address other users. They look a lot like email addresses. A component has its own JID whereas a plugin does not.
How are Tigase and Openfire different? Openfire provides a web based administrative interface which you can extend with your own JSP. You can add your own plugins by packaging them up in a WAR file and adding them through the admin interface. Openfire depends on being hosted by a J2EE application container such as Tomcat. Tigase is a stand-alone program that is executed by itself. The only administrative interface for Tigase is a text based properties file that you can edit before launching the Tigase service. To get Tigase to load your plugins and components, you just have to ensure that your JAR files are in the classpath prior to starting Tigase.
With Tigase, you can also plug in your own repository instead of depending on their relational database. Tigase is more oriented towards high scalability with its support for clustering, virtual hosts, and thread management.
Which one is best for your needs? If you are more concerned about IT footprint and cost containment than you are about serving large numbers of people, then you should start with Openfire. If you already know that you are going to have to serve large numbers of users and are willing to commit the resources of a server farm, then you won’t go wrong with Tigase.

Thursday 27 February 2014

Association, Aggregation, Composition, Abstraction, Generalization, Realization and Dependency


These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.

Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!


Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specialization to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Monday 10 February 2014

JSP Tutorial


What is JavaServer Pages?

JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.


Why Use JSP?

JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
  • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files.
  • JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
  • JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
  • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.

 

Setting up JSP Environment

This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately.
You can downloaded SDK from Oracle's Java site: Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME=C:\jdk1.5.0_20
Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.5.0_20
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java.

 

Setting up Web Server: Tomcat

A number of Web Servers that support JavaServer Pages and Servlets development are available in the market. Some web servers are freely downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine:
  • Download latest version of Tomcat from http://tomcat.apache.org/.
  • Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.
Tomcat can be started by executing the following commands on windows machine:
 %CATALINA_HOME%\bin\startup.bat
 
 or
 
 C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/startup.sh
 
or
 
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result:
Tomcat Home page
Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org

 

JSP Processing:

The following steps explain how the web server creates the web page using JSP:
  • As with a normal page, your browser sends an HTTP request to the web server.
  • The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
  • The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior of the page.
  • The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.
  • A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response.
  • The web server forwards the HTTP response to your browser in terms of static HTML content.
  • Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
JSP Processing

 

The Scriptlet:

A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet:
<% code fragment %>
You can write XML equivalent of the above syntax as follows:
<jsp:scriptlet>
   code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is setup as per environment setup tutorial.
Let us keep above code in JSP file hello.jsp and put this file in C:\apache-tomcat-7.0.2\webapps\ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate following result:
Hello World

 

JSP Declarations:

A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
<jsp:declaration>
   code fragment
</jsp:declaration>
Following is the simple example for JSP Declarations:
<%! int i = 0; %> 
<%! int a, b, c; %> 
<%! Circle a = new Circle(2.0); %> 

 

JSP Expression:

A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression:
<%= expression %>
You can write XML equivalent of the above syntax as follows:
<jsp:expression>
   expression
</jsp:expression>
Following is the simple example for JSP Expression:
<html> 
<head><title>A Comment Test</title></head> 
<body>
<p>
   Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body> 
</html> 
This would generate following result:
Today's date: 11-Sep-2010 21:24:25

 

JSP Comments:

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>
Following is the simple example for JSP Comments:
<html> 
<head><title>A Comment Test</title></head> 
<body> 
<h2>A Test of Comments</h2> 
<%-- This comment will not be visible in the page source --%> 
</body> 
</html> 
This would generate following result:

 

A Test of Comments

There are a small number of special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<%-- comment --%>A JSP comment. Ignored by the JSP engine.
<!-- comment -->An HTML comment. Ignored by the browser.
<\%Represents static <% literal.
%\>Represents static %> literal.
\'A single quote in an attribute that uses single quotes.
\"A double quote in an attribute that uses double quotes.

 

JSP Directives:

A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
There are three types of directive tag:
Directive Description
<%@ page ... %>Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %>Includes a file during the translation phase.
<%@ taglib ... %>Declares a tag library, containing custom actions, used in the page
We would explain JSP directive in separate chapter JSP - Directives

 

JSP Actions:

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available:
Syntax Purpose
jsp:includeIncludes a file at the time the page is requested
jsp:includeIncludes a file at the time the page is requested
jsp:useBeanFinds or instantiates a JavaBean
jsp:setPropertySets the property of a JavaBean
jsp:getPropertyInserts the property of a JavaBean into the output
jsp:forwardForwards the requester to a new page
jsp:pluginGenerates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:elementDefines XML elements dynamically.
jsp:attributeDefines dynamically defined XML element's attribute.
jsp:bodyDefines dynamically defined XML element's body.
jsp:textUse to write template text in JSP pages and documents.
We would explain JSP actions in separate chapter JSP - Actions

JSP Implicit Objects:

JSP supports nine automatically defined variables, which are also called implicit objects. These variables are:
Objects Description
requestThis is the HttpServletRequest object associated with the request.
responseThis is the HttpServletResponse object associated with the response to the client.
outThis is the PrintWriter object used to send output to the client.
sessionThis is the HttpSession object associated with the request.
applicationThis is the ServletContext object associated with application context.
configThis is the ServletConfig object associated with the page.
pageContextThis encapsulates use of server-specific features like higher performance JspWriters.
pageThis is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionThe Exception object allows the exception data to be accessed by designated JSP.
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.

Control-Flow Statements:

JSP provides full power of Java to be embedded in your web application. You can use all the APIs and building blocks of Java in your JSP programming including decision making statements, loops etc.

Decision-Making Statements:

The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between Scriptlet tags.
<%! int day = 3; %> 
<html> 
<head><title>IF...ELSE Example</title></head> 
<body>
<% if (day == 1 | day == 7) { %>
      <p> Today is weekend</p>
<% } else { %>
      <p> Today is not weekend</p>
<% } %>
</body> 
</html> 
This would produce following result:
Today is not weekend
Now look at the following switch...case block which has been written a bit differentlty using out.println() and inside Scriptletas:
<%! int day = 3; %> 
<html> 
<head><title>SWITCH...CASE Example</title></head> 
<body>
<% 
switch(day) {
case 0:
   out.println("It\'s Sunday.");
   break;
case 1:
   out.println("It\'s Monday.");
   break;
case 2:
   out.println("It\'s Tuesday.");
   break;
case 3:
   out.println("It\'s Wednesday.");
   break;
case 4:
   out.println("It\'s Thursday.");
   break;
case 5:
   out.println("It\'s Friday.");
   break;
default:
   out.println("It's Saturday.");
}
%>
</body> 
</html> 
This would produce following result:
It's Wednesday.

Loop Statements:

You can also use three basic types of looping blocks in Java: for, while,and do.while blocks in your JSP programming.
Let us look at the following for loop example:
<%! int fontSize; %> 
<html> 
<head><title>FOR LOOP Example</title></head> 
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
   <font color="green" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%}%>
</body> 
</html> 
This would produce following result:
JSP Tutorial
JSP Tutorial
JSP Tutorial
Above example can be written using while loop as follows:
<%! int fontSize; %> 
<html> 
<head><title>WHILE LOOP Example</title></head> 
<body>
<%while ( fontSize <= 3){ %>
   <font color="green" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%fontSize++;%>
<%}%>
</body> 
</html> 
This would also produce following result:
JSP Tutorial
JSP Tutorial
JSP Tutorial

JSP Operators:

JSP supports all the logical and arithmetic operators supported by Java. Following table give a list of all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.
Category  Operator  Associativity 
Postfix  () [] . (dot operator) Left to right 
Unary  ++ - - ! ~ Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   >> >>> <<   Left to right 
Relational   > >= < <=   Left to right 
Equality   == !=  Left to right 
Bitwise AND  Left to right 
Bitwise XOR  Left to right 
Bitwise OR  Left to right 
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %= >>= <<= &= ^= |=  Right to left 
Comma  Left to right 

JSP Literals:

The JSP expression language defines the following literals:
  • Boolean: true and false
  • Integer: as in Java
  • Floating point: as in Java
  • String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
  • Null: null

Tomcat 7.0

Tomcat 7.0 for Beginners

Tomcat, or officially named Apache Tomcat is a light-weight web container used for deploying and running web application based on Java. Just like apache for PHP as container, tomcat’s role is becoming a runtime for java web application. There are so many web container in the world but i choose tomcat as this tutorial since tomcat is quite easy to be understood and the server management is not that difficult. So for beginner, tomcat is a good kickstart to a real application server. For development, tomcat is a best friend since it has a very quick startup and it’s reliable for small number of applications.
INSTALLING TOMCAT 7.0

1. Download your Tomcat 7.0
Download the latest tomcat 7.0 in here.
Note : I prefer to use the distribution version one, so i recommend to choose any files except the installer version for windows since it is easy to be modified and to be moved to other computer.
2. Extract the downloaded file
Extract the file, then you will see a structure like this :

Folder Structure
After you finished this steps, you have succesfully installed your tomcat to your computer. Now let’s heading on the configuration.

CONFIGURING TOMCAT

1. Define administrator password
In tomcat, administrator term is defined as manager. In default, there will be no user in tomcat 7.0 as a manager. You have to add yours. To add new user, go to ${TOMCAT_INSTALLATION_DIR}/conf/ and open tomcat-users.xml.

At the first time you will see line 29 to 35 will be commented. Please uncomment these lines by removing tag. After that, add additional line for creating your user, and the code will be seen something like this :
1
2
3
4
5
6
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="haka" password="haka" roles="manager-gui"/>
Note : Pay attention for the most bottom line. The username i set to “haka” and password set to “haka”. You can freely change these 2. But if you want the user to be manager, add manager-gui as the roles.
2. Configure local port
To configure any ports in Tomcat, go to ${TOMCAT_INSTALLATION_DIR}/conf/ and open file server.xml. After that, you can see whole configuration for server will be listed up there. For now, we will just customize port for host only. Go to line 67 in the file then you will see listing code like this :

You can change the port into any available port you like.
Note : If you have Oracle database installed, it might make a conflict since oracle listener use port 8080. So remember, if you have an oracle database installed, highly recommended that you change the port into other port, for example 8005, 8088, 8001, 8800,or whatever port you like ;). And also, you can change the connection timeout variable. This variable define how long will the system wait for starting the server. in this case, the value is 20000, means that the system will wait for 20 seconds IF the server is not tend to start.
I have oracle database installed in my current computer and i prefer port 8088, so that i change to port to 8088 :
1
2
3
<Connector port="8088" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
For a while, you have done with the minimum configuration for tomcat.
3. Starting the service
For starting the service, go to ${TOMCAT_INSTALLATION_DIR}/bin/ then execute file startup.bat. If everything is working fine, you will see a pop up uneditable command prompt windows like this :

Congratulations!! You have succesfully started your tomcat server :D
4. Accessing root directory in server
Go to your browser and type this :
http://localhost:8088/
The 8088 port is really depend on what port you set in the server.xml. If you use 8080, then you have to type localhost:8080, and so on. If it’s successful, then you will see display like this :

5. Administering your server
You have set your username and password for the manager. If you want to administer your server, go to http://localhost:8088/manager/html. Then a pop dialog will be prompted, requesting user name and password.

Enter your username and password (for my case, user is haka and password is haka). If it’s succesfull, the screen will drive you to the manager screen :

Friday 7 February 2014

Core JAVA Interview Questions-5

148)What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects.

149)What is a native method?

A native method is a method that is implemented in a language other than Java.

150)What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.

151)What comes to mind when someone mentions a shallow copy in Java?

Object cloning.

152)What is singleton class?

Singleton class means that any given time only one instance of the class is present, in one JVM.

AWT and SWING Interview Questions


153)Which containers use a border layout as their default layout?

The Window, Frame and Dialog classes use a border layout as their default layout.

154)Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.

155)What are peerless components?

The peerless components are called light weight components.

156)is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

157)What is a lightweight component?

Lightweight components are the one which doesn?t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. For example, Swing components.

158)What is a heavyweight component?

For every paint call, there will be a native call to get the graphical units.For Example, AWT.

159)What is an applet?

An applet is a small java program that runs inside the browser and generates dynamic contents.

160)Can you write a Java class that could be used both as an applet as well as an application?

. Yes. Add a main() method to the applet.

Internationalization Interview Questions


161)What is Locale?

A Locale object represents a specific geographical, political, or cultural region.

162)How will you load a specific locale?

By ResourceBundle.getBundle(?) method.

Java Bean Interview Questions


163)What is a JavaBean?

are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java.


Core JAVA Interview Questions-4

17) What is Garbage Collection?

Garbage collection is a process of reclaiming the runtime unused objects.It is performed for memory management. more details...

118) What is gc()?

gc() is a daemon thread.gc() method is defined in System class that is used to send request to JVM to perform garbage collection.

119) What is the purpose of finalize() method?

finalize() method is invoked just before the object is garbage collected.It is used to perform cleanup processing.

120) Can an unrefrenced objects be refrenced again?

Yes.

121)What kind of thread is the Garbage collector thread?

Daemon thread.

122)What is difference between final, finally and finalize?

final: final is a keyword, final can be variable, method or class.You, can't change the value of final variable, can't override final method, can't inherit final class.
finally: finally block is used in exception handling. finally block is always executed.
finalize():finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected.The finalize() method can be used to perform any cleanup processing.

123)What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.

124)How will you invoke any external process in Java?

By Runtime.getRuntime().exec(?) method.

I/O Interview Questions


125)What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

126)What an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

Serialization Interview Questions


127) What is serialization?

Serialization is a process of writing the state of an object into a byte stream.It is mainly used to travel object's state on the network. 

128) What is Deserialization?

Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.

129) What is transient keyword?

If you define any data member as transient,it will not be serialized.

130)What is Externalizable?

Externalizable interface is used to write the state of an object into a byte stream in compressed format.It is not a marker interface.

131)What is the difference between Serializalble and Externalizable interface?

Serializable is a marker interface but Externalizable is not a marker interface.When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

Networking Interview Questions


132)How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?

By InetAddress.getByName("192.18.97.39").getHostName() where 192.18.97.39 is the IP address.

Reflection Interview Questions


133) What is reflection?

Reflection is the process of examining or modifying the runtime behaviour of a class at runtime.It is used in:
  • IDE (Integreted Development Environment) e.g. Eclipse,MyEclipse,NetBeans.
  • Debugger
  • Test Tools etc.

134) Can you access the private method from outside the class?

Yes, by changing the runtime behaviour of a class if the class is not secured.

Collection Interview Questions

In java, collection interview questions are mostly asked by the interviewers. Here is the list of mostly asked collection interview questions with answers.

135) What is difference between ArrayList and Vector?

ArrayListVector
1) ArrayList is not synchronized.1) Vector is synchronized.
2) ArrayList is not a legacy class.2) Vector is a legacy class.
3) ArrayList increases its size by 50% of the array size.3) Vector increases its size by doubling the array size.

136) What is difference between ArrayList and LinkedList?

ArrayListLinkedList
1) ArrayList uses a dynamic array.1) LinkedList uses doubly linked list.
2) ArrayList is not efficient for manipulation because a lot of shifting is required.2) LinkedList is efficient for manipulation.

137) What is difference between HashMap and Hashtable?

HashMapHashtable
1) HashMap is not synchronized.1) Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values.2) Hashtable cannot contain any null key nor value.

138)What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.

139) What is difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key,value).

140)What is difference between HashMap and TreeMap?

HashMapTreeMap
1) HashMap is can contain one null key.1) TreeMap connot contain any null key.
2) HashMap maintains no order.2) TreeMap maintains ascending order.

141) What is difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

142) What is difference between List and Set?

List can contain duplicate elements whereas Set contains only unique elements.

143) What is difference between Iterator and ListIterator?

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

144) Can you make List,Set and Map elements synchronized?

Yes, Collections class provides methods to make List,Set or Map elements as synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

145) What is difference between Iterator and Enumeration?

IteratorEnumeration
1) Iterator can traverse legacy and non-legacy elements.1) Enumeration can traverse only legacy elements.
2) Iterator is fail-fast.2) Enumeration is not fail-fast.
3) Iterator is slower than Enumeration.3) Enumeration is faster than Iterator.

146) What is difference between Comparable and Comparator?

ComparableComparator
1) Comparable provides only one sort of sequence.1) Comparator provides multiple sort of sequences.
2) It provides one method named compareTo().2) It provides one method named compare().
3) It is found in java.lang package.3) it is found in java.util package.
4) If we implement Comparable interface, actual class is modified.4) Actual class is not modified.

147) What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

Core JAVA Interview Questions-3


73) What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors.It is mainly used to handle checked exceptions.

74)What is difference between Checked Exception and Unchecked Exception?

1)Checked Exception:

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at compile-time.

2)Unchecked Exception:

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-time. 

75)What is the base class for Error and Exception?

Throwable.

76)Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

77)What is finally block?

  • finally block is a block that is always executed.

78)Can finally block be used without catch?

  • Yes, by try block. finally must be followed by either try or catch.

79)Is there any case when finally will not be executed?

  • 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).

80)What is difference between throw and throws?

1)throw is used to explicitly throw an exception.throws is used to declare an exception.
2)checked exceptions can not be propagated with throw only.checked exception can be propagated with throws.
3)throw is followed by an instance.throws is followed by class.
4)throw is used within the method.throws is used with the method signature.
5)You cannot throw multiple exceptionYou can declare multiple exception e.g.
public void method()throws IOException,SQLException.

81)Can an exception be rethrown?

Yes.

82)Can subclass overriding method declare an exception if parent class method doesn't throw an exception ?

Yes but only unchecked exception not checked. 

83)What is exception propagation ?

Forwarding the exception object to the invoking method is known as exception propagation.

Core Java: String Handling Interview Questions

There is given a list of string handling interview questions with short and pointed answers. If you know any string handling interview question, kindly post it in the comment section.

84)What is the meaning of immutable in terms of String?

The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value can't be changed.

85)Why string objects are immutable in java?

Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java

86)How many ways we can create the string object?

There are two ways to create the string object, by string literal and by new keyword.

87)How many objects will be created in the following code?

  1. String s1="Welcome";  
  2. String s2="Welcome";  
  3. String s3="Welcome";  
Only one object.

88)Why java uses the concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

89)How many objects will be created in the following code?

  1. String s=new String("Welcome");  
Two objects, one in string constant pool and other in non-pool(heap).

90)What is the basic difference between string and stringbuffer object?

String is an immutable object. StringBuffer is a mutable object.

91)What is the difference between StringBuffer and StringBuilder ?

StringBuffer is synchronized whereas StringBuilder is not synchronized.

92)How can we create immutable class in java ?

We can create immutable class as the String class by defining final class and

93)What is the purpose of toString() method in java ?

The toString() method returns the string representation of any object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Core Java : Nested classes and Interfaces Interview Questions


94)What is nested class?

A class which is declared inside another class is known as nested class. There are 4 types of nested class member inner class, local inner class, annonymous inner class and static nested class. 

95) Is there any difference between nested classes and inner classes?

Yes ofcourse! inner classes are non-static nested classes i.e. inner classes are the part of nested classes. 

96) Can we access the non-final local variable, inside the local inner class?

No, local variable must be constant if you want to access it in local inner class. 

97)What is nested interface ?

Any interface i.e. declared inside the interface or class, is known as nested interface. It is static by default. 

98)Can a class have an interface?

Yes, it is known as nested interface. 

99)Can an Interface have a class?

Yes, they are static implicitely. 

Core Java : Multithreading Interview Questions

There is given a list of multithreading interview questions and answers. If you know any multithreading interview question, kindly post it in the comment section.

100) What is multithreading?

Multithreading is a process of executing multiple threads simultaneously.Its main advantage is:
  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between process is low.

101) What is thread?

A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of execution because each thread runs in a separate stack frame.

102)What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

103) What does join() method?

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

104) What is difference between wait() and sleep() method?

1) The wait() method is defined in Object class.The sleep() method is defined in Thread class.
2) wait() method releases the lock.The sleep() method doesn't releases the lock.

105) Is it possible to start a thread twice?

No, there is no possibility to start a thread twice. If we does, it throws an exception.

106) Can we call the run() method instead of start()?

yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.

107) What about the daemon threads?

The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads.

108)Can we make the user thread as daemon thread if thread is started?

No, if you do so, it will throw IllegalThreadStateException

109)What is shutdown hook?

The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we can use it perform clean up resource.

110)When should we interrupt a thread?

We should interrupt a thread if we want to break out the sleep or wait state of a thread.

Core Java : Synchronization Interview Questions

The following interview questions are also the part of multithreading interview questions.

111) What is synchronization?

Synchronization is the capabilility of control the access of multiple threads to any shared resource.It is used:
  1. To prevent thread interference.
  2. To prevent consistency problem.

112) What is the purpose of Synchnorized block?

  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.

113)Can Java object be locked down for exclusive use by a given thread?

Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

114) What is static synchronization?

If you make any static method as synchronized, the lock will be on the class not on object. 

115)What is the difference between notify() and notifyAll()?

notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

116)What is deadlock?

Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.