Thursday, March 5, 2009

Servlet Questions

1) What is servlet?

Ans: Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

2) What are the classes and interfaces for servlets?
Ans: There are two packages in servlets and they are javax.servlet and javax.servlet.http.
Javax.servlet contains:

Interfaces Classes
Servlet Generic Servlet
ServletRequest ServletInputStream
ServletResponse ServletOutputStream
ServletConfig ServletException
ServletContext UnavailableException
SingleThreadModel

Javax.servlet.http contains:

Interfaces Classes
HttpServletRequest Cookie
HttpServletResponse HttpServlet
HttpSession HttpSessionBindingEvent
HttpSessionContext HttpUtils
HttpSeesionBindingListener

3) What is the difference between an applet and a servlet?

Ans: a) Servlets are to servers what applets are to browsers.
b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

4)what is the lifecycle of a servlet.

Ans: Each Servlet has the same life cycle:
a) A server loads and initializes the servlet by init () method.
b) The servlet handles zero or more client’s requests through service( ) method.
c) The server removes the servlet through destroy() method.

5) What is the ServletConfig() and why are using ServletConfig ?

Ans:This interface is implemented by services in order to pass configuration information to a servlet when it is first loaded.A service writer implementing this interface must write methods
for the servlet to use to get its initialization parameters and the context in which it is running.

public interface ServletConfig


6) What is meant by the ServletContext() and use of the method ?
Ans: public interface ServletContext

The ServletContext interface gives servlets access to information about their environment ,and allows them to log significant events. Servlet writers decide what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet
contexts.

7) What is use of parseQueryString ?

Ans:

Parses a query string and builds a hashtable of key-value pairs, where the values are arrays
of strings. The query string should have the form of a string packaged by the GET or POST method.
(For example, it should have its key-value pairs delimited by ampersands (&) and its keys
separated from its values by equal signs (=).)
Note:

public static Hashtable parseQueryString(String s)

8)what are the types of servlets.
Ans: Genereic Servlets,HttpServlets.

9)what are the different methods in HttpServlet.
Ans: doGet(),doPost(),doHead,doDelete(),deTrace()

10)What is the difference between GET and POST.

Ans:
a) doGet() method is used to get information, while doPost( ) method is used for posting information.
b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However,
doPost( )requests passes all of its data, of unlimited length.
c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

11) Why do you need both GET and POST method implementations in Servlet?

Ans: A single servlet can be called from differenr HTML pages,so Different method calls can be possible.

12)When init() and Distroy() will be called.

Ans:init() is called whenever the servlet is loaded for the first time into the webserver.Destroy will be called whenever the servlet is removed from the webserver.

13) Who is loading the init() method of servlet?

Ans: Web server

14)If you want to modify the servlet,will the Webserver need to be ShutDown.

Ans:No

15)What is the advantage of Servlets over other serverside technologies.

Ans:PlatForm independent, so once compiled can be used in any webserver.For different processes different threads will execute inbuilt mutithreaded.

16) What is Server-Side Includes (SSI)?

Ans: Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many
servlets that support servlets, a page can be processed by the server to include output from servlets at certain
points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes
the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested.
So HTML files that include server-side includes must be stored with an .shtml extension.

17)What is Single Threaded Model in Servlets and how is it useful give one practical example.

Ans: For every single user a differnt copy of this servlet is executed. Credit card transactions.

18) What is the uses Sessions ?

Ans:Its a part of the SessionTracking and it is for mainting the client state at server side.

19)What are the advantage of using Sessions over Cookies and URLReWriting?

Ans:
Sessions are more secure and fast becasue they are stored at serverside. But Sessions has to be used combindly with Cookies or URLReWriting for mainting the client id that is sessionid at client side.

Cookies are stored at client side so some clients may disable cookies so we may not sure that the
cookies which we are mainting may work or not but in sessions cookies are disable we can maintain
our sessionid using URLReWriting .

In URLReWriting we can't maintain large data because it leads to network traffic and access may be
become slow.Where as in seesions will not maintain the data which we have to maintain instead
we will maintain only the session id.

20) What is session tracking and how do you track a user session in servlets?

Ans: Session tracking is a mechanism that servlets use to maintain state about a series requests
from the same user across some period of time. The methods used for session tracking are:

a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password

b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server

c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.

d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.

e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property


21)What is Cookies and what is the use of Cookies ?

Ans:Cookies are used to get user agents (web browsers etc) to hold small amounts of state
associated with a user's web browsing.Later that infromation read by server

22) What are cookies and how will you use them?

Ans: Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information
associated with the user.
a) Create a cookie with the Cookie constructor:
public Cookie(String name, String value)
b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of
HttpServletResponse:
public void HttpServletResponse.addCookie(Cookie cookie)
c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:
public Cookie[ ] HttpServletRequest.getCookie( ).

23) How many Cookies is supported to the host ?

Ans: User agents excepted to support twenty per host.And its take four Kilobytes each.

24) What is the use of setComment and getComment methods in Cookies ?

Ans:
setComment:If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment. This is not supported by version zero cookies.

public void setComment(String use)
{
}
getComment:
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

25)Why we are used setMaxAge() and getMaxAge() in Cookies ?

Ans:setMaxAge

public void setMaxAge(int expiry)

Sets the maximum age of the cookie.The cookie will expire after that many seconds have passed.Negative values indicate the default behaviour:the cookie is not stored persistently, and will be deleted when the user agent exits.A zero value causes the cookie to be deleted

getMaxAge():

public int getMaxAge()

Returns the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behaviour described with setMaxAge.


26)What is the use of setSecure() and getSecure() in Cookies ?

Ans: setSecure

Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.

public void setSecure(boolean flag)

getSecure:

Returns the value of the 'secure' flag.

public boolean getSecure()

27)What is meant by Httpsession and what is the use of sessions ?
Ans:
The HttpSession interface is implemented by services to provide an association between an HTTP client and HTTP server. This session, persists over multiple connections and/or requests during a given time period. Sessions are used to maintain state and user identity across multiple page requests.

HttpSession session = req.getSession(true);

28) What are the methods in HttpSession and use of those methods?
Ans:

a) getCreationTime()

Returns the time at which this session representation was created.

b) getId()

Returns the identifier assigned to this session.

c) getLastAccessedTime()

Returns the last time the client sent a request carrying the identifier assigned to the session.

d) getSessionContext()
Returns the context in which this session is bound.

e) getValue(String)

Returns the object bound to the given name in the session's application layer data.
f) getValueNames()

Returns an array of the names of all the application layer data objects bound into the
session.
g) invalidate()

Causes this representation of the session to be invalidated and removed from its context.
h) isNew()

A session is considered to be "new" if it has been created by the server, but the client has
not yet acknowledged joining the session.
j) putValue(String, Object)

Binds the specified object into the session's application layer data with the given name.

k) removeValue(String)

Removes the object bound to the given name in the session's application layer data.


29) How do you communicate between the servlets.

Ans: a)servlet chaning
b)Servlet context(RequestDespatcher interface)

30)Can you send the mail from a servlet ,if yes tell how?

Ans:yes.using mail API

31)How do you access variables across the sessions.

Ans:Through ServletContext.

32)where the session data will store?

ans: session objects

33)What is Servlet Context?

Ans:This object represents resources shared by a group of servlets like servlet's environment,
Application attributes shared in the context level.

34)How do you trap the debug the errors in servlets.

Ans:error log file

35)How do you debug the Servlet?

Ans:through servlet log();

36)How do u implement threads in servlet?

Ans:Intenally implemented

37)How do you handle DataBase access and in which method of the servlet do you like to create connection.

Ans:init()

38)If you want to improve the performance how do you create connections for multiple users?
A.Connection Pooling.

39)what is connection pooling?

Ans:Class which manages no of user requests for connections to improve the performance.


40) What are the different servers available for developing and deploying Servlets?

Ans: a) JRun2.0--Allaire
b) Apache --jserv
c) jwsdk2.0 --sun
d) servletexec
e) Tomcat webserver--tomcat

f)Weblogic AS--BEA Systems
g)NetDynamics5.0--sun
h)Iplanet--sun&netscape
i)Netscape--netscape
g)IBM websphere--IBM
h)oracle--oracle
i)Proton-Pramati technologies

41) Is it possible to communicate from an applet to servlet and how many ways and how?

Ans: Yes, there are three ways to communicate from an applet to servlet and they are:
a) HTTP Communication(Text-based and object-based)
b) Socket Communication
c) RMI Communication
(You can say, by using URL object open the connection to server and get the InputStream from
URLConnection object).
Steps involved for applet-servlet communication:
step: 1 Get the server URL.
URL url = new URL();
step: 2 Connect to the host
URLConnection Con = url.openConnection();
step: 3 Initialize the connection
Con.setUseCatches(false):
Con.setDoOutput(true);
Con.setDoInput(true);
step: 4 Data will be written to a byte array buffer so that we can tell the server the length of the data.
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
step: 5 Create the OutputStream to be used to write the data to the buffer.
DataOutputStream out = new DataOutputStream(byteout);

42) Why should we go for interservlet communication?

Ans: Servlets running together in the same server communicate with each other in several ways.
The three major reasons to use interservlet communication are:
a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)
b) Servlet reuse - allows the servlet to reuse the public methods of another servlet.
c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

43) Is it possible to call servlet with parameters in the URL?
Ans: Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).


44) What is Servlet chaining?
Ans: Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.
In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the
last servlet is reached. Its output is then sent back to the client.

45) How do servlets handle multiple simultaneous requests?
Ans: The server has multiple threads that are available to handle requests. When a request comes in, it is
assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the
servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

46) How are Servlets and JSP Pages related?
Ans: JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.
Servlets:

47).How do servlets handle multiple simultaneous requests?
Ans: Using Threads

48).How do I automatically reload servlets?
Ans:depends upon the server's servlet reload properites.

48).My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is not running under the Servlet 2.1 APIs (Java Web Server 2.0). What's wrong?
Ans:You might have used servlet to servlet communication by using servletcontext methods like
getServlet(),getServlets() which are depricated and returns null from new release that is from
servlet2.1 API.

49) What are the types of ServletEngines?

Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets.

Add-on ServletEngine: Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.

Embedded ServletEngine: it is a lightweight servlet deployment platform that can be embedded in another application.that application become true server.

50)what is httptunneling?

ans:
it is mechanism of performing both write and read operations using http protocol.it is extending the functionality of htp protocol.

51).How do I use native code in a servlet?
Ans:
52)What's with the javax.servlet package naming?
Ans:
53). List out Differences between CGI Perl and Servlet?

Servlet CGI

Platform independent Platform dependent.

Language dependent Language independent.


Tuesday, February 17, 2009

Java Questions - 1

    OOPS
  • What is an Object?
  • Ans :An object is an entity with certain attributes or qualities and behaviors, for a simple example, a 'Laptop' is an object which has certain attributes like weight,color,screen size,manufacturer etc.It has various behaviors or activities to do or act upon, as play games,browse Internet,write/check emails , watch movies ,listen music etc.

  • What is a Class?
  • Ans :A class is a collection of attributes and behaviors of objects with certain similarities and an instance of a class is represented by an object.A simple example of class is a 'Car' which represents variety of Car objects with different attribute values and behaviors.The different objects of 'Car' class can be, for example : A Mercedes Car,a Toyota Car, two different objects from same class but different attributes and different behaviors too.

  • What is OOAD?
  • Object Oriented Analysis and Design(OOAD) is a methodology to analyze,design and develop application using objects and their relations and message based communication to each other.Everything in OOAD is visualized in terms of objects and classes.OOAD introduced a paradigm shift from thinking and programming procedurally to objects oriented programming.This approach helps in designing complex real time systems with ease.The features like Data Abstraction and Encapsulation, Inheritance and Polymorphism form fundamentals of object oriented programming.

    Advantages:

  • Reusability
  • Modular approach towards problem solving
  • Better Maintainability
    Better Performance

  • What is Data Abstraction ?
  • Data Abstraction is extraction of essential information for a particular purpose and ingnoring the remainder of the information,e.g. a car is consisted of an engine,air filters,a carburetor,a gear box,a steering,a fuel tank,tyres etc.A driver of a car need not to be bothered about several finer points of the car,he/she should know what it requires to drive a car.Take another user, a car mechanic, he will require different set of information in order to repair the car.

  • What is Data Encapsulation?
  • Data Encapsulation is wrapping informations(attributes and behaviors) within an object.A suitable example is a class as it wraps methods and data within itself. The attributes of a class corresponds to its data members while behaviour corresponds to member methods of the class.

  • What is the difference between Data Abstraction and Information Hiding?
  • Data Abstraction is often confused with information hiding while they altogether are two different technical concepts.Here are few established definitions of Data Abstraction:

    "A view of a problem that extracts the essential information relevant to a particular purpose and ignores the remainder of the information." -- [IEEE, 1983]

    "The essence of abstraction is to extract essential properties while omitting inessential details." -- [Ross et al, 1975]

    "Abstraction is the selective examination of certain aspects of a problem. The goal of abstraction is to isolate those aspects that are important for some purpose and suppress those aspects that are unimportant." -- [Rumbaugh et al, 1991]

    "An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer." -- [Booch, 1991]

    While information hiding is not sharing the details of an object with outside world.Here are few standard definitions of Information Hiding which will elaborate more on this concept:

    "The technique of encapsulating software design decisions in modules in such a way that the module's interfaces reveal little as possible about the module's inner workings; thus each module is a 'black box' to the other modules in the system." -- [IEEE, 1983]

    "The process of hiding all the details of an object that do not contribute to its essential characteristics; typically, the structure of an object is hidden, as well as the implementation of its methods. The terms information hiding and encapsulation are usually interchangeable." -- [Booch, 1991]

    "The principle of information hiding is central. It says that modules are used via their specifications, not their implementations. All information about a module, whether concerning data or function, is encapsulated with it and, unless specifically declared public, hidden from other modules." -- [Graham, 1991]

  • What is Inheritance and what are different types of it?
  • Inheritance is a mechanism by which a specific object acquires attributes and behaviors of more general objects.In OOP terminology ,Inheritance is the mechanism which allows a Class 'A' to inherit properties of Class 'B' and we say 'A inherits from B' or in other words B is a 'Superclass'/'Parent class' while A is a 'Subclass'/'Child class'. A typical example of inheritance is a family tree which consists of son,father,grandfather,great grandfather and so on.The different types of Inheritance are:

    1.Single Inheritance
    2.Multiple Inheritance
    3.Multilevel Inheritance
    4.Hierarchical Inheritance
    5.Hybrid Inheritance

    In single inheritance, a class inherits implementation from only one super class. For example, if class B inherits from class A, class B will acquire all the members declared in class A.
    B------>A(Parent)

    In multilevel inheritance, a class inherits from a derived class (or subclass). For example, if class C inherits from class B, and class B inherits from class A, class C will acquire all the members declared in class B as well as all the members declared in class A.
    C------->B------>A(Parent)

    In hierarchical inheritance, many sub classes inherit from a single super class. For example, if classes B, C, and D inherit from class A, classes B, C, and D will acquire all the members declared in class A.
    B------>A(Parent)C------>A(Parent)D------>A(Parent)

    In multiple inheritance, a class inherits from several super classes. For example, if class C inherits from both class A and class B, class C will acquire all the members declared in class A as well as all the members declared in class B. Multiple inheritance is not directly supported by Java but through Interfaces one can.C------>A(Parent)C------>B(Parent)

    A hybrid inheritance is a combination of any two of the above discussed inheritance types

  • Why Java uses Singly rooted hierarchy?
  • All objects in Java are inherited from same base class called 'Object'.In Java all objects have common interface to implement and it makes implementaion of Garbage collector lot easier in Java.The necessary implementaion is provided in base class , and the garbage collector can then send the necessary messages to every objectc in the system.Without singly rooted hierarchy,it would have been difficult to implement garbage collection feature.It enables lot of ease to programmers not to be bothered about memory management while development.It greatly simplifies argument passing amongst object too on the heap. As Java started from scratch and has no backward compatibility issues with any existing language, it was a logical choice to use the singly-rooted hierarchy in common with most other object-oriented programming languages.

  • Why does Java not support Multiple Inheritance?
  • Java does not support multiple inheritance atleast not the way it does in case of C++.In designer’s view Multiple Inheritance poses many problems and confusions than it solves.e.g. famous Diamond problem The diamond problem is an ambiguity that can occur when a class multiply inherits from two classes that both descend from a common super class. In such scenarios assuming if Java implements multiple inheritance then it would be difficult to know which method is to be called by an inheriting class object of two of the super classes. In Java, interfaces solve all these ambiguities caused by the diamond problem. Through interfaces, Java allows multiple inheritance of interface but not of implementation. Implementation, which includes instance variables and method implementations, is always singly inherited. As a result, confusion will never arise in Java over which inherited instance variable or method implementation to use.

  • Why is Java not 100% pure OOP language?
  • Java takes inspirations from C and C++.The native datatypes like 'char','int','float','double' are straight pick from C, which is not an Object Oriented Language.Resonably enough, Java is not a 100% pure Object Oriented Language.

  • What is Early Binding?
  • The assignment of types to variables and expressions at compilation time is known as 'Early Binding',it is also called 'static binding' and 'static typing'.

  • What is Polymorphism/Late Binding?
  • When an object is sent a message then it does not know itself what type it is, the runtime environment will decide about function calling over an object. This feature of connecting an object with its associated message at runtime is known as Polymorphism or Late binding or Dynamic binding.

  • What is method overloading?
  • A method with changed formal parameters will lead to implementing method overloading.

    int calculateSum(int i,int j)
    float calculateSum(float i,int j)
    double calculateSum(double i,int j)
    float calculateSum(int i,float j)

  • What is method overriding?
  • The method with same signature but with changed implementation lead to method overriding and that can occur in a parent child relation of classes. A method defined in parent class can be overridden in its child class with different implementation from its base class.

    An example:

    We will define a base class called Circle

    class Circle
    {
    //declaring the instance variableprotected double radius;
    public Circle(double radius)
    {
    this.radius = radius;
    }
    // other method definitions here
    public double getArea()
    {
    return Math.PI*radius*radius;
    }
    //this method returns the area of the circle

    }// end of class circle

    When the getArea method is invoked from an instance of the Circle class, the method returns the area of the circle.

    The next step is to define a subclass to override the getArea() method in the Circle class. The derived class will be the Cylinder class. The getArea() method in the Circle class computes the area of a circle, while the getArea method in the Cylinder class computes the surface area of a cylinder.
    The Cylinder class is defined below.

    class Cylinder extends Circle
    {
    //declaring the instance variableprotected double length;
    public Cylinder(double radius, double length)
    {
    super(radius);this.length = length;
    }
    // other method definitions herepublic
    double getArea()
    {
    // method overriden here
    return 2*super.getArea()+2*Math.PI*radius*length;
    }//this method returns the cylinder surface area

    }// end of class Cylinder

    When the overriden method (getArea) is invoked for an object of the Cylinder class, the new definition of the method is called and not the old definition from the superclass(Circle).

  • How is Java different from C++?
  • Java is a platform independent, object oriented language while C++ is having some of its features from C, which is a procedural language so it is not pure object oriented. Even Java is not 100% pure object oriented.

    1. Pointers are supported in C++ while not in Java. The memory management is done automatically with help of part of JVM called Garbage Collector.
    2. Multiple inheritance is not supported in Java but supported in C++.
    3. There are no structures, unions or enumeration in Java.
    4. There is no scope resolution operator in Java (::).
    5. There are no destructors in Java like C++.
    6. There is no virtual keyword in Java because all non-static method use dynamic binding.

  • What is UML and how is it useful in designing large systems?
  • Unified Modelling Language(UML) is a notational language which comprises of several tools and techniques to support object oriented development.UML captures scenarios(use case diagram),object interactions(sequence diagram),class interactions(class diagrams) and object states(state diagrams).

    UML helps in designing large and complex systems.It starts with analysis of business requirement and coming up with basic business flow chart and static diagrams i.e. use case diagrams which gives pictorial view of business requirements and captures scenarios. The next step is Interaction diagrams,which mainly consists of Sequence diagrams.A Sequence diagram tells how objects interact with each other through message passing in most importantly in what sequence.Then classes are identified of the system with various class identification approaches like 'Noun Phrase Approach','CRC Approach',this exercise results in UML class diagrams.

    A modular approach helps in breaking down the complex system where each module can further be divided into components like classes and objects.Once the whole system is refined in terms of reusability of objects,omitting unnecessary objects and classes.The building of skeleton code on best practices of coding, like pattern based approach, helps in foundation of efficient code.

  • Is UML useful for procedural programming ?
  • Procedural programming is an unstructured way of programming which consists of set of procedures/method calls/instructions to be executed sequentially in such a way to attain the objective of a program.UML can help here in a very basic way in laying out the sequence of executions of instructions.

  • What are different notations used in UML ?
  • UML predominantly includes static and dynamic model diagrams and each diagram has their own set of notations.
    In brief, the classification of these diagrams is given as below: #

    Structure Diagrams include the Class Diagram, Object Diagram, Component Diagram, Composite Structure Diagram, Package Diagram, and Deployment Diagram.

    Behavior Diagrams include the Use Case Diagram (used by some methodologies during requirements gathering); Activity Diagram, and State Machine Diagram.

    Interaction Diagrams, all derived from the more general Behavior Diagram, include the Sequence Diagram, Communication Diagram, Timing Diagram, and Interaction Overview Diagram.

    Most frequently used diagrams for step by step analysis and design are: Use case,Activity,Sequence,Class
    To know how do they look like,their constituents and how are they used while designing systems,please check following links:

    UML Notation
    UML Reference Card

  • What is a Use case and an Actor?
  • A Usecase represents a particular scenario which corresponds to functional requirement(s) of a system to be designed and developed.An Actor is a user/external program or a system(anyone or anything), which interacts with a system.An Actor may input/receive or both(input and receive) information from the system.
    In the diagram shown below, a scenario of buying bus/train/tram ticket from a vending machine is captured through a use case diagram.Here actor is a 'Customer' as shown by a stickman and in ovals all usecases have been documented.


  • How to identify an Actor?
  • An Actor can be identified by finding an answer for following points: Who is:

    -interacting
    -benefited
    -maintaining
    -supplying information
    -using information
    -removing information Does system use an external resource?

    A good/refined set of actors of system will be arrived iteratively.


  • What is Generalization?
  • In UML , a generalization relationship is a relationship in which one model element (the child) is based on another model element (the parent). Generalization relationships are used in class, component, deployment, and use case diagrams.
    Generalization corresponds to inheritance implemenation amongst classes.

  • What is Association and how it maps into a Java class?
  • An Association specifies how objects are related to one another.To identify associations,look for verb and prepositional phrases like 'part of','next to','works for' or 'contained in'.While identifying implicit associations,a lot common sense and general knowledge is required.It is very important to eleminate redundant associations while desiging a system.The most important aspects of associations are:
    Cardinality - a cardinality of one on a given relationship end generates a Java reference, for example
    public class Customer
    {
    Purchase purchase; ...
    }
    A cardinality of many (depicted as a number or *) generates a Java container:

    public class Customer
    {
    List purchases; ...
    }

    Navigability - For given an instance of an object on one side of a association you can access an instance on the other side. If a association can only be traversed in one direction then this will be indicated with arrows. If there are no arrows then the association is bi-directional.

    Association end - A given class only sees the association through the attributes set on the association end. In other words that simple line actually represents two independent sets of data, one for each of the two classes involved. Besides the cardinality and navigability the most important attribute is the association end name. This name is used to generate the getter and setter methods and in persistent classes database column names.

    The different types of associations can be Aggregation and Composition.I will describe them in more details in next blogs to come.

  • What is Aggregation and how it maps into a Java class?
  • An Aggregation is an Association which denotes an "is part of" relationship.

    Take a 'Car', for example, it is consisted of an engine,a steering wheel, four tires,seats,gear box,fuel tank,engine oil tank, air filters etc.So all constituents of car are parts of it.

    If a car is destroyed/smashed, its parts can still be used separately as spares in other cars,so these parts have individual use even when their conatiner entity is destroyed.

    In a Java class, an aggregation can be represented from above example as :

    class Car
    {
    List getTires();
    List getSeats();
    List getAllParts();
    }

  • What is Composition and how it maps into a Java class?
  • A Composition is a tight Association and denotes "whole-part" relationship.So when an object is destroyed then all its constituents are also destroyed, these 'parts' have no meaning/sense in their lone existence from their 'whole'.

    The best example of Composition is a 'Human body' which is composed of two legs,two hands,two eyes,two ears and so on.During the lifetime of a human being,all organs make sense being part of whole,but once a human being is dead most of these parts are also dead,unless some of his body parts are not medically reused.

    Now come to map composition to Java world, the best example is garbage collection feature of the language.While garbage collecting objects, whole has the responsibility of preventing all its parts being garbage collected by holding some references to them.

    It is the responsibility of whole to protect references to its parts not being exposed to outside world.The only way to have true composition in Java is to never let references to internal objects escape their parent's scope.

    An example of Inner class as shown in the following code snippet may give you an idea how to implement Composition in Java.

    public class Human
    {

    public Human()
    {
    Brain brain = new Brain();
    }

    private class Brain
    {
    ....
    ....
    }

    }

  • What is Dependency and how it maps into a Java class?
  • A Dependency relationship means when a class consumes/uses methods or variables from other class(supplier).So a change to supplier class affects the consumer class as well.Here supplier is indepenedent of any changes being made to consumer classs.

    In UML class diagrams, a dependency relationship connector appears as a dashed line with an open arrow that points from the consumer class to the supplier class. A dependency relationship means an "import" statement.



  • What is the purpose of State machine diagrams?
  • Objects have both attributes and behaviors. Attribute is also know as state. When objects are incredibly complicated then to have better understanding during different state changes one should develop one or more state machine diagrams, formerly called state chart diagrams in UML 1.x, describing how their instances work.

    UML state machine diagrams show the various states that an object may be in and the transitions between those states. And these transitions are triggered by an event that can either be internal or external to the system.An initial state of an object is called creation state,as this is the time when an object is created, and the final state is reached when there are no more leading out transitions from this state.

    A self explanatory example of state machine diagram is given here for PIN check processing at ATM.It includes sub-machine diagrams, as shown in the diagram below:


  • What are different kinds of Structure diagrams?
  • Structure Diagrams as part of UML2.1:

    Class diagrams
    Object diagrams
    Composite structure diagrams
    Component diagrams
    Deployment diagrams
    Package diagrams


    For more details on individual structure diagrams, visit following links:

    Practical UML

  • What are different kinds of Interaction diagrams?
  • The Interaction diagrams represent how objects interact with one another through message passing.

    There are two kinds of Interaction Diagrams :

    Sequence Diagram
    Collaboartion Diagram

    If you want to study these diagrams in detail then go through this pdf given by OMG.

  • What are different kinds of Behavior diagrams?
  • Behavior Diagrams include :

    - Use Case Diagram (used by some methodologies during requirements gathering)
    - Activity Diagram
    - State Machine Diagram.

  • Java Fundamentals

  • What is a Java Virtual Machine (JVM)?
  • A Java Virtual Machine is a runtime environment required for execution of a Java application.Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM.It is JVM which is crux of 'platform independent' nature of the language

  • What is a JVM consisted of?
  • Each time a Java Application is executed then an instance of JVM ,responsible for its running,is created.A JVM instance is described in terms of subsystems, memory areas, data types, and instructions.The block diagram given below,depicts a view of Internal Architecture of JVM :




Each JVM has a class loader subsystem which loads classes and interfaces with fully qualified names.Each JVM has an execution engine too , which executes all instructions contained by methods of a loaded class.While executing a Java program,a JVM requires memory for storing bytecodes,objects ,local variables,method arguments,return values,intermediate computational results and JVM does that memory management on several runtime data areas.The specification of runtime data areas is quite abstract.This abstract nature of JVM specification helps different designers to provide implementation on wide variety of OS and as per choice of the designers.Some implementations may have a lot of memory in which to work, others may have very little. Some implementations may be able to take advantage of virtual memory, others may not.

Each instance of the Java virtual machine has one method area and one heap. These areas are shared by all threads running inside the virtual machine. When the virtual machine loads a class file, it parses information about a type from the binary data contained in the class file. It places this type information into the method area. As the program runs, the virtual machine places all objects the program instantiates onto the heap.

When a new thread is created, it gets its own pc register (program counter) and Java stack. If the thread is executing a Java method (not a native method), the value of the pc register indicates the next instruction to execute. A thread's Java stack stores the state of Java (not native) method which includes its local variables, the parameters with which it was invoked, its return value (if any), and intermediate calculations. The state of native method invocations is stored in an implementation-dependent way in native method stacks, in registers or other implementation-dependent memory areas.

The Java stack is composed of stack frames (or frames). A stack frame contains the state of one Java method invocation. When a thread invokes a method, the Java virtual machine pushes a new frame onto that thread's Java stack. When the method completes, the virtual machine pops and discards the frame for that method.

In JVM ,the instruction set uses the Java stack for storage of intermediate data values.The stack-based architecture of the JVM's instruction set optimizes code done by just-in-time and dynamic compilers.

  • What is a class loader and what is its responsibilities?
  • The Class loader is a subsystem of a JVM which is responsible,predominantly for loading classes and interfaces in the system.Apart from this,a class loader is responsible for the following activities:

    -Verification of imported types(classes and interfaces)

    -Allocating memory for class variables and initializing them to default values.Static fields for a class are created and these are set to standard default values but they are not explicitly initialized.The method tables are constructed for the class.

    -Resolving symbolic references from type to direct references The class loaders can be of two types: a bootstrap or primordial class loader and user defined class loaderEach JVM has a bootstrap class loader which loads trusted classes , including classes from Java API.JVM specs do not tell how to locate these classes and is left to implementation designers.

    A Java application with user defined class loader objects can customize class loading.These load untrustworthy classes and not an intrinsic part of JVM.They are written in Java,converted to class files and loaded into the JVM and installed like any other objects.

    If you want to read this in more details then read Chapter 8,"The Linking Model" of Inside Java 2 Virtual Machine by Bill Venners.

  • What is heap and stack?
  • The heap is the part of memory of JVM where all objects reside.

    The stack is consisted of stack frames.When a thread invokes a method,the JVM pushes a new frame onto that thread's Java stack.Each stack frame is consisted of operand stack and the local variable array.All arguments,local variables,intermediate computations and return values if any are kept in these stack corresponding to the method invoked.The stack frame on the top of the stack is called the active stack frame,which is the current place of execution.When the method completes, the virtual machine pops and discards the frame for that method.

  • How is your Java program executed inside JVM?
  • When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance invoke main() method of Java application.The main() method of an application serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.
    This thread has a program counter(PC) and Java stack.Whenever main() method is invoked, a stack frame is pushed onto the stack,this then becomes the active tack frame.The program counter in the new Java stack frame will point to the beginning of the method.
  • If there are more method invocations within main() method then this process of pushing new stack frame onto the stack for each method call is repeated as and when they are invoked.When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame.The PC is set to the instruction after the method call and the method continues.
There is only one heap corresponding to an instance of JVM and all objects created are stored here.This heap is shared by all threads created in an application.

Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application--the one that begins at main()--is a non- daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

When main() returns,it terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.
  • What is Java class file's magic number?
  • A Magic Number of a class file is a unique identifier for tools to quickly differentiate class files from non class files.The first four bytes of each Java class file has the magic value as 0xCAFEBABE.And the answer to why this number,I do not actually know but there may be very few sensible and acceptable options possible constructed from letters A-F which can surely not be 'CAFEFACE' or 'FADECAFE'....

  • How JVM performs Thread Synchronization?
  • JVM associates a lock with an object or a class to achieve mutilthreading. A lock is like a token or privilege that only one thread can "possess" at any one time. When a thread wants to lock a particular object or class, it asks the JVM.JVM responds to thread with a lock maybe very soon, maybe later, or never. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.If a thread has a lock,no other thread can access the locked data until the thread that owns the lock releases it.

    The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.Each monitor is associated with an object reference. It is the responsibility of monitor to watch an arriving thread must obtain a lock on the referenced object.

    When the thread leaves the block,it releases the lock on the associated object.A single thread is allowed to lock the same object multiple times.JVM maintains a count of the number of times the object has been locked. An unlocked object has a count of zero. When a thread acquires the lock for the first time, the count is incremented to one. Each time the thread acquires a lock on the same object, a count is incremented. Each time the thread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.

    In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization. The language provides two built-in ways to synchronize access to data: with synchronized statements or synchronized methods.

    The JVM does not use any special opcodes to invoke or return from synchronized methods. When the JVM resolves the symbolic reference to a method, it determines whether the method is synchronized. If it is, the JVM acquires a lock before invoking the method. For an instance method, the JVM acquires the lock associated with the object upon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized method completes, whether it completes by returning or by throwing an exception, the lock is released.

    Two opcodes, monitorenter and monitorexit are used by JVM for accomplishing this task.

    When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for that object, a count is incremented. Each time monitorexit is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.

  • How JVM performs Garbage Collection?
  • One of the most frequently asked questions during interviews and it seeks a precise and clear understanding of the concept. Whenever a reference to an object on heap lies dangling or no longer in use by an active program then it becomes eligible for being garbage collected by JVM.JVM specifications do not force any specific kind of garbage collection algorithm though there are several algorithms like reference counting,tracing,compacting,copying,generational etc. in place.It is very important that garbage collection should be efficient and non interfering in execution of Java programs.There is a trade off between ease of implementation versus better performance while implementing garbage collection feature for a JVM.

    Since J2SE1.2 JVM incorporated different algorithms and that are combined using generational collection.This mechanism can be compared with a container or bucket kind of thing, where new object or infant/young objects are kept another as tenured and the third is permanent. The objects lying in young container are more often checked and quick to go in garbage state while this phenomenon decreases with tenure. So when objects are old enough or survive enough to be part of tenure zone then they become less likely to be garbage collected.The JVM specific classes and method objects are part of permanent zone and are never garbage collected.

    So it is quite likely that non reachable object still remains out of bound of gabage collection due to how much time an object has survived for as mentioned above, how much heap space JVM is consuming for its running,if it is low then whole process of garbage collection slows down.

    More you would like to explore here.

  • How to profile heap usage?
  • Try using -Xaprof to get a profile of the allocations (objects and sizes) of your application.

    Also try -agentlib:hprof=heap=all (or other option, try -agentlib:hprof=help for a list)

  • What will you do if VM exits while printing "OutOfMemoryError" and increasing max heap size doesn't help?
  • The Java HotSpot VM cannot expand its heap size if memory is completely allocated and no swap space is available. This can occur, for example, when several applications are running simultaneously. When this happens, the VM will exit after printing a message similar to the following.

    Exception java.lang.OutOfMemoryError: requested bytes

    If you see this symptom, consider increasing the available swap space by allocating more of your disk for virtual memory and/or by limiting the number of applications you run simultaneously. You may also be able to avoid this problem by setting the command-line flags -Xmx and -Xms to the same value to prevent the VM from trying to expand the heap. Note that simply increasing the value of -Xmx will not help when no swap space is available.

  • Should one pool objects to help Garbage Collector?Should one call System.gc() periodically?
  • The answer is No!

    Pooling objects will cause them to live longer than necessary. The garbage collection methods will be much more efficient if you let it do the memory management. The strong advice is taking out object pools.

    Don't call System.gc(), HotSpot will make the determination of when its appropriate and will generally do a much better job.

  • An application has a lot of threads and is running out of memory, why?
  • You may be running into a problem with the default stack size for threads. In Java SE 6, the default on Sparc is 512k in the 32-bit VM, and 1024k in the 64-bit VM. On x86 Solaris/Linux it is 320k in the 32-bit VM and 1024k in the 64-bit VM.

    On Windows, the default thread stack size is read from the binary (java.exe). As of Java SE 6, this value is 320k in the 32-bit VM and 1024k in the 64-bit VM.

    You can reduce your stack size by running with the -Xss option. For example:

    java -server -Xss64k

    Note that on some versions of Windows, the OS may round up thread stack sizes using very coarse granularity. If the requested size is less than the default size by 1K or more, the stack size is rounded up to the default; otherwise, the stack size is rounded up to a multiple of 1 MB.

    64k is the least amount of stack space allowed per thread.

  • If your program is I/O bound or running in native methods, do these activities engage JVM?
  • The answer is 'No'.If the program is I/O bound or running in native methods, then the VM is not involved in the consumption of CPU time. The VM technology will engage CPU for running bytecodes. Typical examples of time spent not running bytecode are graphical operations that make heavy use of native methods, and I/O operations such as reading and writing data to network sockets or database files.

  • What is the difference between interpreted code and compiled code?
  • An interpreter produces a result from a program, while a compiler produces a program written in assembly language and in case of Java from bytecodes.The scripting languages like JavaScript,Python etc. require Interpreter to execute them.So a program written in scripting language will directly be executed with interpreter installed on that computer,if it is absent then this program will not execute.While in case of compiled code,an assembler or a virtual machine in case of Java is required to convert assembly level code or bytecodes into machine level instructions/commands.Generally, interpreted programs are slower than compiled programs, but are easier to debug and revise

  • Why Java based GUI intensive program has performance issues?
  • GUI intensive Java application mostly run underlying OS specific native libraries which is time and more CPU cycles consuming.

    The overall performance of a Java application depends on four factors:
  • The design of the application
  • The speed at which the virtual machine executes the Java bytecodes
  • The speed at which the libraries that perform basic functional tasks execute (in native code)
  • The speed of the underlying hardware and operating system
The virtual machine is responsible for byte code execution, storage allocation, thread synchronization, etc. Running with the virtual machine are native code libraries that handle input and output through the operating system, especially graphics operations through the window system. Programs that spend significant portions of their time in those native code libraries will not see their performance on HotSpot improved as much as programs that spend most of their time executing byte codes.

  • What is 64 bit Java ?
  • A 64-bit version of Java has been available to Solaris SPARC users since the 1.4.0 release of J2SE. A 64-bit capable J2SE is an implementation of the Java SDK (and the JRE along with it) that runs in the 64-bit environment of a 64-bit OS on a 64-bit processor. The primary advantage of running Java in a 64-bit environment is the larger address space.

    This allows for a much larger Java heap size and an increased maximum number of Java Threads, which is needed for certain kinds of large or long-running applications. The primary complication in doing such a port is that the sizes of some native data types are changed. Not surprisingly the size of pointers is increased to 64 bits. On Solaris and most Unix platforms, the size of the C language long is also increased to 64 bits. Any native code in the 32-bit SDK implementation that relied on the old sizes of these data types is likely to require updating.

    Within the parts of the SDK written in Java things are simpler, since Java specifies the sizes of its primitive data types precisely. However even some Java code needs updating, such as when a Java int is used to store a value passed to it from a part of the implementation written in C.

  • What is the difference between JVM and JRE?
  • A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any computer.A JRE contains a Java Virtual Machine(JVM),all standard,core java classes and runtime libraries. It does not contain any development tools such as compiler, debugger, etc. JDK(Java Development Kit) is a whole package required to Java Development which essentially contains JRE+JVM,and tools required to compile and debug,execute Java applications.

  • What are different primitive datatypes in Java?
An expression is a construct made up of variables, operators, and method invocations, which are built-up according to the syntax of the language, that evaluates to a single value.

Some examples of expression:
int val = 0;
iArr[0] = 20;
int var = 4 + 2; // var is now 6

A statement is complete unit of execution.Any expression which is :

  • An assignment expression

  • ++ or --

  • Method invocation

  • Object creation

terminated with ';' is a statement.


x = 123.24; // assignment statement
x++; // increment statement
System.out.println("Hello World!"); // method invocation statement
Person person = new Person(); // object creation statement

A block is zero or more statements grouped together with balanced braces.
The lexical meaning of word transient is 'existing for a short duration',in Java,a transient variable is one which one would not like to be saved during seralization.This is mostly the case when a variable is sensitive enough that it should not be saved during serialization, such as a password.Even when such variable is private in the object,once it is serialized it is possible to read it inside a file or over a network.The keyword 'transient' is solution for such variables that are not required to be serialized.
'&&' is a Logical operator while '&' is a Bitwise operator.
e.g.

int x=12; binary represenation of 12---------> 1100
int y=10; 1010 binary represenation of 10---------> 1010
int z=x & y; binary represenation of (x & y)---------> 1000
Here value of z will be 8.

In case of logical operatior '&&':
condition1 && condition2
if condition1 is false then (condition1 && condition2) will always be false, that is the reason why this logical operator is also known as short circuit operator.
if condition1 is true then condition2 is to be evaluated, if it is true then overall result will be true else it will be false.It is the main entry point of a java file. Every java file has just single copy of main method from where main thread is invoked and that's why main method is static. This method can be overloaded but JVM will distinguish public static void main from rest of the overloaded main methods.
The sequence of call will be:
1. static block
2. main
3. constructor
Whenever a java file is executed it is done by java command given as below: java Usage: java [-options] class [args...]
(to execute a class)
or java -jar [-options] jarfile [args...]
(to execute a jar file)
when some arguments are also passed with execution command then these arguments are called command line arguments as they are taken as an array of String as a parameter in main method.
The Java programming language does not really support multi-dimensional arrays. It does, however, support arrays of arrays. In Java, a two-dimensional array 'arr' is really an array of one-dimensional arrays:
int[][] arr = new int[4][6];
The expression arr[i] selects the one-dimensional array; the expression arr[i][j] selects the element from that array.
The built-in multi-dimensional arrays suffer the same indignities that simple one-dimensional arrays do: Array indices in each dimension range from zero to , where length is the array length in the given dimension. There is no array assignment operator. The number of dimensions and the size of each dimension is fixed once the array has been allocated.
Whenever you say something is static that means data or method is not associated with an object instance of that class.They are allocated when a class is loaded,during compile time. Only a single copy of that will be created for that class. So even if you have never created an object of a class you an always access static data and method of that class. If you have class by name 'Vehicle' and you have a static method 'drive()' then it can simply be invoked by ' Vehicle.drive()', no need of object cretaion in this scenario.A static method cannot access non static data and can invoke other static methods.All static methods are automatically final. It is redundant to make them final.

An abstract method is usually defined in an abstract class or an interface,for which implementation is provided in a subclass or a class implementing the interface.As static methods just have single copy per class and are interpreted at code compile time,not at runtime, so it is impossible to have polymorphic behaviour out of them.In other words, they cannot be overridden.

An abstract class is one which cannot be instantiated but a static method defined in abstract class can be invoked without creating an instance.So there is no mechanism to ensure call of an abstract static method.

Moreover this is a design decision by language designers. :-)

No, 'sizeof' is an operator used in C and C++ to determine the bytes of a data item, but it is not used in Java as all data types are standard sized in all machines as per specifications of the language.
A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.In JDK 1.5+ you can use java.lang.instrument.Instrumentation. getObjectSize() to get the object size.
On JavaWorld, I have found an interesting article on Objects' size determination, read.
The precedence of operators suggests the sequence in which operators will be work upon in case of compounded statements containing several operators.
For example, in the expression

x = a + b * c;

the first "+" operator still first determines its left operand ("a" in this case) and then its right operand. But in this case the right operand consists of the expression "b*c". The multiplication operator "*" has a higher precedence than the additive "+".

Precedence can be overridden with parentheses, e.g.

x = (a + b) * c;

will force the addition of b to a, and then this sum is multiplied by c.

The table shown in image below is organised from higher precedence to low, when you traverse from top to the bottom of the table.
  • How is an argument passed in Java methods?
  • If the variable is primitive datatype then it is passed by value and if the variable is an object then it is passed by reference

  • What is the difference between class variable, member variable and automatic(local) variable?
  • The class variable is a static variable and it does not belong to any instance of class but shared across all the instances.
    The member variable belongs to a particular instance of class and can be called from any method of the class.
    The automatic or local variable is created on a method entry and valid within method scope and they have to be initialized explicitly.



  • When are static and non static variables of a class initialized?
  • The static variables are initialized at class load time during compilation and non static variables are initialized just before the constructor is called.

  • Can shift operators be applied to float types?
  • No, shift operators are applicable only on integer or long types.

  • What are different Java declarations and their associated rules?
  • No, shift operators are applicable only on integer or long types.

  • What are Java Modifiers?
  • Java classes, interfaces, and their members can be declared with one or more modifiers.They can be categorised as:

    Class Modifiers :
    ClassModifier: one of
    public protected private
    abstract static final strictfp

    Field Modifiers
    FieldModifier: one of
    public protected private
    static final transient volatile

    Method Modifiers
    MethodModifier: one of
    public protected private abstract static
    final synchronized native strictfp

    Constructor Modifiers
    ConstructorModifier: one of
    public protected private

    The following matrix of the all modifiers in Java shows which modifier maps to which element:-


  • Explain final modifier.
  • final' modifier can be applied to classes, methods and variables and the features cannot be changed. final class cannot be subclassed, methods cannot be overridden

  • Can you change the reference of the final object?
  • No the reference cannot be changed, but the data in that object can be changed.

  • Can abstract class be instantiated?
  • No,an abstract class cannot be instantiated i.e you cannot create a new object of this class.

  • When does the compiler insist that the class must be abstract?
  • In following conditions,compiler insists 'abstract' keyword with a class :
  • If one or more methods of the class are abstract.
  • If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
  • If class implements an interface and provides no implementation for those methods

  • Where can static modifiers be used?
  • They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class.They are loaded at the class compile time.

  • What is static initializer code?
  • A class can have a block of initializer code that is simply surrounded by curly braces and labeled as static e.g.
    public class Demo{
    static int =10;
    static{
    System.out.println("Hello world');
    }
    }
    And this code is executed exactly once at the time of class load.

  • Can an anonymous class implement an interface and extend a class at the same time?
  • No,an anonymous class can either implement an interface or extend a class at a particular time but not both at the same time.

  • What are volatile variables?
  • A volatile variable is modified asynchronously by concurrently running threads in a Java application.It is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

  • Can protected or friendly features be accessed from different packages?
  • No,when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package.

  • How many ways can one write an infinite loop?
  • Personally I would recommend following ways to implement infinite loop in Java but their can be other ways like calling a method recursively , though I never tested that.

    - while (true)

    - for (;;) { }

  • When do you use 'continue' and 'break' statements?
  • When one wants to complete the iteration of a loop prematurely then 'continue' statement is used.
    While the 'break' statement is used to exit the entire loop whenever encountered.

  • What is the difference between 'while' and 'do while' loop?
  • In case of 'do-while' loop, body is always executed at least once,since test is performed at the end of the body.It should usually be ignored while coding.

  • What is an Assertion and why using assertion in your program is a good idea ?
  • In a Java program,several times, one would like to make certain assumptions for executing a program.For example,while taking a square root of a numeric value it has to be assumed that this value should not be negative.An assertion is a statement in the Java programming language that enables to test assumptions about one's program.Assertions are supported from J2SE1.4 and later.A simple exmaple of assertion can be checking of an employee object from being null:

    Employee employee = null;

    //...
    //Get an Employee object
    //...

    //Ensure we have one
    assert emplyee!= null;

    This asserts that an employee is not null. If employee is null, an AssertionError is thrown. Any line of code executing after the assert statement can safely assume that employee is not null.

    Each assertion is a boolean statement when an assertion executes,it returns true and when it returns false then an error is thrown.So successful execution of an assumption will ensure an error free code.By including assertions in one's program,the following objectives can be achieved:

    -The quickest way of identifying and correcting bugs.
    -The code becomes less prone to errors hence better maintained against errors and more efficient.
    -Better readability of code.


  • Explain Assertions with a code exmaple.
  • The main reason of introducing assertions in Java from R1.4 onwards is to reduce the chances of bugs which otherwise would have gone unnoticed, in one's code.In fact, finding and removing bugs is one tedious and not so exciting task.Assertions should be used for scenarios which ideally should never happen in the lifecycle of a program,check assumptions about data structures (such as ensuring that an array is of the correct length), or enforcing constraints on arguments of private methods.Assertions help in a way to block these bugs at the beginning of writing actual logic inside your code that saves lot of efforts,time and most significantly, costs.A simple assertion facility provides a limited form of design-by-contract programming.In design-by-contract programming identification of preconditions and post conditions to a program are must before even starting the coding itself.

    Here is simple Java code which uses assertions, here the task is to determine the gender of a person.We have used a switch-case statement to define the over all flow of the logic :


    Use J2SE 1.4.x (or later versions) to compile ExampleAssertions, make sure you use the -source option as follows:

    javac -source 1.4 ExampleAssertions.java

    If you try to compile your assertion-enabled classes without using the -source 1.4 option, you will get a compiler error saying that assert is a new keyword as of release 1.4. If you now run the program using the command and you enter a valid character, it will work fine. However, if you enter an invalid character, nothing will happen.

    This is because, by default, assertions are disabled at runtime.You have to enable assertions to make them work.Use the switch -enableassertion (or -ea) as follows:

    java -ea ExampleAssertions
    java -enableassertion ExampleAssertions

    Following is a sample run:






    When assertion fails it throws AssertionError.By default assertions are disabled but once enabled and you wnat to disable them then use switch -diableassertion (or -da).

    Diabling assertions for a particular class in a package:

    java -da:com.punsoft.acc.Account SavingAccount , this means running class SavingAccount with assertions of Account class disabled.

    java -da:com.punsoft.acc... SavingAccount, this means running class SavingAccount with assertions of 'acc' package and its subpackages disabled.

    You can use combination of enable and disable assertions.

    java -ea:com.punsoft.acc... -da:com.punsoft.view.acc SavingAccountView

    If you use the command
    java -ea SavingAccount

    then assertions are enabled in all classes except system classes. If you wish to turn assertions on or off in system classes, use the switches -enablesystemassertions (or -esa) and -disablesystemassertions (or -dsa).

  • How many forms of assertions we have?
  • There are two forms of assertions:

    The first, simpler form is:

    assert Expression1 ;
    where Expression1 is a boolean expression.
    When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
    While the second form of the assertion statement is:

    assert Expression1 : Expression2 ;

    where:
    Expression1 is a boolean expression.
    Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

    This form is used when the assert statement has to provide a detail message for the AssertionError.The system passes the value of Expression2 to the appropriate AssertionError constructor, and this constructor uses the string representation of the value as the error's detail message. This detail message helps in analysing and diagnosing the assertion failure which ultimately helps in resolving the error.



  • When assertions should be avoided?
  • In following situations the assertions should be avoided:
    -When assertion becomes a performance issue.It means an assertion should not include too complex logic equalling implementation of a method.
    -Do not use assertions in argument checking of public methods.As argument checking is part of a method implementation and if these arguments are erroneous then it will throw runtime exception and assertion failure will not result in any error.

  • What situations are best suitable for implementing assertions?
  • Assertions can best be implemented :
    - As Internal Invariants
    - As Control flow Invariants
    - As Preconditions and Postconditions
    - As Class Invariants

    Internal Invariants:

    Assertions can be used in if-statement construct where asserting an invariant is obvious.
    e.g.
    Before assertions were available: the following code snippet could be replaced
    if (k % 3 == 0) {
    ...
    } else if (k % 3 == 1) {
    ...
    } else { // as is obvious (k % 3 == 2)
    ...
    }

    with

    if (k % 3 == 0) {
    ...
    } else if (k % 3 == 1) {
    ...
    } else {
    assert k % 3 == 2 : k;
    ...
    }

    Another good example for an assertion is a switch statement with no default case. An absence of default indicates that a programmer believes that one of the cases will always be executed. The assumption that a particular variable will have one of a small number of values is an invariant that should be checked with an assertion. For example, suppose the following switch statement appears in a program that handles playing cards:

    switch(condition) {
    case condition.ONE:
    ...
    break;

    case condition.TWO:
    ...
    break;

    case condition.THREE:
    ...
    break;

    }
    One should add the following default case:

    default:
    assert false : condition;
    If the 'condition' variable takes on another value and assertions are enabled, the assert will fail and an AssertionError will be thrown.

    An acceptable alternative is:

    default:
    throw new AssertionError(condition);


    Control flow Invariants

    One of the most significant use of assertion is in placing it at any unreachable location. The assertions statement to use is:
    assert false;

    For example:
    void testMethod() {
    for (...) {
    if (...)
    return;
    }
    // Execution should never reach this point!!!
    }
    Replace the final comment so that the code now reads:

    void testMethod() {
    for (...) {
    if (...)
    return;
    }
    assert false; // Execution should never reach this point!
    }
    According to JLS if a program contains an unreachable code then it faces compile time error,if asserted that it is not reached.Another alternative for this could be throwing AssertionError.

    Assertion do not support design by contract facility formally but some level of this feature can be used by using them.The set of preconditions ,postconditions and class invariant give that leverage to implement design by contract.

    Preconditions
    It means what set of conditions that must be satisfied before executing a method.A public method always guarantees checking of its arguments so use of assertions should be avoided in case of public methods.One can use an assertion to test a nonpublic method's precondition that will be true no matter what a client does with the class.

    An assert can be applied in case of multithread blocks or methods which are private to ensure whether a lock on the object is retrieved before actually executing the code within.

    Postconditions
    The postcondition can be tested with assertions in both public and nonpublic methods. For example, the following public method uses an assert statement to check a post condition:
    A simple operation of pushing an element on a stack can have a precondition that the element going to be pushed have a position less than the capacity of the stack and while element being pushed over the stack, it is equally important that new index is equal to old index plus one alongwith surety of an element being pushed on stack.This could be done using assertion as an example shown below:

    public void push(int element) {
    // precondition
    assert num


    Class Invariants
    A class invariant is applicable to every instance of a class at all times, except when an instance is in transition from one consistent state to another. A class invariant can specify the relationships among multiple attributes, and should be true before and after any method completes.


  • What is Exception ?
  • An exception is an abnormal behavior existing during a normal execution of a program. For example: When writing to a file if there does not exist required file then an appropriate exception will be thrown by java code.

  • What is a user-defined exception?
  • For every project you implement you need to have a project dependent exception class so that objects of this type can be thrown so in order to cater this kind of requirement the need for user defined exception class is realized.
    for example:

    class MyException extends Exception{
    public MyException(){};
    public MyException(String msg){
    super(msg);
    }

  • What do you know about the garbage collector?
  • In Java, memory management is done automatically by JVM.A programmer is free of this responsibility of handling memory. A garbage collector is a part of JVM responsible for removing objects from heap, which is no longer in use. The garbage collector typically runs in a background thread, periodically scanning the heap, identifying garbage objects, and releasing the memory they occupy so that the memory is available for future objects.

  • Why Java does not support pointers?
  • As per the design decision Java does not support pointers explicitly.This greatly reduces the burden of dynamic memory management while coding from programmers.Though programmers dynamically allocate memory while coding but they need not worry about deallocating this memory.The automatic garbage collection feature of Java collects dangling references of objects though it has a trade off on performance as programmer managed memory management will be efficient as compared to JVM driven automatic garbage collection.

  • Does garbage collection guarantee that a program will not run out of memory?
  • Garbage collection does not guarantee that a program will not run out of memory. As garbage collection is JVM dependent then It is possible for programs to use memory resources faster than they are garbage collected.Moreover garbage collection cannot be enforced,it is just suggested.Java guarantees that the finalize method will be run before an object is Garbage collected,it is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
    The garbage collection is uncontrolled, it means you cannot predict when it will happen, you thus cannot predict exactly when the finalize method will run. Once a variable is no longer referenced by anything it is available for garbage collection.You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen.

  • What is finally in Exception handling?
  • 'finally' is a part of try-catch-throw and finally blocks for exception handling mechanism in Java.'finally' block contains snippet which is always executed irrespective of exception occurrence. The runtime system always executes the statements within the finally block regardless of what happens within the try block. The cleanup code is generally written in this part of snippet e.g. dangling references are collected here.

  • What can prevent the execution of the code in finally block?
  • -Use of System.exit()
    -The death of thread
    -Turning off the power to CPU
    -An exception arising in the finally block itself

  • Explain 'try','catch' and 'finally' blocks?
  • In Java exceptions are handled in try, catch, throw and finally blocks. It says try a block of Java code for a set of exception/s catch an exception if it appears in a catch block of code separate from normal execution of code. It clearly segregates errors from a block of code in an effective and efficient manner. The exceptions, which are caught, thrown using throw keyword. A finally block is called in order to execute clean up activities for any mess caused during abnormal execution of program.

  • Define Checked and Unchecked exception.
  • A checked exception is one, which a block of code is likely to throw, and represented by throws clause.It represents invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files).
    In Java it is expected that a method 'throws' an exception which is a checked exception.They are subclasses of Exception.
    While unchecked exceptions represent defects in the program (often invalid arguments passed to a non-private method).
    According to definition in The Java Programming Language, by Gosling, Arnold, and Holmes,"Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time." They are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
    It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).

  • What is the difference between an abstract class and an interface?
  • An abstract class allows its subclasses to override the methods defined in it. It is never instantiated and a class can inherit from a single class, as Java doesn't support for Multiple Inheritance. It may contain both abstract and non-abstract methods.

    An interface has public, abstract methods and may have public, static and final variables (read only). It introduces multiple inheritance by a class implementing several interfaces.

    An example:



    interface Movable
    {
    abstract move ();
    }
    abstract class Mammal
    {
    void getHeight(float height)
    { ... }
    abstract eat();
    }
    abstract class Vehicle
    {
    void getSizeofSeat(float seatSize)
    { ... }
    abstract engineType();
    }
    class Student extends Mammal implements Move
    {
    ......
    getheight(height);
    void eat()
    {.......}
    void move();
    }
    class Car extends Vehicle implements Move
    {
    ......
    getSizeofSeat(float seatSize
    void engineTypr()
    {.......}
    void move();
    }

    Hence Student and Car is not related but they can still implement the Move interface.

    Moreover,an abstract class can have concrete methods while an interface cannot.


  • What is the use of interface?
  • An interface is a collection of public abstract methods and read only i.e. public, static and final variables.
    The concept of interfaces in Java makes Multiple Inheritance a reality. Two or more non-related classes can implement the same interface. A class can implement multiple interfaces.Whenever there has to be an ancestry associated with classes along with some concrete behaviors then it is good idea to come up with abstract classes in such scenario but when implementation is more generic in nature and not dependent upon class relations or type hierarchy then such behaviors should be packaged inside an interface.The methods defined inside an interface can be implemented by non related classes.

  • What is serializable interface?
  • In java.io package there is an interface called java.io.Serializable, which is a syntactic way of serializing objects. This interface does not define any method. The purpose of serialization is persistence, communication over sockets or RMI. In Object serialization an object can be converted into byte stream and vice versa.

  • Does a class inherit constructors from its superclass?
  • The answer is No.Constructors cannot be inherited.Constructors are used to initialize a valid sate of an object.Whenever a subclass instance is created then it calls no argument default constructor of super class.

    The following code will explain implicit call to default constructor of base class:-

    class Base {
    Base() {
    System.out.println("I am constructing Base");
    }
    }
    class Child extends Base {
    Child() {
    System.out.println("I am constructing Child");
    }
    }

    public class A {
    public static void main(String[] args) {
    Child child = new Child();
    }
    }

    Once executed this code will print:

    I am constructing Base
    I am constructing Child

    It means when a child class object is created it inherently calls no arg default constructor of base class.

  • What's the difference between constructors and other methods?
  • Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

  • If the method to be overridden has access type 'protected', can subclass have the access type as 'private'?
  • No, it must have access type as protected or public, since an overriding method must restrict access of the method it overrides.

  • If you use super() or this() in a constructor where should it appear in the constructor?
  • It should always be the first statement in the constructor.

  • What modifiers may be used with an inner class that is a member of an outer class?
  • A (non-local) inner class may be declared as public, protected,
    private, static, final, or abstract.

  • Can an inner class be defined inside a method?
  • Yes it can be defined inside a method and it can access data of the
    enclosing methods or a formal parameter if it is final.

  • What is an anonymous class?
  • It is a type of inner class with no name.Once defined an object can be
    created of that type as a parameter all in one line. it cannot have
    explicitly declared constructor.The compiler automatically provides an
    anonymous constructor for such class.

    An anonymous class is never abstract. An anonymous class is always an
    inner class; it is never static. An anonymous class is always
    implicitly final.