What is an Interface?
A Java Interface can contain only method declarations and/or public static final constants, which doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present in the Interface. Also Interfaces have the ability to extend from other Interfaces(multiple Inheritance) and cannot be instantiated with the new operator.
What is an Abstract Class (ABC)?
Abstract class must be extended/subclassed in order to be implemented (useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. i.e. A Vehicle class would be an ABC, while its subclasses Car, Truck, FourWheeler, Spacecraft, etc are specific implementations.
What are the similarities between an ABC and an Interface?
•There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an Interface.
•Neither an ABC nor an Interface can be instantiated.
What are the main differences between an ABC and an Interface?
•An Interface can only contain public members, whereas an ABC can contain private as well as protected members.
•All variables in an Interface are by default, public static final, while an ABC can have instance variables.
•A class that implements an Interface must implement all methods defined in that Interface, while a class extending an ABC need not implement any of the methods defined in an ABC.
When is an Interface preferred over an ABC?
Interfaces are preferred in situations when all its properties need to be implemented by subclasses.
When is an ABC preferred over an Interface?
Abstract classes are preferred in situations when some general methods should be implemented and specialization behavior should be implemented by subclasses.
When should you tend towards an ABC or towards an Interface?
If the various objects are all of the same kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an Interface.
What is the down side to an ABC and an Interface?
The downside to an Interface is; if you want to add a new feature (method) in its contract, then you MUST implement the method in all of the classes which implement that Interface. However, in the case of an ABC, the method can be simply implemented in the ABC and the same can be called by its subclass.
Why should you separate Interfaces from implementation?
Interfaces are the company’s most valuable resources – they’re expensive.
Can Interfaces be used to describe the “peripheral abilities” of a class?
Yes, Interfaces are often used to describe the peripheral abilities of a class, and not its central identity. i.e. An Automobile class might implement the Paint interface, which could apply to many otherwise totally unrelated objects.
What must a class do to implement an Interface?
The class must provide all the methods in the interface and identify the interface in its implements clause.
What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.
How to define an Interface?
In Java an Interface defines the methods but does not implement them and can include constants. A class that implements Interface is bound to implement all the methods defined in Interface.
Example of Interface:
public interface SampleInterface{
public void sampleFunction();
public int SAMPLE_CONSTANT = 1;
}
How to define an ABC?
An ABC serves as a template. An ABC must be extended/subclassed for it to be implemented. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated. An ABC is a class that provides some general functionality but leaves specific implementation to its inheriting classes.
Example of an ABC:
abstract class SampleABC{
protected String name;
public String getName() {
return name;
}
public abstract void sampleFunction();
}
Explain in your own words the "bottom line" benefits of the use of an interface.
The interface makes it possible for a method in one class to invoke methods on objects of other classes, without the requirement to know the true class of those objects, provided that those objects are all instantiated from classes that implement one or more specified interfaces. In other words, objects of classes that implement specified interfaces can be passed into methods of other objects as the generic type Object, and the methods of the other objects can invoke methods on the incoming objects by first casting them as the interface type.
Thursday, September 27, 2007
Wednesday, September 26, 2007
Java Design Patterns
Java is associated with a number of Design Patterns, which are subdivided into three groups, creational, structural, and behaviour. Below is a list of all patterns in Java and a brief description of each. Throughout the next few weeks I will provide coded examples for each individual pattern. Stay tuned!
Creational Patterns
Abstract Factory - Various methods to make various objects various ways.
Builder - Make and return one object various ways.
Factory Method – Methods to make and return components of one object various ways.
Prototype - Make new objects by cloning the objects which you set as prototypes.
Singleton - A class distributes the only instance of itself.
Structural Patterns
Adapter - A class extends another class and takes in an object, and makes the taken object behave like the extended class.
Bridge - An abstraction and implementation are in different class hierarchies.
Composite - Assemble groups of objects with the same signature.
Decorator - One class takes in another class, both of which extend the same abstract class, and adds functionality.
Façade - One class has a method that performs a complex process calling several other classes.
Flyweight - The reusable and variable parts of a class are broken into two classes to save resources.
Proxy - One class controls the creation of and access to objects in another class.
Behaviour Patterns
Chain of Responsibility - A method called in one class can move up a series to find an object that can properly execute the method.
Command - An object encapsulates everything needed to execute a method in another object.
Interpreter- Define a macro language and syntax, parsing input into objects which perform the correct opertaions.
Iterator - One object can traverse all of the elements of another object.
Mediator - An object distributes communication between two or more objects.
Memento - One object stores another objects state.
Observer - An object notifies other object(s) if it changes.
State - An object appears to change its` class when the class it passes calls through to switches itself for a related class.
Strategy - An object controls which of a family of methods is called. Each method is in its` own class that extends a common base class.
Template - An abstract class defines various methods, and has one non-overridden method which calls the various methods.
Visitor - One or more related classes have the same method, which calls a method specific for themselves in another class.
Creational Patterns
Abstract Factory - Various methods to make various objects various ways.
Builder - Make and return one object various ways.
Factory Method – Methods to make and return components of one object various ways.
Prototype - Make new objects by cloning the objects which you set as prototypes.
Singleton - A class distributes the only instance of itself.
Structural Patterns
Adapter - A class extends another class and takes in an object, and makes the taken object behave like the extended class.
Bridge - An abstraction and implementation are in different class hierarchies.
Composite - Assemble groups of objects with the same signature.
Decorator - One class takes in another class, both of which extend the same abstract class, and adds functionality.
Façade - One class has a method that performs a complex process calling several other classes.
Flyweight - The reusable and variable parts of a class are broken into two classes to save resources.
Proxy - One class controls the creation of and access to objects in another class.
Behaviour Patterns
Chain of Responsibility - A method called in one class can move up a series to find an object that can properly execute the method.
Command - An object encapsulates everything needed to execute a method in another object.
Interpreter- Define a macro language and syntax, parsing input into objects which perform the correct opertaions.
Iterator - One object can traverse all of the elements of another object.
Mediator - An object distributes communication between two or more objects.
Memento - One object stores another objects state.
Observer - An object notifies other object(s) if it changes.
State - An object appears to change its` class when the class it passes calls through to switches itself for a related class.
Strategy - An object controls which of a family of methods is called. Each method is in its` own class that extends a common base class.
Template - An abstract class defines various methods, and has one non-overridden method which calls the various methods.
Visitor - One or more related classes have the same method, which calls a method specific for themselves in another class.
J2EE - FAQs
What is J2EE?
J2EE is an environment for developing and deploying enterprise applications.The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.
What is a Servlet?
A Servlet is a Java object that is based on Servlet framework and extends the functionality of a web server, being responsible for creating dynamic contents.
Which tier do Servlet and JSP components belong to?
Servlet and JSP are web tier components that run in a web tier container.
What roles do Servlet and JSP play?
• receive client requests (HTTP)
• perform business logic
• return responses to clients
What are the advantages of Servlet Technology?
• Abundant third-party tools and web servers support Servlet
• Access to an entire family of Java APIs
• Reliable, reusability, scalability
• Platform and server independent
• Secure
• Automatic reloading of Servlets
What is JSP Technology?
• Enables separation of business logic (Java Beans or custom tags) from presentation (HTML or XML/XSLT)
• Extensible via custom tags
• Builds on Servlet technology
What advantage does JSP have over Servlet technology? What is the downside to Servlet?
The downside to Servlet is that the presentation (HTML pages) has to be generated as part of the Servlet Java code, i.e. using printf statements, therefore whenever changes are made to the presentation, the Java code has to be changed and recompiled, redeployed. This in turn results in a maintenance problem of your application along with making web-page prototyping very difficult.
What is JSP page?
A text-based document capable of returning dynamic content to a client browser, which contains both Static (HTML, XML) and Dynamic content (programming code, JavaBeans, custom tags).
When to use Servlet over JSP?
• Extend the functionality of a Web server such as supporting a new file format
• Generate objects that do not contain HTML (graphics or charts)
• Avoid returning HTML directly from your Servlets whenever possible
Should I use Servlet or JSP?
In practice Servlets and JSP are used together via MVC (Model, View, Controller) architecture. Servlet handles Controller while JSP handles View. Servlet is good for controlling functionality while JSP is good for handling presentation logic.
What is a request?
Information that is sent from a client to a server. The information consists of (1) who made the request (2) user-entered data and (3) HTTP header entries.
What is a response?
Information that is sent to a client from a server. The information consists of static text (HTML, plain) or binary(image) data. It also contains HTTP response headers and cookies which are used to maintain session state.
What does the HTTP request contain?
It contains a header, a method(Get, Post, Put, Header) and request data.
What does the Get request contain?
User entered information is appended to the URL in a query string and can only send limited amount of data. i.e. ../servlet/ViewCourse?FirstName=Tom&LastName=Flewwelling
What does the Post request contain?
User entered information is sent as data (not appended to the URL). Any amount of data can be sent.
Servlet Interfaces and classes
List the interfaces and classes associated with Servlet.
Classes: HttpSession, GenericServlet, HttpServlet
Interfaces: Servlet, ServletRequest, HttpServletRequest, ServletResponse, HttpServletResponse
Servlet Life-Cycle
What controls the life cycle of a Servlet?
The container.
Explain the life cycle of a Servlet.
The init() gets called once a Servlet instance is created. The service() gets called every time there comes a new request. The service() calls doGet() and doPost() for incoming HTTP requests. Finally the destroy() is called to remove the Servlet instance.
What classes are Servlet defined in?
javax.servlet.GenericServlet or javax.servlet.HttpServlet.
Is the service() abstract? If so explain.
Yes, the service() is abstract and GenericServlet is thus abstract class. Therefore the service() of the GenericServlet class has to be implemented by a subclass – HTTPServlet class.
What role does the init() play?
Invoked once when the Servlet is instantiated and performs any set-up. i.e. Setting up a data base connection.
What role does the destroy() play?
Invoked before Servlet instance is removed and performs any clean up. i.e. Closing a database connection.
How are user entered parameters via the browser accessed?
They are accessed via getParameter().
How are init parameters via the web.xml deployment descriptor file accessed?
They are accessed via getInitParameter().
What kind of requests and responses does the service() receive?
It receives generic requests and responses. i.e. service(ServletRequest request, ServletResponse response).
What kind of requests and responses do the doGet() and doPost() receive?
They receive HTTP requests and responses. i.e. doGet(HTTPServletRequest request, HTTPServletResponse response), doPost(HTTPServletRequest request, HTTPServletResponse response).
Note: The doGet() and doPost() methods of HTTPServlet class are invoked from concrete implementation of service() method in the HTTPServlet class.
What are 5 things you want to do in doGet() and doPost() methods?
1.Extract client sent info such as user-entered parameter values that were sent as query string.
2.Set and get attributes to and from scope objects.
3.Perform some business logic or access the database.
4.Optionally include or forward your request to other web components.
5.Populate HTTP response message and then send it to client.
What are the typical steps to follow when creating a HTTP response?
1.Fill HTTP response headers with content type.
2.Set properties such as buffer size.
3.Get an output stream object from the response object and the write body contents to the output stream.
What are Scope Objects?
Scope Objects enable sharing information among collaborating web components (Servlet & JSP) via attributes(name/object pairs) maintained in Scope Objects.
What methods are used to access the attributes maintain in the Scope Objects?
getAttribute() & setAttribute()
Name 4 different types of Scope Objects: Class
Web context: Accessible from Web components within a Web context
Session: Accessible from Web components handling a request that belongs to the session
Request: Accessible from Web components handling the request
Page: Accessible from JSP page that creates the object
Web Context
How is a web context object represented?
A web context object is represented by ServletContext object. There is one ServletContext object per web application.
What is ServletContext used for?
It is used by servlets to:
• Set and get context-wide (application-wide) object-valued attributes
• Get request dispatcher
• Access Web content-wide initialization parameters set in the web.xml file
• Access Web resources associated with the Web context
• Log
• Access other misc. info
How do you access ServletContext object?
Call getServletContext() from within your servlet code and filter. Also, the ServletContext is located in ServletConfig object, which the Web server provides to a servlet when the servlet is initialized.
Session (Http Session)
Why is HTTPSession important?
It’s a mechanism employed to maintain client state across a series of requests from a same user over some period of time. i.e. Online shopping cart. Since HTTP is stateless, the HttpSession maintains client state in the form of attributes and the attributes remain in the session scope.
How do you get HTTPSession object in your Servlet code?
By an HTTPRequest object that is passed to your servlet object as an input parameter of Service() or getSession().
Servlet Request (HttpServletRequest)
What is a Servlet Request?
It contains data passed from client to server and implements ServletRequest.
How do you get client sent(user-entered) parameters?
By HTTP GET and HTTP POST.
HTTP GET: The name and value pairs of the parameters are sent as appendix to the URL.
HTTP POST: The name and value pairs of the parameters are sent as user data.
How to extract the values of the parameters?
getParameter() from the ServletRequest interface.
How are object/values attributes set?
The Servlet container itself can set attributes to make available custom information about a request. Or the Servlet set application-specific attribute. i.e. void setAttribute(java.lang.String name, java.lang.Object o)
How can Servlets get client information from the request?
String request.getRemoteAddr(); - get client’s IP address
String request.getRemoteHost(); - get client’s host name
How to obtain Server information?
String request.getServerName(); i.e. www.sun.com
int request.getServerPort(); i.e. Port number 8080
How to determine if the line is secure (if HTTPS)?
boolean isSecure()
HTTPServletRequest
What is HTTP Servlet Request?
It contains data passed from HTTP client to HTTP Servlet that is created by Servlet container and passed to Servlet as a parameter of doGet() or doPost().
What does a HTTP Request URL contain?
http://[host]:[port]/[request path]?[query string]
What do HTTP Request Headers do?
They Accept, Accept-Encoding and Authorize.
HTTPServletResponse
What is a Servlet Response?
It contains data passed from the Servlet to the client. And all Servlet responses implement ServletResponse Java Interface, which contains methods for retrieving an output stream, indicating content type, indicating whether to buffer output or not, for setting localization information.
Status Code in HTTPResponse
Why do we need HTTP response status code?
• To forward a client to another page.
• Indicate resources are missing.
• Instruct browser to use cached copy.
List some common Status Codes?
• 200(SC_OK) Success and documents follows – default for all Servlets.
• 204(SC_No_CONTENT) Success but no response body
• 301(SC_MOVED_PERMANENTLY) The document moved permanently (indicated in Location header)
Header in HTTPResponse
Why HTTP Response Headers?
To name a few:
• Give forwarding location
• Specify cookies
• Supply the page modification date
• Instruct the browser to reload the page after a designated interval
• Give the file size so that persistent HTTP connections can be used
• Designate the type of document being generated
Body in HTTPResponse
What are the key points to writing a response Reader?
A Servlet almost always return a response body which could be either a PrintWriter or a ServletOutputStream.
Overview
What are the 4 main J2EE application parts?
Client-tier components run on the client machine.
Web-tier components run on the J2EE server.
Business-tier components run on the J2EE server.
Enterprise information system (EIS)-tier software runs on the EIS server.
What do Enterprise JavaBeans components contain?
Enterprise JavaBeans components contains Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.
Are JavaBeans J2EE components?
No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
Is HTML page a web component?
No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
What can be considered as a web component?
J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
What is the container?
Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
What are container services?
A container is a runtime support of a system-level entity. Containers provide components with services such as:
lifecycle management
security
deployment
threading
What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a components deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.
What is the EAR file?
An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
What is JAXP?
JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.
What is Java Naming and Directory Service?
The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS.
What is Struts?
A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
<----------------------------------------EJB----------------------------------->
The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.
What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.
What are Struts?
The "Struts" framework tends to mainly focus on the web tier.
What is Spring Framework?
The Spring Framework tends to mainly focus on the Enterprise tier while providing support and integrating well with the Struts framework.
The "Struts" framework is no doubt a good framework to enhance the ability of the web tier, but the biggest drawback is the fact that it caters only to the web tier and leaves most of the Enterprise tier or middle tier to the fancy of the application architects. The Application architects need to provide an additional framework to deal with the enterprise tier and make sure that the new framework integrates well with the Struts framework. Spring tries to alleviate this problem by providing a comprehensive framework, which includes an MVC framework, an AOP integration framework, a JDBC integration framework, and an EJB integration framework
J2EE is an environment for developing and deploying enterprise applications.The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.
What is a Servlet?
A Servlet is a Java object that is based on Servlet framework and extends the functionality of a web server, being responsible for creating dynamic contents.
Which tier do Servlet and JSP components belong to?
Servlet and JSP are web tier components that run in a web tier container.
What roles do Servlet and JSP play?
• receive client requests (HTTP)
• perform business logic
• return responses to clients
What are the advantages of Servlet Technology?
• Abundant third-party tools and web servers support Servlet
• Access to an entire family of Java APIs
• Reliable, reusability, scalability
• Platform and server independent
• Secure
• Automatic reloading of Servlets
What is JSP Technology?
• Enables separation of business logic (Java Beans or custom tags) from presentation (HTML or XML/XSLT)
• Extensible via custom tags
• Builds on Servlet technology
What advantage does JSP have over Servlet technology? What is the downside to Servlet?
The downside to Servlet is that the presentation (HTML pages) has to be generated as part of the Servlet Java code, i.e. using printf statements, therefore whenever changes are made to the presentation, the Java code has to be changed and recompiled, redeployed. This in turn results in a maintenance problem of your application along with making web-page prototyping very difficult.
What is JSP page?
A text-based document capable of returning dynamic content to a client browser, which contains both Static (HTML, XML) and Dynamic content (programming code, JavaBeans, custom tags).
When to use Servlet over JSP?
• Extend the functionality of a Web server such as supporting a new file format
• Generate objects that do not contain HTML (graphics or charts)
• Avoid returning HTML directly from your Servlets whenever possible
Should I use Servlet or JSP?
In practice Servlets and JSP are used together via MVC (Model, View, Controller) architecture. Servlet handles Controller while JSP handles View. Servlet is good for controlling functionality while JSP is good for handling presentation logic.
What is a request?
Information that is sent from a client to a server. The information consists of (1) who made the request (2) user-entered data and (3) HTTP header entries.
What is a response?
Information that is sent to a client from a server. The information consists of static text (HTML, plain) or binary(image) data. It also contains HTTP response headers and cookies which are used to maintain session state.
What does the HTTP request contain?
It contains a header, a method(Get, Post, Put, Header) and request data.
What does the Get request contain?
User entered information is appended to the URL in a query string and can only send limited amount of data. i.e. ../servlet/ViewCourse?FirstName=Tom&LastName=Flewwelling
What does the Post request contain?
User entered information is sent as data (not appended to the URL). Any amount of data can be sent.
Servlet Interfaces and classes
List the interfaces and classes associated with Servlet.
Classes: HttpSession, GenericServlet, HttpServlet
Interfaces: Servlet, ServletRequest, HttpServletRequest, ServletResponse, HttpServletResponse
Servlet Life-Cycle
What controls the life cycle of a Servlet?
The container.
Explain the life cycle of a Servlet.
The init() gets called once a Servlet instance is created. The service() gets called every time there comes a new request. The service() calls doGet() and doPost() for incoming HTTP requests. Finally the destroy() is called to remove the Servlet instance.
What classes are Servlet defined in?
javax.servlet.GenericServlet or javax.servlet.HttpServlet.
Is the service() abstract? If so explain.
Yes, the service() is abstract and GenericServlet is thus abstract class. Therefore the service() of the GenericServlet class has to be implemented by a subclass – HTTPServlet class.
What role does the init() play?
Invoked once when the Servlet is instantiated and performs any set-up. i.e. Setting up a data base connection.
What role does the destroy() play?
Invoked before Servlet instance is removed and performs any clean up. i.e. Closing a database connection.
How are user entered parameters via the browser accessed?
They are accessed via getParameter().
How are init parameters via the web.xml deployment descriptor file accessed?
They are accessed via getInitParameter().
What kind of requests and responses does the service() receive?
It receives generic requests and responses. i.e. service(ServletRequest request, ServletResponse response).
What kind of requests and responses do the doGet() and doPost() receive?
They receive HTTP requests and responses. i.e. doGet(HTTPServletRequest request, HTTPServletResponse response), doPost(HTTPServletRequest request, HTTPServletResponse response).
Note: The doGet() and doPost() methods of HTTPServlet class are invoked from concrete implementation of service() method in the HTTPServlet class.
What are 5 things you want to do in doGet() and doPost() methods?
1.Extract client sent info such as user-entered parameter values that were sent as query string.
2.Set and get attributes to and from scope objects.
3.Perform some business logic or access the database.
4.Optionally include or forward your request to other web components.
5.Populate HTTP response message and then send it to client.
What are the typical steps to follow when creating a HTTP response?
1.Fill HTTP response headers with content type.
2.Set properties such as buffer size.
3.Get an output stream object from the response object and the write body contents to the output stream.
What are Scope Objects?
Scope Objects enable sharing information among collaborating web components (Servlet & JSP) via attributes(name/object pairs) maintained in Scope Objects.
What methods are used to access the attributes maintain in the Scope Objects?
getAttribute() & setAttribute()
Name 4 different types of Scope Objects: Class
Web context: Accessible from Web components within a Web context
Session: Accessible from Web components handling a request that belongs to the session
Request: Accessible from Web components handling the request
Page: Accessible from JSP page that creates the object
Web Context
How is a web context object represented?
A web context object is represented by ServletContext object. There is one ServletContext object per web application.
What is ServletContext used for?
It is used by servlets to:
• Set and get context-wide (application-wide) object-valued attributes
• Get request dispatcher
• Access Web content-wide initialization parameters set in the web.xml file
• Access Web resources associated with the Web context
• Log
• Access other misc. info
How do you access ServletContext object?
Call getServletContext() from within your servlet code and filter. Also, the ServletContext is located in ServletConfig object, which the Web server provides to a servlet when the servlet is initialized.
Session (Http Session)
Why is HTTPSession important?
It’s a mechanism employed to maintain client state across a series of requests from a same user over some period of time. i.e. Online shopping cart. Since HTTP is stateless, the HttpSession maintains client state in the form of attributes and the attributes remain in the session scope.
How do you get HTTPSession object in your Servlet code?
By an HTTPRequest object that is passed to your servlet object as an input parameter of Service() or getSession().
Servlet Request (HttpServletRequest)
What is a Servlet Request?
It contains data passed from client to server and implements ServletRequest.
How do you get client sent(user-entered) parameters?
By HTTP GET and HTTP POST.
HTTP GET: The name and value pairs of the parameters are sent as appendix to the URL.
HTTP POST: The name and value pairs of the parameters are sent as user data.
How to extract the values of the parameters?
getParameter() from the ServletRequest interface.
How are object/values attributes set?
The Servlet container itself can set attributes to make available custom information about a request. Or the Servlet set application-specific attribute. i.e. void setAttribute(java.lang.String name, java.lang.Object o)
How can Servlets get client information from the request?
String request.getRemoteAddr(); - get client’s IP address
String request.getRemoteHost(); - get client’s host name
How to obtain Server information?
String request.getServerName(); i.e. www.sun.com
int request.getServerPort(); i.e. Port number 8080
How to determine if the line is secure (if HTTPS)?
boolean isSecure()
HTTPServletRequest
What is HTTP Servlet Request?
It contains data passed from HTTP client to HTTP Servlet that is created by Servlet container and passed to Servlet as a parameter of doGet() or doPost().
What does a HTTP Request URL contain?
http://[host]:[port]/[request path]?[query string]
What do HTTP Request Headers do?
They Accept, Accept-Encoding and Authorize.
HTTPServletResponse
What is a Servlet Response?
It contains data passed from the Servlet to the client. And all Servlet responses implement ServletResponse Java Interface, which contains methods for retrieving an output stream, indicating content type, indicating whether to buffer output or not, for setting localization information.
Status Code in HTTPResponse
Why do we need HTTP response status code?
• To forward a client to another page.
• Indicate resources are missing.
• Instruct browser to use cached copy.
List some common Status Codes?
• 200(SC_OK) Success and documents follows – default for all Servlets.
• 204(SC_No_CONTENT) Success but no response body
• 301(SC_MOVED_PERMANENTLY) The document moved permanently (indicated in Location header)
Header in HTTPResponse
Why HTTP Response Headers?
To name a few:
• Give forwarding location
• Specify cookies
• Supply the page modification date
• Instruct the browser to reload the page after a designated interval
• Give the file size so that persistent HTTP connections can be used
• Designate the type of document being generated
Body in HTTPResponse
What are the key points to writing a response Reader?
A Servlet almost always return a response body which could be either a PrintWriter or a ServletOutputStream.
Overview
What are the 4 main J2EE application parts?
Client-tier components run on the client machine.
Web-tier components run on the J2EE server.
Business-tier components run on the J2EE server.
Enterprise information system (EIS)-tier software runs on the EIS server.
What do Enterprise JavaBeans components contain?
Enterprise JavaBeans components contains Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.
Are JavaBeans J2EE components?
No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
Is HTML page a web component?
No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
What can be considered as a web component?
J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
What is the container?
Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
What are container services?
A container is a runtime support of a system-level entity. Containers provide components with services such as:
lifecycle management
security
deployment
threading
What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a components deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.
What is the EAR file?
An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
What is JAXP?
JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.
What is Java Naming and Directory Service?
The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS.
What is Struts?
A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
<----------------------------------------EJB----------------------------------->
The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.
What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.
What are Struts?
The "Struts" framework tends to mainly focus on the web tier.
What is Spring Framework?
The Spring Framework tends to mainly focus on the Enterprise tier while providing support and integrating well with the Struts framework.
The "Struts" framework is no doubt a good framework to enhance the ability of the web tier, but the biggest drawback is the fact that it caters only to the web tier and leaves most of the Enterprise tier or middle tier to the fancy of the application architects. The Application architects need to provide an additional framework to deal with the enterprise tier and make sure that the new framework integrates well with the Struts framework. Spring tries to alleviate this problem by providing a comprehensive framework, which includes an MVC framework, an AOP integration framework, a JDBC integration framework, and an EJB integration framework
AWT and Swing FAQs
What does AWT stand for?
AWT stands for Abstract Window ToolKit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons.
Pointers regarding Swing.
•100% Java implementation of components
•Pluggable Look & Feel
•Lightweight components
•Uses Model View Control (MVC) Architecture
What is the difference between AWT and Swing?
AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, but Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.
What is a “heavyweight” component?
A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).
What is a “lightweight” component?
A lightweight component is one that “borrows” the native screen resources of an ancestor (which means it has no native resources of its own – peerless).
Just what is a button really?
It is simply a wrapper class inheriting from JComponent that holds the DefaultButtonModel object, some view data (such as the button label and icons), and a BasicButtonUI object that is responsible for the button views.
Why won’t the JVM terminate when all application windows are closed?
The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit() to terminate the JVM.
Which Swing methods are thread-safe?
The only thread-safe methods are repaint(), revalidate(), and invalidate().
What class is at the top of the AWT event hierarchy?
java.awt.AWTEvent.
What does “heavy weight components” mean?
Heavy weight components like Abstract Window Toolkit (AWT) depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component.
Name the container classes which use Border Layout as their default layout?
Window, Frame and Dialog classes.
Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, and ScrollPane.
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.
Which package has light weight components?
javax.Swing package contains light weight components. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
What is JFC?
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.
What is an event?
Changing the state of an object is an event.
What is an Event Handler?
An Event Handler is part of a program which tells the program how to act in response to a specific event.
What is a layout manager?
A layout manager is an object used to organize components in a container.
Which container classes use BorderLayout manager as their default layout?
Window, Frame and Dialog classes.
Which container classes use FlowLayout manager as their default layout?
Panel and Applet classes.
What method of the Container class is used to set the position and size of the component?
The setBounds() method.
What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout. For example, setLayout(new FlowLayout()); will set the layout as FlowLayout.
How are the elements of different layouts organized?
A layout manager is an object that is used to organize components in a container. The different layouts available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements may be different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
Which Container method is used to cause a container to be laid out and redisplayed?
validate()
Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is just a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
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.
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.
What are peerless components?
The peerless components are called light-weight components.
What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular component. 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.
AWT stands for Abstract Window ToolKit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons.
Pointers regarding Swing.
•100% Java implementation of components
•Pluggable Look & Feel
•Lightweight components
•Uses Model View Control (MVC) Architecture
What is the difference between AWT and Swing?
AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, but Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.
What is a “heavyweight” component?
A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).
What is a “lightweight” component?
A lightweight component is one that “borrows” the native screen resources of an ancestor (which means it has no native resources of its own – peerless).
Just what is a button really?
It is simply a wrapper class inheriting from JComponent that holds the DefaultButtonModel object, some view data (such as the button label and icons), and a BasicButtonUI object that is responsible for the button views.
Why won’t the JVM terminate when all application windows are closed?
The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit() to terminate the JVM.
Which Swing methods are thread-safe?
The only thread-safe methods are repaint(), revalidate(), and invalidate().
What class is at the top of the AWT event hierarchy?
java.awt.AWTEvent.
What does “heavy weight components” mean?
Heavy weight components like Abstract Window Toolkit (AWT) depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component.
Name the container classes which use Border Layout as their default layout?
Window, Frame and Dialog classes.
Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, and ScrollPane.
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.
Which package has light weight components?
javax.Swing package contains light weight components. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
What is JFC?
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.
What is an event?
Changing the state of an object is an event.
What is an Event Handler?
An Event Handler is part of a program which tells the program how to act in response to a specific event.
What is a layout manager?
A layout manager is an object used to organize components in a container.
Which container classes use BorderLayout manager as their default layout?
Window, Frame and Dialog classes.
Which container classes use FlowLayout manager as their default layout?
Panel and Applet classes.
What method of the Container class is used to set the position and size of the component?
The setBounds() method.
What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout. For example, setLayout(new FlowLayout()); will set the layout as FlowLayout.
How are the elements of different layouts organized?
A layout manager is an object that is used to organize components in a container. The different layouts available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements may be different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
Which Container method is used to cause a container to be laid out and redisplayed?
validate()
Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is just a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
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.
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.
What are peerless components?
The peerless components are called light-weight components.
What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular component. 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.
Java Threads FAQs
What is a thread?
A thread is a program’s path of execution.
What is the difference between process and thread?
A thread is a separate path of execution in a program. A Process is a program in execution.
What is a daemon thread?
A thread that works in the background to support the runtime environment is called a daemon thread. For example, the clock handler thread is a daemon thread.
Explain different ways of implementing threads?
Two ways of implementing threads are implementing Runnable interface or by inheriting from Thread class.
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.
What invokes a thread's run() method?
After a thread is started, via its start() of the Thread class, the JVM invokes the thread's run() when the thread is initially executed.
What are the high-level thread states?
The high-level thread states are ready, running, waiting and dead.
What is deadlock?
When two threads are waiting for each other and can’t proceed until the first thread obtains a lock on the other thread or vice versa, the program is said to be in a deadlock.
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 thread inter-communication.
What are some ways in which a thread can enter the waiting state?
1.By invoking sleep()
2.By blocking on I/O
3.By unsuccessfully attempting to acquire an object’s lock
4.By invoking an object’s wait() method
5.By invoking its suspend()
What is the difference between yielding and sleeping?
When a task invokes its yield(), it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep(), it returns to the waiting state from a running state.
What state does a thread enter when it terminates its processing?
A thread enters the dead state, when it terminates its processing.
Is there a separate stack for each thread in Java?
Yes, every thread maintains its own separate stack, called RuntimeStack, however they share the same memory.
What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}
what is a transient variable?
A transient variable is a variable that may not be serialized. Transient instance fields are neither saved nor restored by the standard serialisation mechanism. You have to handle restoring them yourself.
A thread is a program’s path of execution.
What is the difference between process and thread?
A thread is a separate path of execution in a program. A Process is a program in execution.
What is a daemon thread?
A thread that works in the background to support the runtime environment is called a daemon thread. For example, the clock handler thread is a daemon thread.
Explain different ways of implementing threads?
Two ways of implementing threads are implementing Runnable interface or by inheriting from Thread class.
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.
What invokes a thread's run() method?
After a thread is started, via its start() of the Thread class, the JVM invokes the thread's run() when the thread is initially executed.
What are the high-level thread states?
The high-level thread states are ready, running, waiting and dead.
What is deadlock?
When two threads are waiting for each other and can’t proceed until the first thread obtains a lock on the other thread or vice versa, the program is said to be in a deadlock.
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 thread inter-communication.
What are some ways in which a thread can enter the waiting state?
1.By invoking sleep()
2.By blocking on I/O
3.By unsuccessfully attempting to acquire an object’s lock
4.By invoking an object’s wait() method
5.By invoking its suspend()
What is the difference between yielding and sleeping?
When a task invokes its yield(), it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep(), it returns to the waiting state from a running state.
What state does a thread enter when it terminates its processing?
A thread enters the dead state, when it terminates its processing.
Is there a separate stack for each thread in Java?
Yes, every thread maintains its own separate stack, called RuntimeStack, however they share the same memory.
What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}
what is a transient variable?
A transient variable is a variable that may not be serialized. Transient instance fields are neither saved nor restored by the standard serialisation mechanism. You have to handle restoring them yourself.
Java Basics FAQs
What is Byte Code?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.
Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file) and Interpreter reads byte codes.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why?
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
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, i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory. “==” compares references while .equals compares contents.
What does it mean that a class or member is final?
Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be sub-classed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited.
Why are there no global variables in Java?
Global variables break the referential transparency and global variables create collisions in namespace.
Explain the keyword “static”.
Java does not support global variables. Every variable in Java must be declared within a class. However, Java uses the “static” keyword to indicate that a particular variable is a class variable rather than an instance variable. What this means is that there will be only one copy of the variable for the class rather than one for each instance of the class. It will, in effect, be global within that class. There will be one and only one copy of a class variable no matter how many instances of the class are created. When declared static a variable belongs to the class as a whole and not to any instantiated object in particular. You can also "reach" this variable from anywhere in the program.
How to convert a String to a Number in java?
valueOf() function of Integer class is used to convert String to Number.
For example,
int i = Integer.parseInt("75");
or using a wrapper
Integer i = Integer.valueOf("75");
Name eight primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.
How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:
int a=5, b=10; a=a+b; b=a-b; a=a-b;
Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
What's the main difference between a Vector and an ArrayList?
Java Vector class is internally synchronized and ArrayList is not synchronized.
Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper:
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void
Explain the usage of the keyword transient?
Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
Can an inner class declared inside of a method access local variables of this method?
It's possible if these variables are final.
How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This is how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.
If you're overriding the method equals() of an object, which other method might you also consider?
hashCode()
What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
There are two classes: A and B. The class B needs to inform class A when some important event occurs. What Java technique would you use to implement it?
If these classes are threads, I'd consider notify() or notifyAll(). For regular classes you can use the Observer Interface.
Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
Read the following program:
public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}
What is the result?
A. The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: C
Does Java pass-by-reference or pass-by-value?
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
What is the difference between private, protected, and public?
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults
Consider the code below:
public static void main( String args[] )
{ int a = 5;
System.out.println( cube( a ) );
}
int cube( int theNum )
{
return theNum * theNum * theNum;
}
What will happen when you attempt to compile and run this code?
It will not compile because cube is not static.
Describe the differences between the following keywords:
1. final
2. finalize
3. finally
1. final - should be used when a variable must remain constant or unchanged, which helps the compiler generate faster code.
2. finalize – called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
3. finally – is part of try, catch blocks, which is used to ensure that critical code gets executed even if an exception is thrown.
Explain the difference between StringBuilder and StringBuffer?
They are both mutable however; a StringBuilder is not synchronized whereas a StringBuffer is. A StringBuffer is said to be a mutable, thread-safe sequence of characters. Furthermore it’s like a String but can be modified.
Explain “serialization” in Java.
Quite simply, object serialization provides a program the ability to read or write whole objects to and from a raw byte stream.
What's the advantage of Serializable?
It allows you to read and write entire Java objects into streams, which greatly simplifies the process of objects exchange. The real power of serialization is the ability of Java programs to easily read and write entire objects and primitive data types, without converting to/from raw bytes or parsing clumsy text data. Anyone who has taken a modern programming class taught in a programming language such as Pascal or one of the C derivatives, has surely had the opportunity to do I/O on a text file for the purpose of storing and loading data. Parsing these files always seems to reduce to a basic set of hurdles that you must get over: Did I reach the EOF marker? Is the file pointer on top of the integer or the string? What happens when I reach the EOLN mark, and what if the marker is missing? Now consider a situation where a programming language suddenly made these problems go away? Object serialization has taken a step in the direction of being able to store objects instead of reading and writing their state in some foreign and possibly unfriendly format.
How to Make a Class Serializable?
To make a class serializable, just declare that this class implements the interface Serializable:
class Employee implements java.io.Serializable {
String lName;
String fName;
double salary;
String address;
}
How to Serialize an Object?
To serialize an object means to convert it into a set of bytes and send it to a stream. To deserialize an object means to read these bytes from a stream and recreate the instance of the received object.
To serialize an object into a stream perform the following actions:
• Open one of the output streams, for example FileOutputStream
• Chain it with the ObjectOutputStream
• Call the method writeObject() providing the instance of a Serializable object as an argument.
• Close the streams
The following example performs all these steps and creates a snapshot of the object Employee in the file called NewEmployee.ser
import java.io.*;
import java.util.Date;
public class HeadQuarterEmpProcessor {
public static void main(String[] args) {
Employee emp = new Employee();
emp.lName = "John";
emp.fName = "Smith";
emp.salary = 50000;
emp.address = "12 main street";
emp.hireDate = new Date();
FileOutputStream fOut=null;
ObjectOutputStream oOut=null;
try{
fOut= new FileOutputStream("c:\\NewEmployee.ser");
oOut = new ObjectOutputStream(fOut);
oOut.writeObject(emp); //serializing employee
System.out.println(
"An employee is serialized into c:\\NewEmployee.ser");
}catch(IOException e){
e.printStackTrace();
}finally{
try {
oOut.flush();
oOut.close();
fOut.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
What if you prefer not to serialize certain information?
If you do not want to serialize sensitive information such as salary, declare this variable using the keyword transient: transient double salary;
The values of static and transient member variables are not serialized.
What are widgets?
Widgets are the building blocks of java user interfaces.
What is a Marker Interface?
An interface with no methods. Example: Serializable, Remote, Cloneable.
What interface performs sorting?
Comparable
Why are Interfaces so importance?
Interfaces are well suited for classes, which vary in functionality but with the same method signatures.
Explain RMI and How it is useful?
RMI is a remote method invocation. Using RMI, you can work with remote objects. The function calls are as though you are invoking a local variable. So it gives you an impression that you are working really with an object that resides within your own JVM although it is somewhere else.
What’s the main use of preparedstatement?
Preparedstatements are precompiled statements. They are mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk processing.
What threads will start, when you start a java program?
Finalizer, Main, Reference Handler, Signal Dispatcher.
If I write return at the end of the try block, will the finally block still execute?
Yes, even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then control resumes.
If I write System.exit(0); at the end of the try block, will the finally block still execute?
No, in this case the finally block will not execute because when System.exit(0); is executed, control immediately goes out of the program, and thus finally never executes.
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.
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.
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 super class constructor.
Explain different ways of using threads?
Threads can be implemented two ways, by using runnable interface or by inheriting from the Thread class. The former is more advantageous because it supports multiple inheritance - in a certain way.
What is the common usage of serialization?
Whenever an object is to be sent over the network, it needs to be serialized. Moreover if the state of an object is to be saved, objects need to be serialized by converting them to a byte stream.
What are wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types.
What is the default value of an object reference declared as an instance variable?
null, unless we define it explicitly.
What is the difference between an argument and a parameter?
While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.
What are different types of access modifiers?
public: Any thing declared as public can be accessed from anywhere.
private: Any thing declared as private can’t be seen outside of its class.
protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.
default modifier: Can be accessed only to classes in the same package.
What is UNICODE?
Unicode is used for internal representation of characters and strings that use 16bits to represent each other.
What is method overloading and method overriding?
Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.
Method overriding : When a method in a class having the same method name with same arguments, is said to be method overriding.
What is the difference between Assignment and Initialization?
Assignment can be done as many times as desired whereas initialization can be done only once.
What is casting?
Casting is used to convert the value of one type to another.
What is the difference between Integer and int?
a) Integer is a class defined in the java.lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
What is synchronization?
Synchronization is the mechanism that ensures that only one thread can access resources at one time.
When should you synchronize a piece of your code?
When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
What is an applet?
An Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.
What is the lifecycle of an applet?
init() method - Can be called when an applet is first loaded
start() method - Can be called each time an applet is started.
paint() method - Can be called when the applet is minimized or maximized.
stop() method - Can be used when the browser moves off the applet’s page.
destroy() method - Can be called when the browser is finished with the applet.
How do you set security in applets?
using the setSecurityManager() method.
What is the difference between set and list?
Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
What is serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
What is JDBC?
JDBC is a set of Java API methods for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.
What is a stored procedure?
Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
What is the difference between an applet and a servlet?
a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
What is the difference between doPost and doGet methods?
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.
What is the life cycle of a servlet?
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 requests through service() method. c) The server removes the servlet through destroy() method.
What loads the init() method of servlet?
Web server.
Is it possible to call servlet with parameters in the URL?
Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
What is Servlet chaining?
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.
How do servlets handle multiple simultaneous requests?
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.
What is Domain Naming Service(DNS)?
It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.
What is a Jar file?
A Jar file allows to efficiently deploy a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java.util. zip contains classes that read and write jar files.
How can I set a cookie in JSP?
response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>
How can I delete a cookie with JSP?
Say that I have a cookie called “foo, ” that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie(”foo”, null); KillCookie. setPath(”/”); killCookie. setMaxAge(0); response. addCookie(killCookie); %>
What happens if you don’t initialize an instance variable of any of the primitive types in Java?
The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references.
Can a .java file contain more than one java class?
Yes, a .java file can contain more than one java class, provided at most, that one of them is declared as public class.
Is String a primitive data type in Java?
No, String is not a primitive data type in Java, it’s an object. They are instances of the String class defined in java.lang.package.
What are the different scopes for Java variables?
The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.
1. Instance: - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object is accessible.
2. Local: - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.
What is the default value of local variables?
Local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain about the local variable not being initialized.
How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.
Can main method be declared final?
Yes, the main method can be declared final, in addition to being public static.
What will be the output of the following statement?
System.out.println ("1" + 3);
It will print 13.
What will be the default values, of all the elements of an array, defined as an instance variable?
If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.
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.
What must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implements the Runnable interface.
What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in).
What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in an interface.
What is one alternative to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
Also incorporating Interfaces into your design will allow for multiple inheritance.
What is implied when a method or field is “static”?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Also, Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.
What is the difference between pre-emptive 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.
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.
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.
Can applets communicate with each other?
At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.
Does Java provide any construct to find out the size of an object?
No, there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.
What are checked exceptions?
Checked exceptions are those which the Java complier forces the client programmer to check. e.g. IOEXceptions are checked exceptions.
What are runtime exceptions or unchecked exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. Unchecked exceptions are Runtime exceptions and all its subclasses.
If I want an object of my class to be thrown as an exception object, what should I do?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
Does importing a package import the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No, you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access. If a top level class is declared private, the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private nor protected.
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the
serialization process by implementing these methods.
What happens to static fields of a class during serialization?
There are three exceptions in which serialization does not necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular state.
2. Base class fields are only handled if the base class itself is Serializable.
3. Transient fields.
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
What are the differences between a Checked exception and an unchecked exception?
A checked exception is any subclass of Exception (or Exception itself), excluding RuntimeException and its subclasses.
Checked exceptions forces the client programmer to deal with the possibility that the exception will be thrown at compile time.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses are also unchecked.
Unchecked exceptions do not caught at compile time. In fact, client programmers may not even know that the exception could be thrown. eg,StringIndexOutOfBoundsException thrown by String's charAt() method.
Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be, as they tend to be unrecoverable.
Name two types of EJBs?
Enterprise JavaBeans server-side components come in two fundamentally different types: entity beans and session beans.
Basically entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory. Thus entity beans model real-world objects. These objects are usually persistent records in some kind of database.
Session beans are for managing processes or tasks. A session bean is mainly for coordinating particular kinds of activities. That is, session beans are plain remote objects meant for abstracting business logic. The activity that a session bean represents is fundamentally transient. A session bean does not represent anything in a database, but it can access the database.
Thus an entity bean has persistent state whereas a session bean models interactions but does not have persistent state.
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.
Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file) and Interpreter reads byte codes.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why?
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
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, i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory. “==” compares references while .equals compares contents.
What does it mean that a class or member is final?
Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be sub-classed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited.
Why are there no global variables in Java?
Global variables break the referential transparency and global variables create collisions in namespace.
Explain the keyword “static”.
Java does not support global variables. Every variable in Java must be declared within a class. However, Java uses the “static” keyword to indicate that a particular variable is a class variable rather than an instance variable. What this means is that there will be only one copy of the variable for the class rather than one for each instance of the class. It will, in effect, be global within that class. There will be one and only one copy of a class variable no matter how many instances of the class are created. When declared static a variable belongs to the class as a whole and not to any instantiated object in particular. You can also "reach" this variable from anywhere in the program.
How to convert a String to a Number in java?
valueOf() function of Integer class is used to convert String to Number.
For example,
int i = Integer.parseInt("75");
or using a wrapper
Integer i = Integer.valueOf("75");
Name eight primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.
How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:
int a=5, b=10; a=a+b; b=a-b; a=a-b;
Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
What's the main difference between a Vector and an ArrayList?
Java Vector class is internally synchronized and ArrayList is not synchronized.
Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper:
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void
Explain the usage of the keyword transient?
Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
Can an inner class declared inside of a method access local variables of this method?
It's possible if these variables are final.
How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This is how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.
If you're overriding the method equals() of an object, which other method might you also consider?
hashCode()
What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
There are two classes: A and B. The class B needs to inform class A when some important event occurs. What Java technique would you use to implement it?
If these classes are threads, I'd consider notify() or notifyAll(). For regular classes you can use the Observer Interface.
Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
Read the following program:
public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}
What is the result?
A. The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: C
Does Java pass-by-reference or pass-by-value?
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
What is the difference between private, protected, and public?
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults
Consider the code below:
public static void main( String args[] )
{ int a = 5;
System.out.println( cube( a ) );
}
int cube( int theNum )
{
return theNum * theNum * theNum;
}
What will happen when you attempt to compile and run this code?
It will not compile because cube is not static.
Describe the differences between the following keywords:
1. final
2. finalize
3. finally
1. final - should be used when a variable must remain constant or unchanged, which helps the compiler generate faster code.
2. finalize – called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
3. finally – is part of try, catch blocks, which is used to ensure that critical code gets executed even if an exception is thrown.
Explain the difference between StringBuilder and StringBuffer?
They are both mutable however; a StringBuilder is not synchronized whereas a StringBuffer is. A StringBuffer is said to be a mutable, thread-safe sequence of characters. Furthermore it’s like a String but can be modified.
Explain “serialization” in Java.
Quite simply, object serialization provides a program the ability to read or write whole objects to and from a raw byte stream.
What's the advantage of Serializable?
It allows you to read and write entire Java objects into streams, which greatly simplifies the process of objects exchange. The real power of serialization is the ability of Java programs to easily read and write entire objects and primitive data types, without converting to/from raw bytes or parsing clumsy text data. Anyone who has taken a modern programming class taught in a programming language such as Pascal or one of the C derivatives, has surely had the opportunity to do I/O on a text file for the purpose of storing and loading data. Parsing these files always seems to reduce to a basic set of hurdles that you must get over: Did I reach the EOF marker? Is the file pointer on top of the integer or the string? What happens when I reach the EOLN mark, and what if the marker is missing? Now consider a situation where a programming language suddenly made these problems go away? Object serialization has taken a step in the direction of being able to store objects instead of reading and writing their state in some foreign and possibly unfriendly format.
How to Make a Class Serializable?
To make a class serializable, just declare that this class implements the interface Serializable:
class Employee implements java.io.Serializable {
String lName;
String fName;
double salary;
String address;
}
How to Serialize an Object?
To serialize an object means to convert it into a set of bytes and send it to a stream. To deserialize an object means to read these bytes from a stream and recreate the instance of the received object.
To serialize an object into a stream perform the following actions:
• Open one of the output streams, for example FileOutputStream
• Chain it with the ObjectOutputStream
• Call the method writeObject() providing the instance of a Serializable object as an argument.
• Close the streams
The following example performs all these steps and creates a snapshot of the object Employee in the file called NewEmployee.ser
import java.io.*;
import java.util.Date;
public class HeadQuarterEmpProcessor {
public static void main(String[] args) {
Employee emp = new Employee();
emp.lName = "John";
emp.fName = "Smith";
emp.salary = 50000;
emp.address = "12 main street";
emp.hireDate = new Date();
FileOutputStream fOut=null;
ObjectOutputStream oOut=null;
try{
fOut= new FileOutputStream("c:\\NewEmployee.ser");
oOut = new ObjectOutputStream(fOut);
oOut.writeObject(emp); //serializing employee
System.out.println(
"An employee is serialized into c:\\NewEmployee.ser");
}catch(IOException e){
e.printStackTrace();
}finally{
try {
oOut.flush();
oOut.close();
fOut.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
What if you prefer not to serialize certain information?
If you do not want to serialize sensitive information such as salary, declare this variable using the keyword transient: transient double salary;
The values of static and transient member variables are not serialized.
What are widgets?
Widgets are the building blocks of java user interfaces.
What is a Marker Interface?
An interface with no methods. Example: Serializable, Remote, Cloneable.
What interface performs sorting?
Comparable
Why are Interfaces so importance?
Interfaces are well suited for classes, which vary in functionality but with the same method signatures.
Explain RMI and How it is useful?
RMI is a remote method invocation. Using RMI, you can work with remote objects. The function calls are as though you are invoking a local variable. So it gives you an impression that you are working really with an object that resides within your own JVM although it is somewhere else.
What’s the main use of preparedstatement?
Preparedstatements are precompiled statements. They are mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk processing.
What threads will start, when you start a java program?
Finalizer, Main, Reference Handler, Signal Dispatcher.
If I write return at the end of the try block, will the finally block still execute?
Yes, even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then control resumes.
If I write System.exit(0); at the end of the try block, will the finally block still execute?
No, in this case the finally block will not execute because when System.exit(0); is executed, control immediately goes out of the program, and thus finally never executes.
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.
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.
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 super class constructor.
Explain different ways of using threads?
Threads can be implemented two ways, by using runnable interface or by inheriting from the Thread class. The former is more advantageous because it supports multiple inheritance - in a certain way.
What is the common usage of serialization?
Whenever an object is to be sent over the network, it needs to be serialized. Moreover if the state of an object is to be saved, objects need to be serialized by converting them to a byte stream.
What are wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types.
What is the default value of an object reference declared as an instance variable?
null, unless we define it explicitly.
What is the difference between an argument and a parameter?
While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.
What are different types of access modifiers?
public: Any thing declared as public can be accessed from anywhere.
private: Any thing declared as private can’t be seen outside of its class.
protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.
default modifier: Can be accessed only to classes in the same package.
What is UNICODE?
Unicode is used for internal representation of characters and strings that use 16bits to represent each other.
What is method overloading and method overriding?
Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.
Method overriding : When a method in a class having the same method name with same arguments, is said to be method overriding.
What is the difference between Assignment and Initialization?
Assignment can be done as many times as desired whereas initialization can be done only once.
What is casting?
Casting is used to convert the value of one type to another.
What is the difference between Integer and int?
a) Integer is a class defined in the java.lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
What is synchronization?
Synchronization is the mechanism that ensures that only one thread can access resources at one time.
When should you synchronize a piece of your code?
When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
What is an applet?
An Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.
What is the lifecycle of an applet?
init() method - Can be called when an applet is first loaded
start() method - Can be called each time an applet is started.
paint() method - Can be called when the applet is minimized or maximized.
stop() method - Can be used when the browser moves off the applet’s page.
destroy() method - Can be called when the browser is finished with the applet.
How do you set security in applets?
using the setSecurityManager() method.
What is the difference between set and list?
Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
What is serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
What is JDBC?
JDBC is a set of Java API methods for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.
What is a stored procedure?
Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
What is the difference between an applet and a servlet?
a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
What is the difference between doPost and doGet methods?
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.
What is the life cycle of a servlet?
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 requests through service() method. c) The server removes the servlet through destroy() method.
What loads the init() method of servlet?
Web server.
Is it possible to call servlet with parameters in the URL?
Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
What is Servlet chaining?
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.
How do servlets handle multiple simultaneous requests?
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.
What is Domain Naming Service(DNS)?
It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.
What is a Jar file?
A Jar file allows to efficiently deploy a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java.util. zip contains classes that read and write jar files.
How can I set a cookie in JSP?
response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>
How can I delete a cookie with JSP?
Say that I have a cookie called “foo, ” that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie(”foo”, null); KillCookie. setPath(”/”); killCookie. setMaxAge(0); response. addCookie(killCookie); %>
What happens if you don’t initialize an instance variable of any of the primitive types in Java?
The object references are all initialized to null in Java. However in order to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references.
Can a .java file contain more than one java class?
Yes, a .java file can contain more than one java class, provided at most, that one of them is declared as public class.
Is String a primitive data type in Java?
No, String is not a primitive data type in Java, it’s an object. They are instances of the String class defined in java.lang.package.
What are the different scopes for Java variables?
The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.
1. Instance: - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object is accessible.
2. Local: - These are the variables that are defined within a method. They remain accessbile only during the course of method excecution. When the method finishes execution, these variables fall out of scope.
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.
What is the default value of local variables?
Local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain about the local variable not being initialized.
How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.
Can main method be declared final?
Yes, the main method can be declared final, in addition to being public static.
What will be the output of the following statement?
System.out.println ("1" + 3);
It will print 13.
What will be the default values, of all the elements of an array, defined as an instance variable?
If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is an array of references (of any type), all the elements will be initialized to null.
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.
What must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implements the Runnable interface.
What is Externalizable?
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in).
What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in an interface.
What is one alternative to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
Also incorporating Interfaces into your design will allow for multiple inheritance.
What is implied when a method or field is “static”?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Also, Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.
What is the difference between pre-emptive 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.
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.
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.
Can applets communicate with each other?
At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.
Does Java provide any construct to find out the size of an object?
No, there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.
What are checked exceptions?
Checked exceptions are those which the Java complier forces the client programmer to check. e.g. IOEXceptions are checked exceptions.
What are runtime exceptions or unchecked exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. Unchecked exceptions are Runtime exceptions and all its subclasses.
If I want an object of my class to be thrown as an exception object, what should I do?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
Does importing a package import the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No, you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access. If a top level class is declared private, the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private nor protected.
How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the
serialization process by implementing these methods.
What happens to static fields of a class during serialization?
There are three exceptions in which serialization does not necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular state.
2. Base class fields are only handled if the base class itself is Serializable.
3. Transient fields.
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
What are the differences between a Checked exception and an unchecked exception?
A checked exception is any subclass of Exception (or Exception itself), excluding RuntimeException and its subclasses.
Checked exceptions forces the client programmer to deal with the possibility that the exception will be thrown at compile time.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses are also unchecked.
Unchecked exceptions do not caught at compile time. In fact, client programmers may not even know that the exception could be thrown. eg,StringIndexOutOfBoundsException thrown by String's charAt() method.
Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be, as they tend to be unrecoverable.
Name two types of EJBs?
Enterprise JavaBeans server-side components come in two fundamentally different types: entity beans and session beans.
Basically entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory. Thus entity beans model real-world objects. These objects are usually persistent records in some kind of database.
Session beans are for managing processes or tasks. A session bean is mainly for coordinating particular kinds of activities. That is, session beans are plain remote objects meant for abstracting business logic. The activity that a session bean represents is fundamentally transient. A session bean does not represent anything in a database, but it can access the database.
Thus an entity bean has persistent state whereas a session bean models interactions but does not have persistent state.
Object Oriented Programming FAQs
What is an object?
An object is a package that contains related data and instructions. The data relates to what the object represents, while the instructions define how this object relates to other objects and itself.
What is a class?
A class is an encapsulation of data members and functions that manipulate the data.
What is an instance?
An individual object that is a member of a class.
What is a constructor?
Constructors are methods defined in a class that are invoked automatically when an object is created. They are used to initialize a newly allocated object.
What is a default ctor?
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
What is a copy ctor?
Copy constructors are used to make a copy of one class object from another class object of the same class type.
What is a macro?
It is a pattern that specifies how a certain input sequence should be mapped to an output sequence. C++ supports macros although, Java does not.
What are the advantages/disadvantages of using inline and const?
The advantages of inline functions are that they are quick and the disadvantages of inline functions are that they get complied every time the function is called and affects the file size.
What are pass by reference and pass by value?
Pass by reference means passing the address rather than the value. Pass by value means passing a copy of the value.
What does it mean to take the address of a reference?
A reference is an alias or an alternative name for an object. All operations applied to a reference act on the object to which the reference refers. The address of a reference is the address of the aliased object. Passing an object by reference enables the function to change the object being referred to without creating a copy of the object within the scope of the function. Only the address of the actual original object is put on the stack, not the entire object.
What does it mean to declare a function or variable as static?
It simply means that once the variable has been initialized, it remains in memory until the end of the program. Static member functions can only access static members.
What is a pure virtual function?
It doesn’t contain a body and it acts as an interface. A class that has at least one pure virtual function is automatically called an abstract class.
What are wrapper classes?
Wrapper classes allow primitive types to be accessed as objects. The wrapper class is wrapped around the primitive data type.
Explain what happens when an exception is thrown.
It depends on whether or not we have any code that catches the exception.
What happens if an exception is not caught?
An uncaught exception would cause the program to terminate.
What are the costs and benefits of using exceptions?
Advantages: Exception handling increases the programs reliability. Programs doe not crash.
Disadvantages: You must enable exception handling in the complier and there is overhead associated with it. – the expense of overhead.
What is an iterator?
An iterator is similar to a pointer. It accesses elements of a container class.
What is multi-tiered application architecture?
Multi-tiered application architecture involves client/server computing.
What are the main features of OO programming? Explain.
Data Abstraction represents essential features without including the background details or explanations. It refers to language features that allow you to create new, User Defined Types (UDTs).
PIE
Polymorphism: Helps decouple the “what” from the “how”. This is done by virtual functions. It allows you to treat derived class members just like their base class members. For example, Animal->Speak->Dog->Pig. If speak is invoked, a dog will bark and a pig will oink.
Inheritance: The ability to construct one class from another. A derived class is a completely new class that inherits attributes and behaviors (all the data and member functions) of its base class. The derived class is usually more specialized version of the base class. Inheritance provides reusability. Also, Inheritance is unidirectional. i.e. A car is a vehicle however, a vehicle is not necessarily a car.
Encapsulation or Information Hiding: Allows you to hide the details of a class from objects that communicate with it.
Can you explain an “is a” (Inheritance) relationship and a “has a” (Composition) relationship?
They both allow you to place sub-objects inside your new class. They are two of the main techniques for code reuse. For example,
- a car is a vehicle
- a car has an engine
Composition simply means using instance variables that refer to other objects. The class Vehicle will have an instance variable which refers to the Car object.
What is the difference between the stack and the heap?
The difference between the stack and the heap is that the stack gets allocated at compile-time while the heap gets allocated at run-time.
What are the main differences between Object Oriented Programming and Procedural Programming?
1.OOP enables the programmer to create programs (modules) that do not need to be changed when a new object is added.
2.A programmer can create a new object that inherits many of its features from existing objects.
PP consists of data structures and subroutines.
OOP consists of objects and allows mapping of a database model to their own classes.
How does Object Oriented Programming improve software development?
Code reusability and the ability to map real world things to objects.
What is final?
A final class can’t be extended. i.e, a final class may not be sub-classed. A final method cannot be overridden when its class is inherited. You can’t change the value of a final variable.
What two general classes that software can be divide into?
Software can be divided into two general classes: systems software and applications software. Systems software consists of low-level programs that interact with the computer at a very basic level. This includes operating systems, compilers, and utilities for managing computer resources.
In contrast, applications software (also called end-user programs) includes database programs, word processors, and spreadsheets. Figuratively speaking, applications software sits on top of systems software because it is unable to run without the operating system and system utilities.
What is an application?
A program or group of programs designed for end users.
What is a State Diagram?
Relates events and states. When an event is received, the next state depends on the current state as well as the event. A state Diagram gives insight to the flow of an object in a system, and the effect it can have when an event occurs.
What is UML?
It represents the blueprints in which the language is written in.
An object is a package that contains related data and instructions. The data relates to what the object represents, while the instructions define how this object relates to other objects and itself.
What is a class?
A class is an encapsulation of data members and functions that manipulate the data.
What is an instance?
An individual object that is a member of a class.
What is a constructor?
Constructors are methods defined in a class that are invoked automatically when an object is created. They are used to initialize a newly allocated object.
What is a default ctor?
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
What is a copy ctor?
Copy constructors are used to make a copy of one class object from another class object of the same class type.
What is a macro?
It is a pattern that specifies how a certain input sequence should be mapped to an output sequence. C++ supports macros although, Java does not.
What are the advantages/disadvantages of using inline and const?
The advantages of inline functions are that they are quick and the disadvantages of inline functions are that they get complied every time the function is called and affects the file size.
What are pass by reference and pass by value?
Pass by reference means passing the address rather than the value. Pass by value means passing a copy of the value.
What does it mean to take the address of a reference?
A reference is an alias or an alternative name for an object. All operations applied to a reference act on the object to which the reference refers. The address of a reference is the address of the aliased object. Passing an object by reference enables the function to change the object being referred to without creating a copy of the object within the scope of the function. Only the address of the actual original object is put on the stack, not the entire object.
What does it mean to declare a function or variable as static?
It simply means that once the variable has been initialized, it remains in memory until the end of the program. Static member functions can only access static members.
What is a pure virtual function?
It doesn’t contain a body and it acts as an interface. A class that has at least one pure virtual function is automatically called an abstract class.
What are wrapper classes?
Wrapper classes allow primitive types to be accessed as objects. The wrapper class is wrapped around the primitive data type.
Explain what happens when an exception is thrown.
It depends on whether or not we have any code that catches the exception.
What happens if an exception is not caught?
An uncaught exception would cause the program to terminate.
What are the costs and benefits of using exceptions?
Advantages: Exception handling increases the programs reliability. Programs doe not crash.
Disadvantages: You must enable exception handling in the complier and there is overhead associated with it. – the expense of overhead.
What is an iterator?
An iterator is similar to a pointer. It accesses elements of a container class.
What is multi-tiered application architecture?
Multi-tiered application architecture involves client/server computing.
What are the main features of OO programming? Explain.
Data Abstraction represents essential features without including the background details or explanations. It refers to language features that allow you to create new, User Defined Types (UDTs).
PIE
Polymorphism: Helps decouple the “what” from the “how”. This is done by virtual functions. It allows you to treat derived class members just like their base class members. For example, Animal->Speak->Dog->Pig. If speak is invoked, a dog will bark and a pig will oink.
Inheritance: The ability to construct one class from another. A derived class is a completely new class that inherits attributes and behaviors (all the data and member functions) of its base class. The derived class is usually more specialized version of the base class. Inheritance provides reusability. Also, Inheritance is unidirectional. i.e. A car is a vehicle however, a vehicle is not necessarily a car.
Encapsulation or Information Hiding: Allows you to hide the details of a class from objects that communicate with it.
Can you explain an “is a” (Inheritance) relationship and a “has a” (Composition) relationship?
They both allow you to place sub-objects inside your new class. They are two of the main techniques for code reuse. For example,
- a car is a vehicle
- a car has an engine
Composition simply means using instance variables that refer to other objects. The class Vehicle will have an instance variable which refers to the Car object.
What is the difference between the stack and the heap?
The difference between the stack and the heap is that the stack gets allocated at compile-time while the heap gets allocated at run-time.
What are the main differences between Object Oriented Programming and Procedural Programming?
1.OOP enables the programmer to create programs (modules) that do not need to be changed when a new object is added.
2.A programmer can create a new object that inherits many of its features from existing objects.
PP consists of data structures and subroutines.
OOP consists of objects and allows mapping of a database model to their own classes.
How does Object Oriented Programming improve software development?
Code reusability and the ability to map real world things to objects.
What is final?
A final class can’t be extended. i.e, a final class may not be sub-classed. A final method cannot be overridden when its class is inherited. You can’t change the value of a final variable.
What two general classes that software can be divide into?
Software can be divided into two general classes: systems software and applications software. Systems software consists of low-level programs that interact with the computer at a very basic level. This includes operating systems, compilers, and utilities for managing computer resources.
In contrast, applications software (also called end-user programs) includes database programs, word processors, and spreadsheets. Figuratively speaking, applications software sits on top of systems software because it is unable to run without the operating system and system utilities.
What is an application?
A program or group of programs designed for end users.
What is a State Diagram?
Relates events and states. When an event is received, the next state depends on the current state as well as the event. A state Diagram gives insight to the flow of an object in a system, and the effect it can have when an event occurs.
What is UML?
It represents the blueprints in which the language is written in.
Subscribe to:
Posts (Atom)