Thursday, May 29, 2008

JSP Interview Questions

  1. What is JSP? Describe its concept. JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic

  2. What are the lifecycle phases of a JSP?
    JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.

    1. Page translation: -page is parsed, and a java file which is a servlet is created.

    2. Page compilation: page is compiled into a class file

    3. Page loading : This class file is loaded.

    4. Create an instance :- Instance of servlet is created

    5. jspInit() method is called

    6. _jspService is called to handle service calls

    7. _jspDestroy is called to destroy it when the servlet is not required.

  3. What is a translation unit? JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.

  4. How is JSP used in the MVC model? JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

  5. What are context initialization parameters? Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

  6. What is a output comment? A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

  7. What is a Hidden Comment? A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.

  8. What is a Expression? Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.

  9. What is a Declaration? It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file.

  10. What is a Scriptlet? A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a .

  11. What are the implicit objects? List them. Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:

    • request

    • response

    • pageContext

    • session

    • application

    • out

    • config

    • page

    • exception

  12. What’s the difference between forward and sendRedirect? When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

  13. What are the different scope values for the ? The different scope values for are:

    • page

    • request

    • session

    • application

  14. Why are JSP pages the preferred API for creating a web-based client program? Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

  15. Is JSP technology extensible? Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

  16. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:

    • Custom tags can manipulate JSP content; beans cannot.

    • Complex operations can be reduced to a significantly simpler form with custom tags than with beans.

    • Custom tags require quite a bit more work to set up than do beans.

    • Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.

    • Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

17. What are the most common techniques for reusing functionality in object-oriented systems?
A: The two most common techniques for reusing functionality in object-oriented systems are class inheritance and object composition.

Class inheritance lets you define the implementation of one class in terms of another’s. Reuse by subclassing is often referred to as white-box reuse.
Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality. This is known as black-box reuse.

18.Why would you want to have more than one catch block associated with a single try block in Java?
A: Since there are many things can go wrong to a single executed statement, we should have more than one catch(s) to catch any errors that might occur.

19. What language is used by a relational model to describe the structure of a database?
A: The Data Definition Language.

20. What is JSP? Describe its concept.
A: JSP is Java Server Pages. The JavaServer Page concept is to provide an HTML document with the ability to plug in content at selected locations in the document. (This content is then supplied by the Web server along with the rest of the HTML document at the time the document is downloaded).

21.What does the JSP engine do when presented with a JavaServer Page to process?
A: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in calls to methods of the appropriate JavaBean class whose output is translated into more calls to a println method to place the result in the HTML document.

Servlet interview questions

  1. What is a servlet?
    Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

  2. Whats the advantages using servlets over using CGI?
    Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

  3. What are the general advantages and selling points of Servlets?
    A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online
    real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

  4. Which package provides interfaces and classes for writing servlets? javax

  5. What’s the Servlet Interface?
    The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more
    commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet.
    The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

  6. When a servlet accepts a call from a client, it receives two objects. What are they?
    ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.

  7. What information does ServletRequest allow access to?
    Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names
    of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods.

  8. What type of constraints can ServletResponse interface set on the client?
    It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through
    which the servlet can send the reply data.

  9. Explain servlet lifecycle?
    Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down.

  10. How does HTTP Servlet handle client requests?
    An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

  11. Explain the life cycle methods of a Servlet ? The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
    public void init(ServletConfig config) throws ServletException
    public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
    public void destroy()

    First the servlet is constructed, then initialized wih the init() method.
    Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

    The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

  12. What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface? The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

    The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.

  13. Explain the directory structure of a web application ? The directory structure of a web application consists of two parts.
    A private directory called WEB-INF
    A public resource directory which contains public resource folder.

    WEB-INF folder consists of
    1. web.xml
    2. classes directory
    3. lib directory

  14. What are the common mechanisms used for session tracking? Cookies
    SSL sessions
    URL- rewriting

  15. Explain ServletContext. ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

  16. What is preinitialization of a servlet? A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

  17. What is the difference between Difference between doGet() and doPost()?A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
    http://www.hitechskill.com/svt1?p1=v1&p2=v2&...&pN=vN
    doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

  18. What is the difference between HttpServlet and GenericServlet?A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
    Both these classes are abstract.

Collections List

Access Modifiers

1. Is it a must for a abstract class to have a abstract method?

A: No!

All methods defined in interfaces are abstract.
All classes which have abstract method(s) must be declared abstract, but not vice versa.

2. What is modifier for the default constructor implicitly generated by Java compiler?

A: The default constructor implicitly generated by Java compiler should have the same accessibility as the class. i.e. public class will have a public default constructor, package "friendly" class will have package "friendly" constructor, unless you explicitly define it otherwise.See Package usage example for details.

3. Can one object access a private variable of another object of the same class?

A: Yes! One object can access a private variable of another object of the same class. The private field can be accessed from static method of the class through an instance of the same class too.Here is an example:

public class Test1 {
private int i;
Test1(int ii) {
i = ii;
System.out.println("Self: " + i);
// to avoid infinite recursion
if (i != 3) {
Test1 other = new Test1(3);
other.i++;
System.out.println("Other: " + other.i);
}
}

public static void main(String[] args) {
Test1 t = new Test1(5);

// The private field can be accessed from
// static method of the same class
// through an instance of the same class
System.out.println(t.i);
}
}

4. Several questions about static:

a) Can a static variable be declared within a method?
b) Can a static method contain an inner class?
c) Can a static method contain an static inner class?

A:

a) No, not in Java, but yes in C++
b) Yes
c) No
The simplest way to have your doubts clarified is to write a short program, then compile it to see the result. CODE, Code, code, ... please! An example here:

class Test {
void method() {
//static int i = 3; // not compilable
}
static void smethod() {
//static int i = 3; // not compilable
class local {
}
/* not compilable
static class slocal {
}
*/
}
}

5. Why the following code not compilable? Do we need to initial final variable explicitly?

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;
}

A:

The above code is not compilable since final variable fsn and fn are not initialized.Yes, final variable (variables), static or instance, must be initialized explicitly. It can be done by an initializer, static or instance respectively. final instance variables can also be initialized by every constructor.Three choices to make the code right:

public class Test{
static int sn;
int n;
final static int fsn = 3;
final int fn = 6;
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}
{fn =8;}
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}

Test(){
fn =8;
}
Test(int pn){
fn =pn;
}
}

6. Can we declare an object as final? I think I still can change the value of a final object.

A:

final variables cannot be changed.
final methods cannot be overridden.
final classes cannot be inherited. However, there is something easily to be confused. There is no final Object in Java. You cannot even declare an Object in Java, only Object references. We only can have final object reference, which cannot be changed. It is like that the address of your house cannot be changed if it is declared as final. However, you can remodel your house, add a room, etc. Your house is not final, but the reference to your house is final. That is a little confusing. By the way, use finals as much as possible, but do not overuse them of course. It is because compiler knows they are not going to change, the byte code generated for them will be much more efficient.

7. Can we use transient and static to modify the same variable? Does it make any difference in Object serialization?

A: Yes, we can use transient and static to modify the same variable. It Does not make any difference in Object serialization. Since both transient and static variables are not serializable.See your exausting example at TestSerialization.java

8. What happens if we don't declare a constructor as public? Is it a useful strategy somewhere?

A: Following discussion is based on the assumption of that your class is declared as public and at least has some public members, and the other package imports your class or using full-qualified names to use your class.

  1. You cannot construct an instance of the class by using this constructor in another package.

  2. If you have other constructors declared public, you still can construct an instance of the class by using other public constructors in another package.

  3. If all your constructors are not public, then the class cannot be constructed in packages other than the package it was defined.

  4. If the other package gets a reference to it, its public members still can be used. Singleton Design Pattern is a good example for it. We even use private construtor intentionally.

9. In a non-static inner class, static final variables are allowed, but not static variables! why?

A: When a variable is static final, actually, it is not a variable; it is a constant. Compiler will treat it differently.

10. Can final and transient be used together? Why?

A: Yes, they can.

final variables cannot be changed.
final methods cannot be overridden.
final classes cannot be inherited. transient variables cannot be serialized. They are independent of each other. A variable can be final or a constant (an oxymoron, right? ), and transient or not serializable. I actually figured out a good reason not to serialize final variables.Serializing objects are mostly for transferring data. The both side of transferring will know the Class object, know the constants in most of the cases, with the exception of initialized finals in constructors by using the parameter value. Not Serializing the final will certainly save transferring time. Using final and transient together will certainly have some advantages in distributed computing. And, please remember, putting final and transient together is an option, not a requirement.

11. Why null variable can access static member variables or methods?

A: When you call a static data member or method, all it matters is right type. See example here

// ST.java
class ST {
static int n = 3;
static int getInt() {
return n + 35;
}

public static void main(String[] args) {
ST st = null; // st has the type of ST

System.out.println(st.n); // 3
System.out.println(st.getInt());// 38

// the above lines are equivalent to the followings
System.out.println(ST.n); // 3
System.out.println(ST.getInt());// 38
}
}

12. Should we hide private method defined in the superclass by defining the same name and signature method in the subclass?

A: No.

If super class defined a private method, it hides itself; nobody else can see it or use it. That is exactly what private means. It does not need a subclass to define a same name and signature method to be hided!!!If the subclass use the same name and signature to define another method, it does not hide anything, it is just itself and totally irrelevant with the super class same name method. In addition, it should be only considered a bad-coding style, even it is legal.Please read everything about hiding here!
a section in JLS2

13. Why I got IllegalAccessException when I try to use reflection or dynamic proxy to access some package level methods from another package?

A: Why not?

Do you think what you get is the reasonable behavior of Java? OR Do you assume Proxy or reflection should break the rule of Java, and open a backdoor to a class, and let it do something, which it is not supposed to do?

String and StringBuffer

1.What is the difference between String s = "hello"; and String s = new String("hello"); ?

2. Why String and StringBuffer works differently, discrimination?

// Test.java
public class Test {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("hello");
System.out.println("String: s1.equals(s2) = " + s1.equals(s2));
System.out.println("StringBuffer: sb1.equals(sb2) = " + sb1.equals(sb2));
}
}

// output
/*
String: s1.equals(s2) = true
StringBuffer: sb1.equals(sb2) = false
*/

A:

Since String class overrides the equals() method of Object class, and StringBuffer does not.
Read here: equals method and check the JDK doc for String and StringBuffer too.

3. How does Java String concatenation, or the overloaded + between different types, work?

A: Go to your JDK1.2.2/JDK1.3 directory, find src.jar, unjar it. Then you can see all source code of JDK.Goto src\java\lang, to find StringBuffer.java and String.java. Search for append in the beginning comments of StringBuffer.java, then follow the lead, you will find out all the secrets you are interested in. "If you give me a fish, You feed me for the day.
If you teach me how to fish, you feed me for life.
"

4. Why are outputs of these two statements so different?

System.out.println(6 + 4 + " = sum"); // 10 = sum
System.out.println("sum = " + 6 + 4); // sum = 64

A:

  • Java evaluates the expression inside println(expr) first, then convert it to a String.

  • When Java evaluates the expression, it follows the left-to-right rule.

  • "+" operator is overloaded in a very intuitive way just as in most other languages.

  • In 6 + 4 + " = sum": from left to right, evaluates 6 + 4 first, two integer adds, 10 resulted. Then 10 + " = sum", int plus a String, String concatenation assumed, converts 10 to a string, then ...

  • In "sum = " + 6 + 4: from left to right, "sum = " + 6, String plus an int, String concatenation assumed, converts 6 to a String, concatenates them together, become "sum = 6". Then repeats the same process with "sum = 6" + 4. You know the answer.

  • String concatenation process actually is finished by a class StringBuffer. If you want to know the details, read the source code of jdk: StringBuffer.java. It is highly recommended for you to do that.

Methods Overloading and Overriding

5. What is the basic difference between the concept of method overloading and overriding?

A: They are totally irrelevant except the name similarities in two senses.

sense #1: English words overriding and overloading both have "over" inside
sense #2:overloading methods will have the "same name" but different signature. overriding methods will have the "same name" and same signature.

Except these above, there is nothing in common between them. Please read some more from the following QAs.

6. Can overloaded methods in derived class hide the same name methods (with different signature) in base class?

A: When methods are defined with the same name, but different signature, they are just name overloading, nothing can hide anything else. It is irrelevant it is in a derived class or not.

  1. American people drive on the right side.

  2. You are right on this topic.

  3. He will be right back.

English word right is overloaded here, we understand the difference by the context. Compiler understands the method overloading by the signature, which serves the same purpose as context, but more reliable, since compiler is not as intelligent as you are. If derived class (subclass) defines a non-private method with the same name and same signature as the non-private method defined in base class, then it is method overriding, polymorphism comes into play. Late binding/Runtime binding will happen.Never mix these two words overriding and overloading, please.

7.Can overloaded methods be override too? Static binding or dynamic binding?

A: Yes, of course! In compiler point of view, overloaded methods are totally different methods. Because compiler identifies methods by their name and signature, you know overloaded methods must have different signatures.

Derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future. It is compiler's responsibility to check the caller class has the method being called. It is the runtime's responsibility to call the right method along the hierarchy from bottom-up according to the real Object type identified.

8. What are the differences between overloading and overriding? Are they both concepts of polymorphism?

A: No, overloading is NOT a concept of polymorphism.

Let me try a short one about overloading. The approach is like you take the test, cross out something obviously not correct, before you decide what is correct. 3 + 5
3.0 + 5.0
The plus (+) operator is overloaded long before even OO concepts came into play in computer sciences. It is in Fortran (the first high level computer language) for sure.

  1. American drives on the right. British drives on the left.

  2. Maha Anna is right on this topic.

  3. I'll be right back.

  4. These are right angle triangles.

  5. You have the right to disagree with me.

  6. He is a right extremist.

  7. Actually, you can even overload the English word right to mean a dog in certain communication circle. Just thinking a scenario, you name your dog as Right, then in your family, when you or your kids talk about Right, the most of the time, it is referring to the dog. And it is a valid overloading; no body will put you in jail or even criticize you for your use of English word right this way...

  8. ...

The English word right is overloaded here. All natural languages are overloaded long before computer even invented. Polymorphism is a very specific OO concept, which has nothing to do with overloading. You really need to read a good OO book to understand it. It is too large a job for me to write about it here. There is so much misunderstanding out there on this topic, a lot of them are in published books. Like Marcus said: "Don't believe everything you read." If you don't believe what you read here by Roseanne, I'm OK.

P.S. The word Polymorphism itself in natural languages can be overloaded too like the Right example in English. You can overload the word polymorphism with whatever meaning you want it to mean. However, I still agree with most computer scientists' narrow and precise definition of polymorphism. If you don't agree with me, no more arguments are needed; we all can rest in peace...

9. When ambiguity exists between method calls, how does compiler resolve it? Why String version of the method is called instead of the Object version in the following example?

// Overloading.java
public class Overloading {

public void method(Object o) {
System.out.println("Object Version");
}

// String is an Object, but a specific Object
public void method(String s) {
System.out.println("String Version");
}

public static void main(String args[]) {
Overloading test = new Overloading();

// null is ambiguous to both methods
// The more specific one is called
test.method(null); // String Version
}
}

A:

The answer is in the comments of above code; just remember that when ambiguity exists between method calls, compiler resolves it by choosing the more specific ones. If it does not work, it will error out.

Why String is more specific than Object?

This is a Basic OO concept about generalization/specialization, read here for more specific information. Here is a brief:

OakTree is a specific Tree.
Cat is a specific Animal.
String is a specific Object.
Subclass ISA specific Baseclass.

10. Can overloaded methods have the same signature but different return type?

A: No, absolutely not!

In any programming languages, Methods overloading only applies to methods with different signatures. If same signature, there is only one method, two return types is impossible for one method. Try 5-10 line of code in Java or C++, you get your answer.Read here from JLS 8.4.7 Overloading


If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.


However, If we have two overloaded methods (which means they have the same name, but different signatures), they can have same/different return types, and/or throw same/different exceptions.

11. Can static method be overridden?

A: No!

The concept of overriding is binding at runtime, or polymorphism. Static is just on the opposite side of the equation, binding at the compile time, polymorphism does not apply to static method.


Methods a Subclass Cannot Override A subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). If you attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program:"
... "Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass. " Quotation from Overriding Methods of The Java Tutorial


See more interesting discussion and sample code here: Can subclass override methods that are declared static in the superclass?

12. Can constructor be overridden?

A: No!

No, constructor cannot be overridden. Constructor must have the same name of the class itself, can never be its ancestor's name. For constructor calling orders, read here: What is the calling order of constructors along the hierarchy, from child up, or from ancestor down?

13. Can you explain the result of the following example? Oh, my!

class Base {
public boolean foo(Base b) {
return true;
}
}
class Sub extends Base {
public boolean foo(Sub s) {
return false;
}
}

public class Test {
public static void main(String argv[]) {
Base bb = new Base();
Base bs = new Sub();
Sub ss = new Sub();

System.out.println(bb.foo(bb)); //true

System.out.println(bs.foo(bs)); //true ???
System.out.println(bs.foo(ss)); //true ???
System.out.println(bs.foo(bb)); //true ???
System.out.println(ss.foo(bs)); //true ???
System.out.println(ss.foo(bb)); //true ???

System.out.println(ss.foo(ss)); //false
}
}

A: The foo methods are overloaded in the Sub. In Base, there is only one foo method, and it is not overridden by the Sub!

Overloading is fundamentally different then overriding. There is no polymorphism or dynamic binding here!!! All decisions are made at compile time!!! See detailed explanation in the same code below, documented!

class Base {
// There is only one foo method in Base!!!
public boolean foo(Base b) {
return true;
}
}
class Sub extends Base {
// differnt signature, method overloading
// there are 2 foo methods in the Sub
public boolean foo(Sub s) {
return false;
}
}

public class Test {
public static void main(String argv[]) {
// bb is a Base ref to the compiler, Base obj at runtime
Base bb = new Base();
// bs is a Base ref to the compiler, Sub obj at runtime
Base bs = new Sub();
// ss is a Sub ref to the compiler, Sub obj at runtime
Sub ss = new Sub();

// All these 4 lines are Base ref
// call Base.foo(Base) method, and only one foo available
// bs is a Base ref, and ss ISA Base ref too
// Everything is fine!!!
System.out.println(bb.foo(bb)); //true
System.out.println(bs.foo(bs)); //true
System.out.println(bs.foo(ss)); //true
System.out.println(bs.foo(bb)); //true

// bb, bs are both Base refs to Compiler
// ss is a Sub ref
// call Sub.foo(Base) which is inherited from Base
System.out.println(ss.foo(bs)); //true
System.out.println(ss.foo(bb)); //true

// no doubt about this one, am I right?
System.out.println(ss.foo(ss)); //false
}
}

Are Java and C++ using the same rules on method overriding/overloading?

14. Are Java and C++ using the same rules on method overriding/overloading?

A: Yes, they are basically the same.

Here are two equivalent class A/B in Java and C++. Compare carefully!

A.java

public class A {
public int mtdA(int x) {
return x + 3;
}
public int mtdB(int x, int y) {
return x + y;
}
}

class B extends A {
/*
$ javac A.java
A.java:23: mtdA(int) in B cannot override mtdA(int) in A;
attempting to use incompatible return type

found : double
required: int
public double mtdA(int x) {
^
1 error

public double mtdA(int x) {
return x + 0.2;
}
*/

// Compiled OK
public double mtdB(int x) {
return x + 0.2;
}
}

A.cpp

class A {
virtual int mtdA(int x) {
return x + 3;
};
virtual int mtdB(int x, int y) {
return x + y;
};
};

class B : public A {
// $ g++ A.cpp
// A.cpp:15: error: conflicting return type specified for `virtual double B::mtdA(int)'
// A.cpp:2: error: overriding `virtual int A::mtdA(int)'
/*
virtual double mtdA(int x) {
return x + 0.2;
};
*/


// OK
virtual double mtdB(int x) {
return x + 0.2;
};
};

Basic OO concepts

1. What is abstraction, what is encapsulation? What is the difference?

A: pine tree, apple tree, oak tree....
Abstraction: Tree
They are all trees.
Another way to express the same concepts is generalization and specialization.Capacitor, resister, wire, box, CRT, ...
Encapsulation: television
You don't care what are inside the black box, and how they interact with each other, as long as the television works.
Another way to express the same concepts is information hiding.

2. Why we need to construct a Vector first, then we can call addElement method?

A:

Since addElement(Object) is an instance method of class Vector. If we don't construct a Vector instance first, we cannot call instance method. You may askWhy we define addElement(Object) as instance method?
The answer should be obvious. You might use different Vectors in different parts of your application. Each Vector might add very different Objects. Define addElement as static (class) method does not make any sense.Give you a simple analog, you build a home, which is an instance of Home class, then add a TV to your living room. The addTV() method must be called after you construct your home, in other words, an instance method. Do you want you TV to be a class static variable and used by all home owners. No, you don't, and it is also impossible in reality too.

3. When an instance of subclass is created, is an instance of base class created also? How many objects are created during the process?

A:

Truth: FordCar ISA or "is a" Car.Think:
Which one is generalization/specialization? (Answer: Car is generalization)
Which one should be the base/sub class? (Answer: Car should be the base class)Fact: A FordCar was just made.Questions:
true/false? A Car was just made. (Answer: true)
How many objects (Cars) were created during this process? (Answer: one)
~~~~~~~~~~~~~~~~~~~~~There is only one object, but it contains all of the variables for the entire hierarchy. The reason being that the execution of a constructor causes calls to the constructors all the way back up the hierarchy to java.lang.Object - as each constructor executes, it gets the memory and sets the variables as required for that class.Where I can learn more about this topic?Reading some good Java / C++ / OO books, pay attention to the inheritance (or generalization/specialization) part. This is a big and extremely important topic. Yes, it is more important than learning Java. "Nothing can replace the technique of reading a good book from front to back." Here is an excellent free book:
Bruce Eckel's Thinking in Java, 2nd Edition

4. When we should use static methods, when we should use instance methods? Which one is better?

A: This should depend on what problem you need to solve. If the method is a long complicated scientific calculation, static method is the right way to do it. It makes the method available and easy to be used everywhere. That is exactly what Java Math class does. Go there, and see it.If the method is an individual behavior, such as putOnMakeUp() , it is very cultural/personal dependent. Putting it as static method would be almost meaningless. Of course, you can make a static putOnMakeUp() work fine if you are willing to pass 15 parameters to it, or pass a large struct including all cultural/personal information needed. Ah, we drive our time machine and go back to that magnificent procedural/structural paradigm era...

Inheritance/polymorphism/static/dynamic binding

1. Which one of the methods defined in interface or class with the same name will be called?

A: There is no method in interface can be called. Only the actual implementation of that method in class, which implements the interface mentioned, can be called.

2. Can subclass override methods that are declared static in the superclass?

A: No!

Methods a Subclass Cannot Override A subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). If you attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program:"
... "Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass. " Quotation from Overriding Methods of The Java Tutorial

When you should use this kind of "hide" technique?
Don't use it unless your boss gives you the assignment!!! Then you have no choice. Something legal does not mean it is recommended.
Copied from Sun's Code Conventions for the JavaTM Programming Language

Quote:

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

An interesting example here:

class Base {
static void doThis() {
System.out.println("Base static doThis()");
}

void doThat() {
System.out.println("Base instance doThat()");
}
}

class Sub extends Base {
// This is static method defined in the Sub class
// which does not override the Base doThis()
// only hide it.
// proved in the Test.main()
static void doThis() {
System.out.println("Sub static doThis()");
}

// This is instance method defined in the Sub class
// which does override the Base doThat()
void doThat() {
System.out.println("Sub instance doThat()");
}
}

public class Test {
public static void main(String[] args) {
// base is an instance of Sub
Base base = new Sub();
// legal cast both at compile and run time
Sub sub = (Sub)base;

base.doThis(); //Base static doThis()
base.doThat(); //Sub instance doThat()

sub.doThis(); //Sub static doThis()
sub.doThat(); //Sub instance doThat()

//Think why, try to understand the following concepts
//static binding : bind at compile time
//Dynamic binding : bind at run time
}
}

3. If subclass overrides the methods in super class, can subclass call the super class method?

A: Yes, you can. However, that is the subclass it self's choice. Outsider does not have this choice. You can see it clearly from the following example.

class Sup
{
void m1()
{
System.out.println("m1 in super");
}
}

class Sub extends Sup{
void m1()
{
super.m1();
System.out.println("m1 in sub");
}
}

public class T{
public static void main(String arg[])
{
new Sub().m1();
}
}

4. What is hide(a variable or a static method) means in computer languages (such as Java)? Should we do that?

A: Hide basic is a scope issue, when we have the same name in a smaller/more local scope, the smaller scope one will hide the upper ones. Here is a real life example: If you call your daughter Oprah Winfrey, then in your home, or in your daughter's kindergarten, people talk about Oprah Winfrey will refer to your daughter. The popular talk show host Oprah Winfrey will be hidden, unless you refer her as talk show host Oprah Winfrey. This example tells you three things: 1) Hiding is a scope issue. 2) Hiding cannot be complete/absolute. 3) Hiding is not good practice, since it causes confusion.My suggestion is don't call your daughter Oprah Winfrey, or don't practice hiding in your Java or C# or ... programming.The followings are two Java programs to illustrate the hiding concepts.

// hiding a instanse variable
class A {
int i = 3;
void method1() {
// this i will hide the member i
// bad coding practice
int i =5;
System.out.println(i); //5

// however, it can still be accessed by using this.i
System.out.println(this.i); //3
}
}

// hiding a static method
class A {
static void method1() {
System.out.println("in class A's static method1");
}
}

class B extends A {
// this will hide the static method1 in class A
static void method1() {
System.out.println("in class B's static method1");
}

public static void main(String[] args) {
// since we are in class B's scope
// call method1 directory will refer to B's method1,
// A's method1 is hidden
method1(); //in class B's static method1

// However, we still can call A's method1 even in B's territory
A.method1(); //in class A's static method1
}
}

5. Why the call to xy.amethod() calls amethod() in X instead of amethod() in Y in the following code?

class X {
public static void jout(String s) {
System.out.println(s);
}
static void amethod() {
jout("In X, amethod()");
}
}
class Y extends X {
static void amethod() {
jout("In Y, amethod()");
}
}
class Z extends Y {
static void amethod() {
jout("In Z. amethod()");
}
}
public class Test
public static void main (String[] args) {
X xy = new Y();
X xz = new Z();
Y yz = new Z();

xy.amethod();
xz.amethod();
yz.amethod();
}
}

A:

All three amethod()s here are static methods. static method is Class method, which has nothing to do with your object instantiation, dynamic binding, or polymorphism, whatsoever. In other words, the 3 line of codexy.amethod();
xz.amethod();
yz.amethod();can be replaced by the following 3 lines without causing any changes:X.amethod();
X.amethod();
Y.amethod();Since compiler interprets them exactly like this. xy and xz are reference type of X. yz is reference type of Y.Just remember "static is not dynamic" probably will help some.

6. When base class calls a method, how could the run time knows to called the overridden method in the derived class? The object is not even constructed yet.

A: Why? From the language theory, it is called deferred binding or dynamic binding or binding at run time. Compiler leaves the decision to run time. To make the decision at run time, you don't need the object built first. The only thing you need to know is the type of the actual object. In Java, the Class (not class) objects are loaded to the memory when it is first used. The run time knows it before any instance is constructed. In C++, the class methods virtual table is there for the same purpose. As you probably know, in C++, method are default to static binding, only virtual methods are dynamically bound. In Java, methods are default to dynamic binding, unless they are declared as static, private, or final.

7. Does private method defined in base class participate polymorphism, if the derived class has a same name method?

A: No, private method defined in any class will never participate polymorphism.

If you want to confuse yourself, your boss, and your co-worker (and you might get fired for that too), and define same name private methods along the hierarchy, the compiler will treat them individually, as no relationship at all. If you call private method in your class, the method will be bound at compile time (not runtime).See the following example:

// Base.java
public class Base {
public static void main(String[] args) {
Sub sub = new Sub();
System.out.println(sub.g()); // 20, not -100
}

private int f() {
return 20;
}

protected int g() {
// statc bound with Base.f()
// compiler does not know any derived class has f() or not
// and does not care either
return f();
}
}

class Sub extends Base {
// f() here has nothing to do with Base.f()!!!
// In real world programming, never do this!!!
public int f() {
return -100;
}
}

8. What kind of Java methods does not participate polymorphism?

A: Polymorphism for Java method is always there except the following three situations: 1) The method is declared as final
2) The method is declared as private
3) The method is declared as static In those three cases, static binding will be performed by the compiler. Compiler does not have the knowledge, nor care about the method was, is, or will be overridden by none, one, or many subclass(es). The decision is made by the runtime, which is called dynamic binding. See next question, which discuss the same topic in a different angle.

9. What methods in Java is static bound? Please compare with c++ too.

A: static, private, final methods are static bound.

Those 3 methods does not participate polymorphism. In other words, they are not allowed to be overridden. In c++, virtual function can be overridden, others not.
virtual in C++ --> nothing in Java
nothing in C++ --> final in Java

10. Do we need an object reference to call a static method?

A: No, not quite. See the following example.

MyClass t = null;
// the following two are equivalent
t.aStaticMethod();//OK
MyClass .aStaticMethod();//perfect

It is the class type; it doesn't need a "reference variable ". You can use a object reference to call a static method, of course, provided it has the right type. However, you don't have to. The above example clearly said that. t is not referring to anything but null, but has a MyClass type. If you know the old procedural programming, static method is equivalent to that, except in Java, we have a class Class. In Java, we can write magnificent old procedural program without any OO concepts by using all static methods. (No object reference at all).

11. What is the calling order of constructors along the hierarchy, from child up, or from ancestor down?

A:The order is from child up. However, the super() is always implicitly or explicitly called as the first statement before any code in the child being executed. This might cause some confusion here. If you put a print statement in each of the constructor, the ancestor one will be output first. The following code will illustrate how it works.This is called LIFO, which one is called the first, will be finished the last. The child is called first, but it call its parent as the first statement, and the immediate parent will call its parent as the first statement too, and so on. Therefore the far ancestor, which is the Object will finish its constructor the first, then its immediate child, and so on. That is why the print statements will finish from the ancestor down. The calling stack is working this way. Last In, First Out (LIFO)

public class Child extends Parent {
public Child() {
// super() is implicitly called here
System.out.println("Child");
}
public static void main(String[] args) {
new Child();
}
}
class Parent extends GrantParent{
public Parent() {
// super is explicitly called here
super("Mother's parent");
System.out.println("Parent");
}
}
class GrantParent{
public GrantParent(String sWhosPrt) {
System.out.println("GrantParent: " + sWhosPrt);
}
}

// output
// GrantParent: Mother's parent
// Parent
// Child

12.What is the static, instance initialization, constructor header, and code execution order? Why the radius prints out as 0 instead of 1 in the following code?

//Ex from Bruce Eckel's Book "Thinking In Java"
abstract class Glyph {
abstract void draw();
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println(
"RoundGlyph.RoundGlyph(), radius = " + radius);
}
void draw() {
System.out.println("RoundGlyph.draw(), radius = " + radius);
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
//Output is:
//Glyph() before draw()
//RoundGlyph.draw(), radius = 0
//Glyph() after draw()
//RoundGlyph.RoundGlyph(), radius=5

A:

The execution order is:

  1. static variable initialization and static block executes only once when the class is loaded to the memory by JVM.

  2. When constructor is called, the constructor header executes first before instance variable initialization and instance block execution.

  3. instance variable initialization and instance block execute.

  4. Code in the constructor executes.

This is exactly what happened in your example (except no static stuff). The RoundGlyph constructor header executes first, which implicitly called default constructor of Glyph super(). The radius has not initialized yet; the value is 0. Then the radius is initialized to 1. Then the code in the RoundGlyph() constructor executes and changed radius value to 5. This kind of hair splitting trick, we'd better not know it, or don't tell your boss you know it. I probably learned from Mughal and Rasmussen's book, which I gave away after the test. Today, I wrote a little code to prove that I remembered it right. I usually do not pay a lot of attention to what is going to be on the SCJP test like Marcus Green does, however, it is quite safe to say, questions like this will NOT be on your test.Warning: Don't try this at work!

13. Constructor or not constructor? Please explain why the output of the following code is null?

public class My {
String s;
public void My(){
s = "Constructor";
}
public void go() {
System.out.println(s);
}
public static void main(String args[]) {
My m = new My();
m.go();
}
}
//output : null

A:

public void My() is not a constructor. The default constructor is called. s is still null by default.Constructor is not supposed to have a return type, even a void type. If it has, then it is not a constructor, but a method, which happens to have the same name as the class name. This is a tricky question just for testing your Java knowledge. Using class name as your method name is not considered as good code practice at work!

14. Base b = new SubBase(); How the compiler/Runtime to resolve the addresses of methods calls, Fields?

// TestBinding.java
class Base {
String s = "string in Base";
void init(){
System.out.println("init() call in Base");

}
}
class SubBase extends Base{
String s = "string in SubBase";
void init(){
System.out.println("init() call in SubBase");

}
}

public class TestBinding {
public static void main(String[] args) {
Base b = new SubBase();

// static binding on instance fields
System.out.println(b.s); //string in Base

// dynamic binding on instance methods
b.init(); //init() call in SubBase
}
}

A:

The above example plus comments actually told everything you need to know.When a field of an object is accessed using a reference, it is the type of the reference declared, which determines, which variable will actually be accessed.
Static Binding -- Bind at compile time: The addressing of the field is determined at compile time.

When a method is invoked on an object using a reference, it is the class of the current object denoted by the reference, not the type of the reference that determines which method implementation will be executed.
Dynamic Binding -- Bind at run time: The addressing of the method is determined at run time.Notice to C++ programmer: In C++, only virtual methods (functions) are bound at run time. In Java, methods are default to dynamic binding, unless they are declared as static, private, or final.

15. If I remove the init() from the Base in the above question, I got a compile error: ""method init() not found class Base". Why?

A: It will make you understand dynamic binding or polymorphism much better. If you remove init() from Base class, you actually take init() out of the polymorphism between Base and SubBase class. Compiler only know b is refer to a Base class, which does not have the method init(), compile time error!!! The Java compiler does not know, nor care who, when, where, how some other class is going to extends the Base class, there are some different named methods defined in them. And one of them happens to be called init(). They are totally irrelevant to the Base class.Remember SubBase ISA Base. Compiler does not care which child/grandchild/grand grandchild down the hierarchy b is actually referring to, and which init() it should call. However, they all have an init() (polymorphism). It is a runtime decision. Dynamic Binding.Dynamic binding, or binding at runtime only for those methods defined in Base class, either inherited or overridden by the subclass. The override can be already happened now or will happen in the future, the compiler does not care.

16. Here is another tricky code example for you to cracking on! Cover up the explanation to see you can explain it or not.

class Base {
int x = 3;
public Base (){}
public void showx(){
System.out.println("In base, x = " + x);
}
}
class SubBase extends Base {
int x = 2;
public void showx() {
System.out.println("In SubBase, x = " + x);
}
}

public class BindingTest {

public static void main (String args[]){
Base b = new SubBase();
b.showx();
System.out.println("In Main, the (?) x = " + b.x);
}
}

// output
/*
In SubBase, x = 2
In Main, the (?) x = 3
*/

A: Danger: Do not try this at work!

1) In main(), b.x is bound at compile time, since b is declared as Base, x is 3.
2) In main(), b.showx() is bound at runtime, since b is actually a SubBase. the SubBase.showx() will be called.
3) In SubBase, call of x in method showx() is bound at the compile time, in class SubBase, x is 2. This is a typical tricky question, good for you cracking the concepts, but never write it on your job. You would be fired for that, no kidding!!!