Advanced Java Interview Questions | Eklavya Online

Advanced Java Interview Questions

B2B stands for Business-to-business.

The application client module contains:

class files, and an application client deployment descriptoor.

Application client modules are packaged as JAR files with a .jar extension

A person who combines J2EE components and modules into deployable application units.

The process of saving the state of an object and restoring it.

The XML file that contains one or more asant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project’s default target is executed.

A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.

A Java-based build tool that can be extended using Java classes. The configuration files are XML-based, calling out a target tree where various tasks get executed

A qualifier on an XML tag that provides additional information.

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.

An authentication mechanism in which a Web server authenticates an entity via a user name and password obtained using the Web application’s built-in authentication mechanism.

A predefined XML tag for character data that means “don’t interpret these characters,” as opposed to parsed character data (PCDATA), in which the normal rules of XML syntax apply. CDATA sections are typically used to show examples of XML syntax.

A container that supports application client components.

A software unit that consists of one or more classes and an application client deployment descriptor

A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

A trusted organization that issues public key certificates and provides identification to the bearer.

The process by which access to a method or resource is determined. Authorization depends on the determination of whether the principal associated with a request through authentication is in a given security role. A security role is a logical grouping of users defined by the person who assembles the application. A deployer maps security roles to security identities. Security identities may be principals or groups in the operational environment.

Component methods called by the container to notify the component of important events in its life cycle.

An authentication mechanism that uses HTTP over SSL, in which the server and, optionally, the client authenticate each other with a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure

An authorization rule that determines who is permitted to access a Web resource collection.

Generating the code needed to process a well-defined portion of XML data.

Same as caller principal.

In an XML document, text that is ignored unless the parser is specifically told to recognize it.

An XML file used to configure resources for a JavaServer Faces application, to define navigation rules for the application, and to register converters, validators, listeners, renderers, and components with the application.

cmd/designated folder/ jar cf name.jar *.*

Create a file: META-INF/MANIFEST.MF Add a line: Main-Class: com.myco.calc.CalculatorDemo Include META-INF/MANIFEST.MF in calculator.jar Run with java -jar calculator.jar

load()get()
Only use the load() method if you are sure that the object exists.If you are not sure that the object exists, then use one of the get() methods
load() method will throw an exception if the unique id is not found in the database.get() method will return null if the  unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.get() will hit the database immediately.

A “cookie” is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. This is useful for having the browser remember some specific information.

  • to create a temporary session where the site in some way “remembers in the short term” what the user was doing or had chosen between web page requests, e.g. remembering who the user is logged in as at the moment, or what they’ve ordered from an on-line “shopping cart”;
  • to remember low-security information more permanently: for example, to remember a user’s search results preferences or who they are logged in as on their social bookmarking site;
  • to compile user statistics, e.g. for advertising purposes or for improving the functionality of a site.

Getting the Value of a Cookie with a Specified Name :

for(int i=0; i<cookies.length; i++)

{

Cookie cookie = cookies[i];

if (cookieName.equals(cookie.getName()))

return(cookie.getValue());

}

return(defaultValue);

request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

Gets/sets how much time (in seconds) should elapse before the cookie expires. If you don’t set this, the cookie will last only for the current session (i.e. until the user quits the browser), and will not be stored on disk.

setSecure method indicates to the web browser that the cookie should only be sent using a secure protocol (https). getSecure method returns the value of the ‘secure’ flag.

Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST  method.

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

myCar” is a persistent object at this stage.
Session session1 = sessionFactory.openSession();
Car myCar = session1.get(Car.class, carId);
session1.close();
once the session is closed “myCar” becomes a detached objectyou can now pass the “myCar” object all the way upto the presentation tier. It can be modified without any effect to your database table.
myCar.setColor(“Red”); //no effect on the database
When you are ready to persist this change to the database, it can be reattached to another session as shown below:
Session session2 = sessionFactory.openSession();
Transaction tx = session2.beginTransaction();
session2.update(myCar); //detached object ”myCar” gets re-attached
tx.commit(); //change is synchronized with the database.
session2.close()

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

SQLWarning warning = stmt.getWarnings();

if (warning != null)

{

while (warning != null)

{

System.out.println(\”Message: \” + warning.getMessage());

System.out.println(\”SQLState: \” + warning.getSQLState());

System.out.print(\”Vendor error code: \”);

System.out.println(warning.getErrorCode());

warning = warning.getNextWarning();

}

}

Application level data integrity constants are important if you are making changes to offline information which is again backed by database. Higher level locking or versioning protocol is required to support them. Version field usage comes at this stage but the design and implementation process is left to the developer

  • Forward : when forward is used server forwards the request to the new url and the control stays on the same page. in other words it just forward the request to new url and come back fomr where forward is called.
  • sendRedirect : sendRedirect forward the request to url as new request and the cotrol goes to the destination page and never come back to the calling page

When you reattach detached objects, you need to make sure that the dependent objects are reattached as well.

Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application.
They are:
Request, response, pageContext, session, application, out, config, page, exception.

Using System.exit(1); in try block will not allow finally code to execute

In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactionalreliability.

The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.

Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)

  • Do we need to support multiple data formats?
  • Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
  • Is the call synchronous or asynchronous?
  • Is the call stateful or stateless? (REST is suited for statless CRUD operations)
  • What level of security is required? (SOAP WS has better support for security)
  • What level of transaction support is required? (SOAP WS has better support for transaction management)
  • Do we have limited band width? (SOAP is more verbose)
  • What’s best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)

This function translates a Java class name into file name. This translated file name is then loaded as an input stream from the Java class loader. This addclass function is important if you want efficient usage of classes in your code.

The best practice is to use “contract-first”, and here is the link that explains this much better with examples –>  contract-first versus contract-last web services In a nutshell, the contract-last is more fragile than the “contract-first”.You will have to decide what is most appropriate based on your requirements, tool sets you use, etc.

Note: More Java Web Services interview questions and answers including WSDL, SOAP, UDDI, JAXR, SAAJ, etc are covered in Java/J2EE Job Interview Companion with diagrams.

SoapUI tool for SOAP WS and the Firefox “poster” plugin for RESTFul services.

This id field corresponds to the surrogate key which is generated by the database. These fields are handled by the id field. Name attribute is used to specify the names of the field and it should correspond to the method name of getid. This also should correspond to long type and the values should be stored I the database in the long column.

Server Side Templating

  • Pros:
    • More search engine friendly.
    • Entire response message can be cached.
    • Can work without JavaScript
  • Cons:
    • Harder to mix and match different server side technologies. For example, retrieve data from both Java and Ruby based services
    • Harder to send content for multiple devices. E.g. browser, mobile devices, etc.

Client Side Templating

  • Pros:
    • Faster development and prototyping
    • Serves JSON data to multiple devices.
    • The responses are smaller as JSON data is less verbose.
    • Templates and JSON data can be cached.
    • Can work with multiple server side technologies like .Net, JEE, Ruby, etc
  • Cons:
    • Less search engine friendly
    • Older browsers may not work properly
    • Cross browser compatbility testing is required

These two approaches

  • The contract-first approach, where you define the contract first with XSD and WSDL and the generate the Java classes from the contract.
  • The contract-last approach where you define the Java classes first and then generate the contract, which is the  WSDL file from the Java classes.

Note: The WSDL describes all operations that the service provides, locations of the endpoints (i.e.e where the services can be invoked), and simple and complex elements that can be passed in requests and responses.

Contract-first Web service

PROS:

  • Clients are decoupled from the server, hence the implementation logic can be revised on the server without affecting the clients.
  • Developers can work simultaneously on client and server side based on the contract both agreed on.
  • You have full control over how the request and response messages are constructed — for example, should “status” go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the “status” would be generated as “attribute” instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc.

CONS:

  • More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as well.
  • Developers need to learn XSDs and WSDLs in addition to just knowing Java.

Contract-last Web service

PROS:

  • Developers don’t have to learn anything related to XSDs, WSDLs, and SOAP. The services are created quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based wizards, etc.
  • The learning curve and development time can be smaller compared to the Contract-first Web service.

CONS:

  • The development time can be shorter to initially develop it, but what about the on going maintenance and extension time if the contract changes or new elements need to be added? In this approach, since the clients and servers are more tightly coupled, the future changes may break the client contract and affect all clients or require the services to be properly versioned and managed.
  • In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could cause something that used to be an element to become an attribute with the change of the OXM.