Saturday, July 2, 2011

code fragment gives a simple example of these three steps


public void connectToAndQueryDatabase(String username, String password) {

Connection con = DriverManager.getConnection
("jdbc:myDriver:myDatabase", username, password);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
// ...

code fragment gives a simple example of these three steps

Three programming activities JDBC



JDBC helps you to write java applications that manage these three programming activities:





  1. Connect to a data source, like a database


  2. Send queries and update statements to the database


  3. Retrieve and process the results received from the database in answer to your query

Friday, July 1, 2011

Which one to favor, composition or inheritance?

The guide is that inheritance should be only used when
subclass ‘is a’ superclass.
􀂃 Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code
reuse. Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if
the superclass is modified.
􀂃 Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is
polymorphism then use interface inheritance with composition, which gives you code reuse.

How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition? What is the difference between compositio

The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.
Inheritance [ is a ] Vs Composition [ has a ] Building Bathroom House
class Building{
.......
}
class House extends Building{
.........
}
is a [House is a Building]
class House {
Bathroom room = new Bathroom() ;
....
public void getTotMirrors(){
room.getNoMirrors();
....
}
}
is a has a [House has a Bathroom] has a Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.

How does the Object Oriented approach improve software development?

The key benefits are:
􀂃 Re-use of previous work: using implementation inheritance and object composition.
􀂃 Real mapping to the problem domain: Objects map to real world and represent vehicles, customers,
products etc: with encapsulation.
􀂃 Modular Architecture: Objects, systems, frameworks etc are the building blocks of larger systems.
The increased quality and reduced development time are the by-products of the key benefits discussed above.
If 90% of the new application consists of proven existing components then only the remaining 10% of the code
have to be tested from scratch.

What are the advantages of Object Oriented Programming Languages (OOPL)?

The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account,
Customer etc. The features of the OO programming languages like polymorphism, inheritance and
encapsulation make it powerful. [Tip: remember pie which, stands for Polymorphism, Inheritance and
Encapsulation are the 3 pillars of OOPL

How to call the superclass constructor?

If a class called “SpecialPet” extends your “Pet” class then you can
use the keyword “super” to invoke the superclass’s constructor. E.g.
public SpecialPet(int id) {
super(id); //must be the very first statement in the constructor.
}
To call a regular method in the super class use: “super.myMethod( );”. This can be called at any line. Some frameworks based on JUnit add their own initialization code, and not only do they need to remember to invoke their parent's setup() method, you, as a user, need to remember to invoke theirs after you wrote your initialization
code:
public class DBUnitTestCase extends TestCase {
public void setUp() {
super.setUp();
// do my own initialization
}
}
public void cleanUp() throws Throwable
{
try {
… // Do stuff here to clean up your object(s).
}
catch (Throwable t) {}
finally{
super.cleanUp(); //clean up your parent class. Unlike constructors
// super.regularMethod() can be called at any line.

Can you call one constructor from another?

Yes, by using this() syntax.
E.g. public Pet(int id) {
this.id = id; // “this” means this object
}
public Pet (int id, String type) {
this(id); // calls constructor public Pet(int id)
this.type = type; // ”this” means this object
}

What happens if you do not provide a constructor?

Java does not actually require an explicit constructor in
the class description. If you do not include a constructor, the Java compiler will create a default constructor in the
byte code with an empty argument. This default constructor is equivalent to the explicit “Pet(){}”. If a class includes
one or more explicit constructors like “public Pet(int id)” or “Pet(){}” etc, the java compiler does not create the
default constructor “Pet(){}”.

What is the difference between constructors and other regular methods? What happens if you do not provide a constructor? Can you call one constructor


What are “static initializers” or “static blocks with no function names”?

When a class is loaded, all blocks that are declared static and don’t have function name (i.e. static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields.
public class StaticInitializer {
public static final int A = 5;
public static final int B; //note that it is not 􀃆 public static final int B = null;
//note that since B is final, it can be initialized only once.
//Static initializer block, which is executed only once when the class is loaded.
static {
if(A == 5)
B = 10;
else
B = 5;
}
public StaticInitializer(){} //constructor is called only after static initializer block
}
The following code gives an Output of A=5, B=10.
public class Test {
System.out.println("A =" + StaticInitializer.A + ", B =" + StaticInitializer.B);
}

Explain static vs. dynamic class loading?




What do you need to do to run a class with a main() method in a package?

Example: Say, you have a class named “Pet” in a project folder “c:\myProject” and package named
com.xyz.client, will you be able to compile and run it as it is?
package com.xyz.client;
public class Pet {
public static void main(String[] args) {
System.out.println("I am found in the classpath");
}
}
To run 􀃆 c:\myProject> java com.xyz.client.Pet
The answer is no and you will get the following exception: “Exception in thread "main" java.lang.-
NoClassDefFoundError: com/xyz/client/Pet”. You need to set the classpath. How can you do that? One of the
following ways:
1. Set the operating system CLASSPATH environment variable to have the project folder “c:\myProject”. [Shown
in the above diagram as the System –classpath class loader]
2. Set the operating system CLASSPATH environment variable to have a jar file “c:/myProject/client.jar”, which
has the Pet.class file in it. [Shown in the above diagram as the System –classpath class loader].
3. Run it with –cp or –classpath option as shown below:
c:\>java –cp c:/myProject com.xyz.client.Pet
OR
c:\>java -classpath c:/myProject/client.jar com.xyz.client.Pet

Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?


Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So, how is the very first class loaded? The very first class is especially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader.
Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.

What are the usages of Java packages?

It helps resolve naming conflicts when different packages have classes with the same names. This also helps you
organize files within your project. For example: java.io package do something related to I/O and java.net
package do something to do with network and so on. If we tend to put all .java files into a single package, as the
project gets bigger, then it would become a nightmare to manage all your files.
You can create a package as follows with package keyword, which is the first keyword in any Java program
followed by import statements. The java.lang package is imported implicitly by default and all the other packages
must be explicitly imported.
package com.xyz.client ;
import java.io.File;
import java.net.URL;

What is the difference between C++ and Java?

Both C++ and Java use similar syntax and are Object Oriented, but:
􀂃 Java does not support pointers. Pointers are inherently tricky to use and troublesome.
􀂃 Java does not support multiple inheritances because it causes more problems than it solves. Instead Java
supports multiple interface inheritance, which allows an object to inherit many method signatures from
different interfaces with the condition that the inheriting object must implement those inherited methods. The
multiple interface inheritance also allows an object to behave polymorphically on those methods.
􀂃 Java does not support destructors but adds a finalize() method. Finalize methods are invoked by the garbage
collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means
you do not know when the objects are going to be finalized. Avoid using finalize() method to release nonmemory
resources like file handles, sockets, database connections etc because Java has only a finite
number of these resources and you do not know when the garbage collection is going to kick in to release
these resources through the finalize() method.
􀂃 Java does not include structures or unions because the traditional data structures are implemented as an
object oriented framework.
􀂃 All the code in Java program is encapsulated within classes therefore Java does not have global variables or
functions.
􀂃 C++ requires explicit memory management, while Java includes automatic garbage collection

What is the main difference between the Java platform and the other software platforms?


Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc.
The Java platform has 2 components:
􀂃 Java Virtual Machine (JVM) – ‘JVM’ is a software that can be ported onto various hardware platforms. Byte
codes are the machine language of the JVM.
􀂃 Java Application Programming Interface (Java API) – set of classes written using the Java language and run
on the JVM.

Give a few reasons for using Java?

Java is a fun language. Let’s look at some of the reasons:
􀂃 Built-in support for multi-threading, socket communication, and memory management (automatic garbage
collection).
􀂃 Object Oriented (OO).
􀂃 Better portability than other languages across operating systems.
􀂃 Supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI, EJB etc)
and network protocols (HTTP, JRMP etc) with the help of extensive standardized APIs (Application
Programming Interfaces).

An included servlet


package com.ack.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AnIncludedServlet extends HttpServlet {

public void doGet( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException {
PrintWriter pw = res.getWriter();

/**
* note that a servlet that has been included within another
* servlet has access to both the original request uri, servlet
* path, path info, context path and query string through the
* HttpServletRequest object.
*
* However it also has access to these values that can be different
* depending on how the servlet include was dispatched. The servlet
* engine gives you access to these though request attributes as
* demonstrated before.
*/

pw.println( "

The Included Servlet

" );
pw.println( "
request uri: " +
req.getAttribute( "javax.servlet.include.request_uri" ) );
pw.println( "
context path: " +
req.getAttribute( "javax.servlet.include.context_path" ) );
pw.println( "
servlet path: " +
req.getAttribute( "javax.servlet.include.servlet_path" ) );
pw.println( "
path info: " +
req.getAttribute( "javax.servlet.include.path_info" ) );
pw.println( "
query string: " +
req.getAttribute( "javax.servlet.include.query_string" ) );
}
}