Saturday, May 9, 2009

Aasara


Wednesday, April 22, 2009

Vivekananda Degree College

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.

Java Questions - 2


  • What is a thread?
  • A thread is most fundamental unit of a computer program which is under execution independent of other parts.A thread and a task are similar and often confused.An operating system executes a program by allocating it certain resources like memory,CPU cycles and when there are many a programs doing several things corresponding to several users requests.In such a scenario each program is viewed as a 'task' by OS for which it identifies an allocate resources. An OS treats each application e.g. Word Processor,spreadsheet,email client etc as a separate task , if a certain program initiates some parallel activity e.g. doing some IO operations,printing then a 'thread' will be created fro doing this job.

  • What is the difference between process and threads?
  • A thread is part of a process; a process may contain several different threads. Two threads of the same process share a good deal of state and are not protected against one another, whereas two different processes share no state and are protected against one another. Two threads of the same process have different values of the program counter; different stacks (local variables); and different registers.The program counter, stack pointer, and registers are therefore saved in the thread table. Two threads share open files and memory allocation; therefore, file information and memory information (e.g. base/limit register or page table) is stored in the process table.

  • What are two types of multitasking?
  • Co-operative
    In case of co-operative multitasking applications consume resources i.e. memory and CPU cycle and once it is completed with its execution of set of instructions, it returns control back to the OS. The scheme depends on the application co-operating and so is known as co-operative multitasking. In cases where the application entered an endless loop and never reached the code which handed control back to the operating system, the whole machine became locked up. An example is Windows 3.1

    Pre -emptive
    In this technique the operating system allocates resources to an application. This will enable it to execute. Rather than wait for the application to give the resources up, the operating system is
    activated at certain time intervals and may take the resources back from the executing application and allocate them to another application that is waiting.Example: Unix, Windows NT, and 32 bit programs running under Windows '95


  • What are two ways of creating threads in Java and why so?
  • Threads can be created in the following ways :

    -Instantiating a class extending java.lang.Thread class and calling start() method

    -Creating a java.lang.Thread and passing a reference of a class implementing Runnable interface.Then calling start() method on this object.
    As mentioned,Java supports these two mechanisms for Thread creations but second option is preferred as in first case there is a possibility of single inheritance making a thread object less flexible in its behaviour while in second case a thread object can be clubbed with multiple features.

  • How does multithreading take place on a computer with a single CPU?
  • It is the responsibility of scheduler to organise multiple tasks by allocating execution time to each task, in such a way that it seems to be executed in a sequential fashion to rest of the world.

  • How a Java object be locked for exclusive use by a given thread?
  • A Java object can be locked for an exclusive use of a thread by making it available via a 'synchronized' block or method.Only a particular thread at given time which will be possessing the lock on the object will be able to do execution of code available in synchronized block or method, once this thread with lock is through with its executions then it releases the lock on the object and it is made available to the next thread in wait state.

  • What is Synchronization?
  • In Java, JVM takes care of thread synchronization. Java support multithreading and data is shared along multiple threads.
    Inside the Java virtual machine, each thread is awarded a Java stack, which contains data no other thread can access, including the local variables, parameters, and return values of each method the thread has invoked. The data on the stack is limited to primitive types and object references. In the JVM, it is not possible to place the image of an actual object on the stack. All objects reside on the heap.
    There is only one heap inside the JVM, and all threads share it. The heap contains nothing but objects. There is no way to place a solitary primitive type or object reference on the heap -- these things must be part of an object. Arrays reside on the heap, including arrays of primitive types, but in Java, arrays are objects too.

    Besides the Java stack and the heap, the other place data may reside in the JVM is the method area, which contains all the class (or static) variables used by the program. The method area is similar to the stack in that it contains only primitive types and object references. Unlike the stack, however, the class variables in the method area are shared by all threads.
    Object and class locks
    As described above, two memory areas in the Java virtual machine contain data shared by all threads. These are:

    The heap, which contains all objects
    The method area, which contains all class variables
    If multiple threads need to use the same objects or class variables concurrently, their access to the data must be properly managed. Otherwise, the program will have unpredictable behavior.

    To coordinate shared data access among multiple threads, the Java virtual machine associates a lock with each object and class. A lock is like a privilege that only one thread can "possess" at any one time. If a thread wants to lock a particular object or class, it asks the JVM. At some point after the thread asks the JVM for a lock -- maybe very soon, maybe later, possibly never -- the JVM gives the lock to the thread. 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.

    Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object.

    Threads need not obtain a lock to access instance or class variables. If a thread does obtain a lock, however, no other thread can access the locked data until the thread that owns the lock releases it.

    Monitors
    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. When a thread arrives at the first instruction in a block of code that is under the watchful eye of a monitor, the thread must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code.

    When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object.

  • Explain wait(),notify(), and notifyAll() methods?
  • These methods are used for thread intercommunication and usually called within synchronised block or methods.A thread with lock on the object when calls wait() then it goes into wait state till some other thread with lock on this object invokes notify() method or the notifyAll() method.

  • What is a Daemon thread?
  • A ''daemon'' thread is one that is supposed to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non
    daemon threads complete the program is terminated. Conversely, if there are any non-daemon threads still running the program doesn' t terminate.

  • How a dead thread can be started?
  • It is not possible to start a dead thread.

  • What is the difference between String and StringBuffer?
  • String objects are immutable. It means any method like concat, substring, replace called upon an existing String object will return a new String object i.e. updations of an existing String object will not be reflected in the same object rather a new String object will be created.

    A StringBuffer implements a mutable sequence of characters, which can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point

  • How is '==' different from .equals() method in case of String objects?
  • In case of String objects:

    '==': does reference check

    .equals() method: checks the contents of the two String objects.

    The following example will illustrate the difference between the two:


  • Explain StreamTokenizer?
  • The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.

    Each byte read from the input stream is regarded as a character in the range '\u0000' through '\u00FF'. The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character. Each character can have zero or more of these attributes.

    In addition, an instance has four flags. These flags indicate:

    Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens.
    Whether C-style comments are to be recognized and skipped.
    Whether C++-style comments are to be recognized and skipped.
    Whether the characters of identifiers are converted to lowercase.
    A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF.

  • What is Collection?
  • A collection object(technically speaking data-structures) represents a container for objects,which generally expands itself to accommodate these objects.One has not be bothered about how many objects a collection object can contain.The collection classes like Vector,Hashtable(both are in Java 1.1) and ArrayList,HashMap(both are in Java2)are sophisticated way of holding objects.One can pick any of the collection objects as per need and sometimes on choice.

  • Explain List,Set and Map.
  • The three most significant types of Collections framework are:
    -List
    -Set
    -Map

    First,look into the hierarchy of collection interfaces:

    java.util.Collection <---------java.util.List
    java.util.Collection <--------- java.util.Set
    java.util.Collection <--------- java.util.SortedSet
    Collection interface is the root interface of collection hierarchy.List interface is most commonly used collection type.LinkedList and ArrayList are its well known implementing classes.Lists can store objects only and not primitive types like int but one can create Integer objects.All objects in List are indexed from 0 to (size of list-1)

    Set is very much like list but with added constraint of not storing duplicate values.Sets do not impose a 0..size-1 indexing of the elements (that's what Lists do), so List methods like get(int index) are not available for sets.

    HashSet is mostly used set which only works with elements, like String and Integer, which have a hashCode() defined. The TreeSet is an alternative which has performance issues, but keeps the set in sorted order, so iteration will yield the values in sorted order.

    java.util.Collection <-----------java.util.Map

    A Map is altogether different from List and Set.It stores key-value pairs and any value can quickly be searched on the basis of a key.A map cannot contain duplicate keys; each key can map to at most one value.'Map' is a basic interface being implemented by classes HashMap and TreeMap.HashMap is most commonly used which can store objects in unordered fashion while TreeMap can store in ordered fashion.Some implementations of Map prohibit null keys and values and some have restrictions on type of their keys.You may get NullPointerException or ClassCastException when trying to insert or retrieve invalid keys or values.
    Read More on Collection Framework...

  • What is the serialization?
  • Serialization is a process of converting an object into byte stream which can be stored in persistent storage area like file system or database and can occur over a network.This persisted object can be converted back,called a process of deserialization, to restore original object. A java.io.Serailizable interface provides syntactical approach to do serialization.This interface does not contain any method,also known as marker interface.
    Object serialization is necessary for:
    -Java RMI, while sending messages to a remote object,it is necessary to transport arguments to remote object and return values.
    -Java Beans, state information of object is stored and later recovered when needed.

  • What is the difference between Serializable and Externalizable interface?
  • java.io.Serializable interface is an empty interface with no methods and attributes.It is implemented by objects which are needed to be serialized and serves only to identify the semantics of being serializable.
    When process of serializing an object is to be controlled then Externalizable interface is used.The Externizable interface extends Serializable and adds two methods,writeExternal() and readExternal() which are automatically called during serialization and deserialization.
    Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
    private void writeObject(java.io.ObjectOutputStream out) throws IOException

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

  • What is memory leak?
  • A memory leak occurs when all references (pointers) to a piece of allocated memory are overwritten, cleared, or pass out of scope. The result is that the program simply "forgets" about that particular piece of memory.Unfortunately , the operating environment (usually an OS) is not aware of the application's amnesia. That memory is treated by the outside world as though it still belongs to the application. The memory is therefore completely unavailable;it has "leaked". (In the worst case, the memory can become unavailable to all applications in the system, even if the application that created the leak is terminated. The memory can only be reclaimed by rebooting the system.)

  • Difference between ArrayList and Vector class?
  • From an API perspective, the two classes are very similar.

    Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList.

    Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

  • What is the difference between Hashtable and HashMap?
  • Both Hashtable and HashMap store key-value pairs but they have following distinctive features:
    -Hashtable is synchronized while HashMap is not.In such a case Hashtable has performance overhead and should only be used when data is to be accessed in thread safe manner.
    -In Hashtable any non-null object can be used as a key or as a value but HashMap allows null keys and values.

  • What is JFC?
  • Java Foundation Classes(JFC) offers lightweight Java language specific GUI controls.JFC consists of group of classes for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications.
    JFC supoorts:
    -Swing GUI Components
    -Pluggable Look-and-Feel Support
    -Accessibility API
    -Java 2D API
    -Internationalization

  • What is the difference between JFC Swing and AWT?
  • AWT has following characteristics:
    -It has native C specific code
    -Rendering of AWT controls is dependent upon underlying OS.
    While JFC Swing is :
    -Pure Java based
    -Lightweight components
    -Pluggable look and feel features
    -Appearance of GUI developed using JFC Swing will be consistent across various OS.
    -Swing uses a more efficient event model than AWT; therefore, Swing components can run more quickly than their AWT counterparts

  • What is the base class for all swing components?
  • JFC Swing components (like textfields,buttons,checkboxes,lists etc. ) are direct replacements of corresponding AWT components and it replaces just some section of AWT GUI components,other aspects of AWT like layout managers remains unchanged.All these Swing components are extended from the javax.swing.JComponent, which has following hierarchy:
    java.lang.Object
    - java.awt.Component
    - java.awt.Container
    - javax.swing.JComponent

  • What are lightweight and heavyweight components ?
  • In AWT, all GUI controls are referred as heavyweight components as they are dependent on underlying OS(e.g. Windows,Solaris etc.) to provide it(paint it and redraw it).An AWT button control in MacOS is actually a MacOS button.
    All Swing components are lightweight components(except for the top-level ones: JWindow, JFrame, JDialog, and JApplet) as they do not require underlying OS to provide them.JVM renders Swing components and hence they are platform independent but they have performance related issues as compared to heavyweight components which are faster to be rendered due to hardware acceleration.
    The lightweight components have transparent pixels unlike heavyweights which have opaque pixels.Mouse events on a lightweight component fall through to its parent; while on a heavyweight component it does not.It is generally not recommended to mix heavyweight components with lightweight components while building the GUI.

  • How can a GUI component handle its own events?
  • A GUI component handles its events by implementing the required event listener interface.It adds its own event listener in order to keep a track of all events associated with it.AWT has Java1.0 and Java1.1 of Event handling in different manners:
    In Java1.0:Event handling is based on inheritance.A program catches and processes GUI events by subclassing GUI components and override either action() or handleEvent() methods.There are two possibilities in this scenario:

    a)Each component is subclassed to specifically handle its target events. The results in too many classes.
    b)All events or a subset for an entire hierarchy for handling a particular container; results in container's overridden action() or handleEvent() method and complex conditional statement for events processing.

    The event handling in Java 1.0 had issues like cumbersome to handle by developers,flitering of events was not too efficient as it was done in a single method handleEvent().

    In Java 1.1 these issues are resolved through delegation based event model.The GUI code can be seprated from event handling code which is cleaner,flexible,easier to maintanin and robust.In delegation event model,java.util.EventObject is the root class for event handling.An event is propagated from "Source" object(responsible for firing the event) to "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated.

    A listener is commonly an "adapter" object which implements the appropriate listener/(s) for an application to handl of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other.

    There can be following types of events:
    A low-level event represents a low-level input or window-system occurrence on a visual component on the screen.
    The semantic events are defined at a higher-level to encapsulate the semantics of a UI component's model.

    The low event class hierarchy:

    -java.util.EventObject

    -java.awt.AWTEvent

    -java.awt.event.ComponentEvent (component resized, moved, etc.)

    -java.awt.event.FocusEvent (component got focus, lost focus)

    -java.awt.event.InputEvent


    -java.awt.event.KeyEvent (component got key-press, key-release, etc.)

    -java.awt.event.MouseEvent (component got mouse-down, mouse-move, etc.)

    -java.awt.event.ContainerEvent

    -java.awt.event.WindowEvent

    The semantics event class hierarchy:

    -java.util.EventObject

    -java.awt.AWTEvent

    -java.awt.event.ActionEvent ("do a command")

    -java.awt.event.AdjustmentEvent ("value was adjusted")

    -java.awt.event.ItemEvent ("item state has changed")

    -java.awt.event.TextEvent ("the value of the text object changed")

    The low-level listener interfaces in AWT are as follows:

    java.util.EventListener

    - java.awt.event.ComponentListener

    - java.awt.event.ContainerListener

    - java.awt.event.FocusListener

    - java.awt.event.KeyListener

    - java.awt.event.MouseListener

    - java.awt.event.MouseMotionListener

    - java.awt.event.WindowListener

    The semantic listener interfaces in AWT are as follows:

    java.util.EventListener

    -java.awt.event.ActionListener

    -java.awt.event.AdjustmentListener

    -java.awt.event.ItemListener

    -java.awt.event.TextListener

    There are following Adapter classes in AWT :

    java.awt.event.ComponentAdapter

    java.awt.event.ContainerAdapter

    java.awt.event.FocusAdapter

    java.awt.event.KeyAdapter

    java.awt.event.MouseAdapter

    java.awt.event.MouseMotionAdapter

    java.awt.event.WindowAdapter


  • What is a Layout Manager and what are its different types and their advantages?
  • In Java,a GUI component does not decide about its geometry(location and size) on its own.A layout manager is an object which is responsible for managing or arranging the size and location of a GUI component.In AWT there are following layout managers which are supported:

    -Flow
    -Border
    -GridBag
    -Card
    -GridBag

    These layout managers organizes components consistently across all windowing platforms. Irrespective of underlying windowing OS,layouts behave in a regular fashion and show GUI components.A layout manager also represents an instance of a class which implements LayoutManager interface.The layout manager is set by setLayout(LayoutManager layoutManager) method.

  • How are the elements of a GridBagLayout organized?
  • A GridBagLayout organizes/arranges all GUI controls to a grid. However, these controls are of different sizes and may occupy more than one row or column of the grid. These rows and columns may have different sizes as well.It is by far most powerful layout manager and requires good practice and understanding to use.It can combine the features of Border,Flow and Card layouts and capable of much more.
    GridBag layout divides its container into an array of cells, different cell rows can have different heights, and different cell columns can have different widths. A component can occupy part or all of a region.While a region is spanned over a single cell or a rectangle made up of multiple cells.A helper class called GridBagConstraints is used to hold all the layout position information.The add(Component, Object) version of the add() method is used for adding a control, passing an instance of GridBagConstraints as the Object parameter.

  • What are the problems faced by Java programmers in absence of layout managers?
  • If relevant layout managers are not used while designing a GUI then GUI controls will have haphazard/inconsistent display across multiple windowing systems.These GUI controls will neglect their common sizing and positioning that ideally should be same across various windowing systems.
    In order to counter this issue, an appropriate layout which is applicable for container object, must be chosen.

  • Where the CardLayout is used?
  • A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.

    The ordering of cards is determined by the container's own internal ordering of its component objects. CardLayout defines a set of methods that allow an application to flip through these cards sequentially, or to show a specified card. The addLayoutComponent(java.awt.Component,java.lang.Object) method can be used to associate a string identifier with a given card for fast random access


  • What is the difference between GridLayout and GridBagLayout?
  • GridLayout class lays all components in a rectangular grid like structure of container. The container is divided into an equal sized rectangles and each component is placed inside a rectangle.
    The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each component occupying one or more cells, called its display area.

    Each component managed by a GridBagLayout is associated with an instance of GridBagConstraints. The constraints object specifies where a component's display area should be located on the grid and how the component should be positioned within its display area. In addition to its constraints object, the GridBagLayout also considers each component's minimum and preferred sizes in order to determine a component's size.

  • How will you add a panel to a frame?
  • Here goes the snippet:

    import javax.swing.*;

    public class XYZ extends JFrame{

    public XYZ(){

    JPanel panel =new JPanel();

    this.getContentPane().add(panel);

    }

    public static void main (String args[]){

    XYZ obj=new XYZ();

    obj.setVisible(true);

    }

    }


  • What is the difference between Application and Applet?
  • An applet runs in client side web browser. A class extending java.awt.Applet class which has methods like init(), start(), stop(), destroy(),paint() overridden.An applet has restriction of accessing client side resources like network connections, it cannot open socket connections and cannot write to client side files i.e. hard disk.
    An application runs standalone with a support of virtual machine. An application does not have nay restrictions as Applets have over network and file related activities.They are free to open sockets over a network read and write to a file.

  • Explain Lifecycle of the Applet and what is the order of method invocation in an applet?
  • An applet is built up of four methods:init,start,stop and destroy.First of all an instance of applet subclass will be created and then applet will be initialized.Swing provides a special subclass of Applet, called javax.swing.JApplet, which should be used for all applets that use Swing components to construct their GUIs.
    Here is a sequence of method calls in an applet :

    -init():An applet can initialize itself and does whatever initializations are required to do for an applet.
    -start(): This method is automatically called when applet is initialized.When a user comes back to a page with an applet this method is invoked then too.
    -stop(): This method is called when user moves away from the webpage containing applet
    -destroy:It is responsible for clean up and is called when browser is shut down normally.
    An applet can be initialized and destroyed only once in its lifetime but it can be started and stopped several times.

  • What is the difference between Java class and bean?
  • What differentiates Beans from typical Java classes is introspection. The tools that recognize predefined patterns in method signatures and class definitions can "look inside" a Bean to determine its properties and behavior. A Bean's state can be manipulated at the time it is being assembled as a part within a larger application. The application assembly is referred to as design time in contrast to run time. In order for this scheme to work, method signatures within Beans must follow a certain pattern in order for introspection tools to recognize how Beans can be manipulated, both at design time, and run time.

  • What is difference between trusted and untrusted applet?
  • A trusted applet is one which signed by a trusted authority. The trusted applet is installed on the local hard disk, in a directory on the CLASSPATH used by the program that you are using to run the applet. Usually, this is a Java-enabled browser, but it could be the appletviewer, or other Java programs that know how to load applets.

    The applet is signed by an identity marked as trusted in your identity database.By default all applets downloaded in client browser are untrusted.
    -They cannot read or write files to clients' local file system at all.
    -They cannot start a program at client's machine.
    -They cannot do network operations i.e. cannot do Socket programming.
    -They cannot load libraries and use native codes.

  • How do you set Java Library path programmatically?
  • Java library path can be set by choosing an option as:-

    -Djava.library.path=your_path

    While setting the java.library.path property to "." instructs the Java virtual machine to search for native libraries in the current directory.

    And you execute your code as :
      java -Djava.library.path=. HelloWorld

    The "-D" command-line option sets a Java platform system property. But these values are 'read only' like many of the system properties, the value in java.library.path is just FYI and changing it doesn't actually change the behaviour of the JVM.
    If you want to load a library from a specific location, you can use System.load() instead with the full path to the library.

  • Explain the usage of java.util.Date and more classes and APIs for date handling in Java?
  • The class java.util.Date
    -Represents a point in time.
    -Corresponds to the number of milliseconds since the start of the Unix epoch on January 1, 1970, 00:00:00 GMT.
    -This class depends on System.currentTimeMillis() to obtain the current point in time,which actually returns a long value and its accuracy and precision is determined by the implementation of System and underlying OS.
    Apart from this class there are several other classes like GregorianCalendar,SimpleTimeZone,SimpleDateFormat,DateFormatSymbols,java.sql.Date,java.sql.Time ,java.sql.Timestamp which are used for handling date and time related problems.In the table shown below a very brief purposes of these classes have been summarized:



  • JDBC

  • What is JDBC ?
  • JDBC is Java Database Connectivity, a collection of APIs for connecting a Java application to a database. It is an abstraction over ODBC so as to provide Java clients an interface to connect to the database end.The latest update of the JDBC API is JDBC3.0. It contains many features, including scrollable result sets and the SQL:1999 data types.
    The first version of JDBC(JDBC1.22 with JDK1.1.x release) had only one pacakge named java.sql.* but in JDBC2.0(released with Java2) there had been introduced several new features in two pacakges namely,java.sql.* and javax.sql.*

  • What are four drivers available in JDBC?
  • Type 1: JDBC-ODBC bridge.It is for databases that support ODBC.It Uses a bridging technology to access the database (e.g., Sun's JDBC-ODBC Bridge driver)

    Type 2: JDBC to a database vendor DLL.It uses native API drivers.It requires software on the client machine. Uses native API drivers; requires software on the client machine Supplied by the vendor or by third parties.

    Type 3: JDBC to middleware software to the database.It translates JDBC calls into a database-independent network protocol, which a server then translates into a database protocol

    Type 4: Pure Java to a network protocol.It uses the network protocols built into the database engine

    Type1 and Type2 database drivers are not suitable for Internet based connection to the databases as these types of database drivers are to be installed on client machine.

  • How do you establish database connection using JDBC?
  • The database connection using JDBC involves two steps:
    - Loading database driver class
    - Making the connection to database
    Here is code snippet for connection to the database:

    String driverClassName="sun.jdbc.odbc.JdbcOdbcDriver";
    String url="jdbc:odbc:dsnname";
    String usrname="hello";
    String passwd="india";
    String qry="select username from users";
    try{
    Class.forName(driverClassName);//loading the database driver
    Connection con=DriverManager.getConnection(url,usrname,passwd);
    Statement stmt=con.createStatement();
    ResultSet rs =stmt.executeQuery(qry);
    while(rs.next()){

    }
    } catch(Exception exc){
    exc.printStackTrace();
    }


  • How do you connect to a MySql Database using JDBC?
  • Recently some newbie asked me a simple question of connecting to MySql database using JDBC.Here is a code snippet for that.The important thing here is to ensure that you have added MySql database driver classes(mysql.jar) in your classpath. Here goes the code snippet:

    import java.sql.*;

    public class MySqlConnect {


    public static void main (String[] args)
    {
    Connection connection = null;

    try
    {
    String userName = "root";
    String password = "bunty";
    String url = "jdbc:mysql://localhost:3306/systdb";

    Class.forName ("com.mysql.jdbc.Driver").newInstance ();

    connection = DriverManager.getConnection (url, userName, password);
    System.out.println ("Database connection established");
    }
    catch (Exception e)
    {
    System.err.println ("Connection to database server cannot be establish");
    }
    finally
    {
    if (connection != null)
    {
    try
    {
    connection.close ();
    System.out.println ("Database connection terminated");
    }
    catch (Exception e) { System.out.println ("These connection errors can be ignored."); }
    }
    }
    }
    }

  • What are the different types of Statements?
  • There are several statements supported in JDBC and mainly they are as given below:
    -Regular statement (use createStatement method),
    -Prepared statement (use prepareStatement method)
    -Callable statement (use prepareCall)

  • What is PreparedStatement and how is different from Statement?
  • A PreparedStatement, in contrast to a Statement, is used for SQL statements that are executed multiple times with different values. For instance, you might want to insert several values into a table, one after another. The advantage of the PreparedStatement is that it is pre-compiled, reducing the overhead of parsing SQL statements on every execution.
    In such cases DBMS will execute the query directly without worrying about compiling the statement again.

  • What is the difference between executeQuery () and execute() ?
  • The return type of execute() method is boolean , if true that means a ResultSet object is returned, if false no result is returned.The ResultSet is obtained on Statement object in such case through getResultSet method.In case of executeQuery() method once executed returns ResultSet object.

  • What is the difference between executeQuery () and executeUpdate()?
  • The difference between executeQuery and executeUpdate is that executeUpdate is for executing statements that change data in the database. For example, use executeUpdate to execute a CREATE an INSERT or an UPDATE statement. executeUpdate returns an int, and the value of that int corresponds to the number of records that were modified. While executeQuery() method is used for executing SQL statements and it returns ResultSet object.

  • How do you call a stored procedure in Java?
  • Through a CallableStatement: Callable statements are implemented by the CallableStatement object. A CallableStatement is a way to execute stored procedures in a JDBC-compatible database.

  • What are new features from JDBC2.0 onwards?
  • New Features in JDBC 2.0:
    -Scrollable resultset
    -No more updations on tables through queries required,one can use methods provided like updateRow(),insertRow() and deleteRow() etc.
    -Send multiple SQLs to database as a unit/batch(addbatch(),executeBatch() )
    -Use new SQL3 datatypes as column values like Blob,Clob etc

  • How can a cursor move in scrollable result sets?
  • JDBC result sets are created with three properties: type, concurrency and holdability.
    The type can be one of
    -TYPE_FORWARD_ONLY
    -TYPE_SCROLL_INSENSITIVE
    -TYPE_SCROLL_SENSITIVE.

    The concurrency can be one of
    -CONCUR_READ_ONLY
    -CONCUR_UPDATABLE.

    The holdability can be one of
    -HOLD_CURSORS_OVER_COMMIT
    -CLOSE_CURSORS_AT_COMMIT.

    JDBC allows the full cross product of these. Some database like SQL 2003 prohibits the combination {TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE}, but this combination is supported by some vendors, notably Oracle.

    The movable cursors,moving forward and backward on a resultset is one of the new features in the JDBC 2.0 API. There are also methods that let you move the cursor to a particular row and check the position of the cursor.

    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

    ResultSet resultSet = stmt.executeQuery("SELECT FNAME, LNAME FROM EMPLOYEE");

    while (resultSet.next()) {

    . . . // iterates forward through resultSet

    }

    . . .

    resultSet.absolute(5); // moves cursor to the fifth row

    . . .

    resultSet.relative(-2); // moves cursor to the third row

    . . .

    resultSet.relative(4); // moves cursor to the seventh row

    . . .

    resultSet.previous(); // moves cursor to sixth row

    . . .

    int rowNumber = resultSet.getRow(); // rowNumber should be 6

    resultSet.moveAfterLast(); // moves cursor to position // after last row

    while (previous()) {

    . . . // iterates backward through resultSet

    }

    When a resultset type is defined then it is also significant to define whether it is readonly or updatable and type and concurrency should be in the same order as shown in the code above.If you change the order then compiler can not distinguish it.If you specify the constant TYPE_FORWARD_ONLY, it creates a nonscrollable result set, in which the cursor moves forward only. The default value of ResultSet object type is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

  • Differentiate TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?
  • TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.

    TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.

    This needs a small coding effort to verify this differntiation.Any volunteers? Please write in your comments to put your understanding about this concept.


  • How will you differentiate the following two ways of loading a database driver?
  • (1)DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    (2)Class.forName("oracle.jdbc.driver.OracleDriver");

    In case one, to load the driver, one needs an appropriate class to load, make a driver instance and register it with the JDBC driver manager. Class.forName() will cause the class to create an instance, and call the current class loader's DriverManager.registerDriver() method to announce its presence.While DriverManager.registerDriver registers an instance of the with driver manager

  • How can you display a particular web page from an applet?
  • The following code snippet shows you how to achieve that using showPage method is capable of displaying any URL passed to it.

    import java.net.*;
    import java.awt.*;
    import java.applet.*;

    public class TestApplet extends Applet
    {
    // Applet code goes here

    // Show a page
    public void showPage ( String showPage)
    {
    URL url = null;

    // Create a URL object
    try
    {
    url = new URL ( showPage );
    }
    catch (MalformedURLException e)
    {
    // Invalid URL
    }

    // Show URL
    if (url != null)
    {
    getAppletContext().showDocument (url);
    }

    }
    }

  • How can you get the hostname on the basis of IP addres ?
  • The following snippet of code helps you in finding hostname on the basis of IP address:-


    InetAddress inetAddress = InetAddress.getByName("67.83.45.98");
    System.out.println ("Host Name: " + inetAddress.getHostName());

  • How can you get an IP address of a machine from its hostname?
  • In case of TCP protocol i.e. ServerSocket:

    Each Socket connection accepted corresponds to who is connecting to your server, that means relevant method calls on ServerSocket will fetch IP address and port of the same.

    Socket socket = serverSocket.accept();

    // Print IP address and port
    System.out.println ("Connecting from : " +
    socket.getInetAddress().getHostAddress() + ':' + socket.getPort());


    In case of UDP i.e. DatagramSocket

    The DatagramPacket received contains all the necessary information:

    DatagramPacket datagramPacket = null;

    // Receive next packet
    datagramSocket.receive ( datagramPacket );

    // Print address + port
    System.out.println ("Packet received from : " +
    datagramPacket.getAddress().getHostAddress() + ':' + datagramPacket.getPort());

  • How do you know who is accessing your server?
  • In case of TCP protocol i.e. ServerSocket:

    Each Socket connection accepted corresponds to who is connecting to your server, that means relevant method calls on ServerSocket will fetch IP address and port of the same.

    Socket socket = serverSocket.accept();

    // Print IP address and port
    System.out.println ("Connecting from : " +
    socket.getInetAddress().getHostAddress() + ':' + socket.getPort());


    In case of UDP i.e. DatagramSocket

    The DatagramPacket received contains all the necessary information:

    DatagramPacket datagramPacket = null;

    // Receive next packet
    datagramSocket.receive ( datagramPacket );

    // Print address + port
    System.out.println ("Packet received from : " +
    datagramPacket.getAddress().getHostAddress() + ':' + datagramPacket.getPort());

  • What are different socket options?
  • The different Socket options are :

    SO_TIMEOUT
    SO_LINGER
    TCP_NODELAY
    SO_RCVBUF
    SO_SNDBUF.

    They may be specified in various scenarios e.g. one might like to specify a timeout for read operations, to control the amount of time a connection will linger for before a reset is sent, whether Nagle's algorithm is enabled/disabled, or the send and receive buffers for datagram sockets.


  • What should I use a ServerSocket or DatagramSocket in my applications?
  • DatagramSocket accepts only UDP packets, whereas ServerSocket allows TCP connections in an application. It depends on the protocol one implements. Here are few things which one should keep in mind while implementing a new protocol:

    -UDP is not a reliable protocol as you may loose data packets over the network so while coding you will have to handle missing packets in your client/server.

    -ServerSockets use TCP connections for communication.TCP is safe and reliable protocol and guarantees delivery, all you need is InputStream to read and OutputStream to write over TCP.

Wednesday, February 11, 2009

Core Java Questions

1.what is a transient variable?
A transient variable is a variable that may not be serialized.

2.which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.

3.Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.

4. How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

5. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

6. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object..

7. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

8. Is null a keyword?
The null value is not a keyword.

9. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.

10. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.

11. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.

12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.

13. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.

14. Which characters may be used as the second character of an identifier,
but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

15. What is the List interface?
The List interface provides support for ordered collections of objects.

16. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

17. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects

18. 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.

19. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.

20. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

21. Which method of the Component class is used to set the position and
size of a component?
setBounds()

22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

23What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

24. Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.

25. Is sizeof a keyword?
The sizeof operator is not a keyword.

26. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.

27. 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. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

28. What restrictions are placed on the location of a package statement
within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).

29. Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

30. What is the immediate superclass of the Applet class?
Panel

31. 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.

32. Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.

33. What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.

34. What is the immediate superclass of the Dialog class?
Window

35. What is clipping?
Clipping is the process of confining paint operations to a limited area or shape.

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

37. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following:
for(;;) ;

38. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

39. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.

40. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.

41. What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

42. What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

43. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

44. What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

45. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.

46. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

47. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.

48. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.

49. In which package are most of the AWT events that support the event-delegation
model defined?
Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

50. What is the immediate superclass of Menu?
MenuItem

51. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

52. Which class is the immediate superclass of the MenuComponent class.
Object

53. What invokes a thread's run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

54. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

55. Name three subclasses of the Component class.
Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent

56. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.

57. Which Container method is used to cause a container to be laid out and redisplayed?
validate()

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

59. How many times may an object's finalize() method be invoked by the
garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.

60. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

61. What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type.

62. Which Java operator is right associative?
The = operator is right associative.

63. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

64. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.

65. What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

66. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.

67. What method is invoked to cause an object to begin executing as a separate thread?
The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

68. Name two subclasses of the TextComponent class.
TextField and TextArea

69. What is the advantage of the event-delegation model over the earlier event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.

70. Which containers may have a MenuBar?
Frame

71. How are commas used in the intialization and iteration parts of a for statement?
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

72. What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods..

73. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.

74. How are Java source code files named?
A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

75. What is the relationship between the Canvas class and the Graphics class?
A Canvas object provides access to a Graphics object via its paint() method.

76. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.

77. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.

78. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.

79. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

80. What is the difference between the String and StringBuffer classes?
String objects are constants. StringBuffer objects are not.

81. If a variable is declared as private, where may the variable be accessed?
A private variable may only be accessed within the class in which it is declared.

82. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

83. What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.

84. How are the elements of a BorderLayout organized?
The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

85. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

86. When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.

87. What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.

88. Which class is extended by all other classes?
The Object class is extended by all other classes.

89. Can an object be garbage collected while it is still reachable?
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected..

90. Is the ternary operator written x : y ? z or x ? y : z ?
It is written x ? y : z.

91. What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

92. How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding toward zero.

93. What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

94. 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.

95. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

96. If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

97. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.

98. What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

99. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.

100. For which statements does it make sense to use a label?
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.

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

102. Which TextComponent method is used to set a TextComponent to the read-only state?
setEditable()

103. How are the elements of a CardLayout organized?
The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

104. Is &&= a valid Java operator?
No, it is not.

105. Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.

106. Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.

107. What is the relationship between clipping and repainting?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

108. Is "abc" a primitive value?
The String literal "abc" is not a primitive value. It is a String object.

109. What is the relationship between an event-listener interface and an
event-adapter class?
An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.

110. What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

111. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.

112. Is a class a subclass of itself?
A class is a subclass of itself.

113. What is the highest-level event class of the event-delegation model?
The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

114. What event results from the clicking of a button?
The ActionEvent event is generated as the result of the clicking of a button.

115. How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

116. What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

117. How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

118. What advantage do Java's layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.

119. What is the Collection interface?
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.

120. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.

121. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

122. What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

123. What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.

124. Can an exception be rethrown?
Yes, an exception can be rethrown.

125. Which Math method is used to calculate the absolute value of a number?
The abs() method is used to calculate absolute values.

126. How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

127. When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.

128. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause.

129. Which class is the immediate superclass of the Container class?
Component

130. If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

131. How can the Checkbox class be used to create a radio button?
By associating Checkbox objects with a CheckboxGroup.

132. Which non-Unicode letter characters may be used as the first character
of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier

133. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.

134. What happens when you invoke a thread's interrupt method while it is
sleeping or waiting?
When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

135. What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

136. What is the return type of a program's main() method?
A program's main() method has a void return type.

137. Name four Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

138. What is the difference between a Choice and a List?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

139. What class of exceptions are generated by the Java run-time system?
The Java runtime system generates RuntimeException and Error exceptions.

140. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.

141. What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

142. Under what conditions is an object's finalize() method invoked by the garbage collector?
The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable.

143. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

144. What is the relationship between a method's throws clause and the exceptions
that can be thrown during the method's execution?
A method's throws clause must declare any checked exceptions that are not caught within the body of the method.

145. What is the difference between the JDK 1.02 event model and the event-delegation
model introduced with JDK 1.1?
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried..
In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

146. How is it possible for two String objects with identical values not to be equal
under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.

147. Why are the methods of the Math class static?
So they can be invoked as if they are a mathematical code library.

148. What Checkbox method allows you to tell if a Checkbox is checked?
getState()

149. What state is a thread in when it is executing?
An executing thread is in the running state.

150. What are the legal operands of the instanceof operator?
The left operand is an object reference or null value and the right operand is a class, interface, or array type.

151. How are the elements of a GridLayout organized?
The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.

152. 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.

153. If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

154. What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

155. What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.156. What are E and PI?
E is the base of the natural logarithm and PI is mathematical value pi.

157. Are true and false keywords?
The values true and false are not keywords.

158. What is a void return type?
A void return type indicates that a method does not return a value.

159. What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

160. What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

161. What happens when you add a double value to a String?
The result is a String object.

162. What is your platform's default character encoding?
If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1..

163. Which package is always imported by default?
The java.lang package is always imported by default.

164. What interface must an object implement before it can be written to a
stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

165. How are this and super used?
this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.

166. What is the purpose of garbage collection?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.

167. What is a compilation unit?
A compilation unit is a Java source code file.

168. What interface is extended by AWT event listeners?
All AWT event listeners extend the java.util.EventListener interface.

169. What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown
by the overridden method.

170. How can a dead thread be restarted?
A dead thread cannot be restarted.

171. What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.

172. What is a layout manager?
A layout manager is an object that is used to organize components in a container.

173. Which arithmetic operations can result in the throwing of an ArithmeticException?
Integer / and % can result in the throwing of an ArithmeticException.

174. What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

175. Can an abstract class be final?
An abstract class may not be declared as final.

176. What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

177. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.178. What is numeric promotion?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

179. What 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.

180. What is the difference between a public and a non-public class?
A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

181. To what value is a variable of the boolean type automatically initialized?
The default value of the boolean type is false.

182. Can try statements be nested?
Try statements may be tested.

183. What is the difference between the prefix and postfix forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.

184. What is the purpose of a statement block?
A statement block is used to organize a sequence of statements as a single statement group.

185. What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

186. What modifiers may be used with a top-level class?
A top-level class may be public, abstract, or final.

187. What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program..

188. How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

189. Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

190. When is an object subject to garbage collection?
An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

191. What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

192. What methods are used to get and set the text label displayed by a Button object?
getLabel() and setLabel()

193. Which Component subclass is used for drawing and painting?
Canvas

194. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

195. What are the two basic ways in which classes that can be run as threads may be defined?
A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

196. What are the problems faced by Java programmers who don't use layout managers?
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

197. What is the difference between an if statement and a switch statement?
The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

198. What happens when you add a double value to a String?
The result is a String object.

199. What is the List interface?
The List interface provides support for ordered collections of objects.
Justify Full





Friday, February 6, 2009

slam book

Wednesday, January 28, 2009

Home

Tarun - Details

Tarun Kumar Konhtam


Tarun Kumar Kontham

Age 23

lombard

il

60148

userid


First name:



Yahoo

Gmail

Last name:

Tuesday, November 18, 2008

todat pic


Part 2

Thursday, September 18, 2008

New Pics










Friday, August 15, 2008

Tuesday, July 8, 2008

Munna - Manasa

Saturday, June 28, 2008





























Wednesday, June 11, 2008

















Saturday, April 26, 2008

Out Of Control



Classmates