Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Search Your Question

Showing posts with label Java Interview Questions. Show all posts
Showing posts with label Java Interview Questions. Show all posts

Wednesday, July 23, 2008

Java Technical Questions

What modifiers may be used with top-level class?

public, abstract and final can be used for top-level class.



What are inner class and anonymous class?

Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.

Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.




What is a package?


A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.



What is a reflection package?

java. lang. reflect package has the ability to analyze itself in runtime.



What is interface and its use?

Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object’s programming interface without revealing the actual body of the class.



What is an abstract class?

An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.



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 a cloneable interface and how many methods does it contain?

It is not having any method because it is a TAGGED or MARKER interface.



What is the difference between abstract class and interface?

a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can’t have subclasses.




Can you have an inner class inside a method and what variables can you access?

Yes, we can have an inner class inside a method and final variables can be accessed.



What is the difference between String and String Buffer?

a) String objects are constants and immutable whereas StringBuffer objects are not.

b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.

Some Java Job Interview Questions

What is Garbage Collection and how to call it explicitly?

When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.


What is finalize() method?

finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.


What are Transient and Volatile Modifiers?

Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.



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 difference between overloading and overriding?

a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.



What is meant by Inheritance and what are its advantages?

Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.



What is the difference between this() and super()?

this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.



What is the difference between superclass and subclass?

A super class is a class that is inherited whereas sub class is a class that does the inheriting.

Fundamental Java interview questions

Why do you prefer Java?

Answer: write once ,run anywhere.


2. Name some of the classes which provide the functionality of collation?

Answer: collator, rulebased collator, collationkey, collationelement iterator.

3. Awt stands for? and what is it?

Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated set of classes to manage user interface components.

4. why a java program can not directly communicate with an ODBC driver?

Answer: Since ODBC API is written in C language and makes use of pointers which Java can not support.


5. Are servlets platform independent? If so Why? Also what is the most common application of servlets?

Answer: Yes, Because they are written in Java. The most common application of servlet is to access database and dynamically construct HTTP response

Java Web programming questions

What is a Servlet?

Answer: Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client side) to answer client requests.


What advantages does CMOS have over TTL(transitor transitor logic)? (ALCATEL)

Answer:

* low power dissipation
* pulls up to rail
* easy to interface


How is Java unlike C++? (Asked by Sun)

Answer:

Some language features of C++ have been removed. String manipulations in Java do not allow for buffer overflows and other typical attacks. OS-specific calls are not advised, but you can still call native methods. Everything is a class in Java. Everything is compiled to Java bytecode, not executable (although that is possible with compiler tools).


What is HTML (Hypertext Markup Language)?

Answer:

HTML (HyperText Markup Language) is the set of "markup" symbols or tags inserted in a file intended for display on a World Wide Web browser. The markup tells the Web browser how to display a Web page’s words and images for the user.

Define class.

Answer: A class describes a set of properties (primitives and objects) and behaviors (methods).

Advanced Java interview questions


1:In Java, what is the difference between an Interface and an Abstract class?

A: An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

2: Can you have virtual functions in Java? Yes or No. If yes, then what are virtual functions?

A: Yes, Java class functions are virtual by default. Virtual functions are functions of subclasses that can be invoked from a reference to their superclass. In other words, the functions of the actual object are called when a function is invoked on the reference to that object.


3:Write a function to reverse a linked list p in C++?

A:

Link* reverse_list(Link* p)
{
if (p == NULL)
return NULL;

Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
{
Link* t = p->next;
p->next = h;
h = p;
p = t;
}

return h;
}

4:In C++, what is the usefulness of Virtual destructors?

A: Virtual destructors are neccessary to reclaim memory that were allocated for objects in the class hierarchy. If a pointer to a base class object is deleted, then the compiler guarantees the various subclass destructors are called in reverse order of the object construction chain.

5:What are mutex and semaphore? What is the difference between them?

A:A mutex is a synchronization object that allows only one process or thread to access a critical code block. A semaphore on the other hand allows one or more processes or threads to access a critial code block. A semaphore is a multiple mutex.

Advanced enterprise Java interview questions

Q1) What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q2) Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.


Q3) How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components. On the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business logic components.

Q4) In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures. It helps them to choose design alternatives that make a system reusuable and avoid alternatives that compromise reusability through proven techniques as design patterns.

Q5) Describe 3-Tier Architecture in enterprise application development.

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application.

Java and networking interview questions




1: What is a JavaBean? (asked by Lifescan inc)

ANS: JavaBeans are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java. They are similar to Microsoft’s ActiveX components, but designed to be platform-neutral, running anywhere there is a Java Virtual Machine (JVM).

2: What are the seven layers(OSI model) of networking? (asked by Caspio.com)

ANS: 1.Physical, 2.Data Link, 3.Network, 4.Transport, 5.Session, 6.Presentation and 7.Application Layers.


3: What are some advantages and disadvantages of Java Sockets? (asked by Arashsoft.com)

ANS:
Advantages of Java Sockets:

Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.

Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Disadvantages of Java Sockets:

Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.


4: What is the difference between a NULL pointer and a void pointer? (asked by Lifescan inc)

ANS: A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does).


5: What is encapsulation technique? (asked by Microsoft)

ANS: Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state.

JSP interview questions

Q: 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.

Q: 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.

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

Q: 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).

Q: 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.

courtesy:http://www.crackthecampus.com

Software Engineering related Java questions

1: What is the three tier model?

Ans: It is the presentation, logic, backend


2: Why do we have index table in the database?

Ans: Because the index table contain the information of the other tables. It will
be faster if we access the index table to find out what the other contain.


3: Give an example of using JDBC access the database.

Ans:
try

{

Class.forName("register the driver");

Connection con = DriverManager.getConnection("url of db", "username","password");

Statement state = con.createStatement();

state.executeUpdate("create table testing(firstname varchar(20), lastname varchar(20))");

state.executeQuery("insert into testing values(’phu’,'huynh’)");

state.close();

con.close();

}

catch(Exception e)

{

System.out.println(e);

}



4: What is the different of an Applet and a Java Application

Ans: The applet doesn’t have the main function


5: How do we pass a reference parameter to a function in Java?


Ans: Even though Java doesn’t accept reference parameter, but we can
pass in the object for the parameter of the function.
For example in C++, we can do this:

void changeValue(int& a)
{
a++;
}
void main()
{
int b=2;
changeValue(b);
}

however in Java, we cannot do the same thing. So we can pass the
the int value into Integer object, and we pass this object into the
the function. And this function will change the object.


courtesy:http://www.crackthecampus.com

Java and Perl Web programming interview questions

Q1: How can we store the information returned from querying the database? and if it is too big, how does it affect the performance?
In Java the return information will be stored in the ResultSet object. Yes, if the ResultSet is getting big, it will slow down the process and the performance as well. We can prevent this situation by give the program a simple but specific query statement.




Q2: What is index table and why we use it?
Index table are based on a sorted ordering of the values. Index table provides fast access time when searching.




Q3: In Java why we use exceptions?
Java uses exceptions as a way of signaling serious problems when you execute a program. One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors.




Q4: Write a code in Perl that makes a connection to Database.

#!/usr/bin/perl
#makeconnection.pl

use DBI;
my $dbh = DBI->connect('dbi:mysql:test','root','foo')||die "Error opening database:
$DBI::errstrn";
print"Successful connect to databasen";

$dbh->disconnect || die "Failed to disconnectn";



Q5: Write a code in Perl that select all data from table Foo?

#!usr/bin/perl
#connect.pl

use DBI;
my ($dbh, $sth, $name, $id);
$dbh= DBI->connect('dbi:mysql:test','root','foo')
|| die "Error opening database: $DBI::errstrn";
$sth= $dbh->prepare("SELECT * from Foo;")
|| die "Prepare failed: $DBI::errstrn";
$sth->execute()
|| die "Couldn't execute query: $DBI::errstrn";
while(( $id, $name) = $sth->fetchrow_array)
{
print "$name has ID $idn";
}
$sth->finish();

$dbh->disconnect
|| die "Failed to disconnectn";


Java Programming Interview Questions

Q1: What are the advantages of OOPL?

Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.

Q2: What do mean by polymorphisum, inheritance, encapsulation?

Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.

Q3: What do you mean by static methods?

Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.

Q4: What do you mean by virtual methods?

Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.

Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level.

Ans: SELECT Student.name, Student.SID
FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = "freshman"
AND Student.Course = 3;

Q6: What are the disadvantages of using threads?

Ans: DeadLock.

Q7: Write the Java code to declare any constant (say gravitational constant) and to get its value?

Ans: Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}


Q8: What do you mean by multiple inheritance in C++ ?

Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.

Q9: Can you write Java code for declaration of multiple inheritance in Java ?

Ans: Class C extends A implements B
{
}

courtesy:http://www.crackthecampus.com


Miscellaneous collection of Java interview questions

1. What is the difference between an Abstract class and Interface ?
2. What is user defined exception ?
3. What do you know about the garbage collector ?
4. What is the difference between C++ & Java ?
5. Explain RMI Architecture?
6. How do you communicate in between Applets & Servlets ?
7. What is the use of Servlets ?
8. What is JDBC? How do you connect to the Database ?
9. In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
10. What is the difference between Process and Threads ?
11. What is the difference between RMI & Corba ?
12. What are the services in RMI ?
13. How will you initialize an Applet ?
14. What is the order of method invocation in an Applet ?
15. When is update method called ?
16. How will you pass values from HTML page to the Servlet ?
17. Have you ever used HashTable and Dictionary ?
18. How will you communicate between two Applets ?
19. What are statements in JAVA ?
20. What is JAR file ?
21. What is JNI ?
22. What is the base class for all swing components ?
23. What is JFC ?
24. What is Difference between AWT and Swing ?
25. Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ?
26. How does thread synchronization occurs inside a monitor ?
27. How will you call an Applet using a Java Script function ?
28. Is there any tag in HTML to upload and download files ?
29. Why do you Canvas ?
30. How can you push data from an Applet to Servlet ?
31. What are 4 drivers available in JDBC ?
32. How you can know about drivers and database information ?
33. If you are truncated using JDBC, How can you know ..that how much data is truncated ?
34. And What situation , each of the 4 drivers used ?
35. How will you perform transaction using JDBC ?
36. In RMI, server object first loaded into the memory and then the stub reference is sent to the client ? or whether a stub reference is directly sent to the client ?
37. Suppose server object is not loaded into the memory, and the client request for it , what will happen?
38. What is serialization ?
39. Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?
40. What is difference RMI registry and OSAgent ?
41. To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message should be sent to the client ? What will you do for achieving for this ?
42. What are the benefits of Swing over AWT ?
43. Where the CardLayout is used ?
44. What is the Layout for ToolBar ?
45. What is the difference between Grid and GridbagLayout ?
46. How will you add panel to a Frame ?
47. What is the corresponding Layout for Card in Swing ?
48. What is light weight component ?
49. Can you run the product development on all operating systems ?
50. What is the webserver used for running the Servlets ?
51. What is Servlet API used for connecting database ?
52. What is bean ? Where it can be used ?
53. What is difference in between Java Class and Bean ?
54. Can we send object using Sockets ?
55. What is the RMI and Socket ?
56. How to communicate 2 threads each other ?
57. What are the files generated after using IDL to Java Compilet ?

Java networking and algoritms questions



1. What is the protocol used by server and client ?
2. Can I modify an object in CORBA ?
3. What is the functionality stubs and skeletons ?
4. What is the mapping mechanism used by Java to identify IDL language ?
5. Diff between Application and Applet ?
6. What is serializable Interface ?
7. What is the difference between CGI and Servlet ?
8. What is the use of Interface ?
9. Why Java is not fully objective oriented ?
10. Why does not support multiple Inheritance ?
11. What it the root class for all Java classes ?
12. What is polymorphism ?
13. Suppose If we have variable ‘ I ‘ in run method, If I can create one or more thread each thread will occupy a separate copy or same variable will be shared ?
14. In servlets, we are having a web page that is invoking servlets username and password ? which is checked in the database ? Suppose the second page also If we want to verify the same information whether it will connect to the database or it will be used previous information?
15. What are virtual functions ?
16. Write down how will you create a binary Tree ?
17. What are the traverses in Binary Tree ?
18. Write a program for recursive Traverse ?
19. What are session variable in Servlets ?
20. What is client server computing ?
21. What is Constructor and Virtual function? Can we call Virtual function in a constructor ?
22. Why we use OOPS concepts? What is its advantage ?
23. What is the middleware ? What is the functionality of Webserver ?
24. Why Java is not 100 % pure OOPS ? ( EcomServer )
25. When we will use an Interface and Abstract class ?
26. What is an RMI?
27. How will you pass parameters in RMI ? Why u serialize?
28. What is the exact difference in between Unicast and Multicast object ? Where we will use ?
29. What is the main functionality of the Remote Reference Layer ?
30. How do you download stubs from a Remote place ?
31. What is the difference in between C++ and Java ? can u explain in detail ?
32. I want to store more than 10 objects in a remote server ? Which methodology will follow ?
33. What is the main functionality of the Prepared Statement ?
34. What is meant by static query and dynamic query ?
35. What are the Normalization Rules ? Define the Normalization ?
36. What is meant by Servlet? What are the parameters of the service method ?
37. What is meant by Session ? Tell me something about HTTPSession Class ?
38. How do you invoke a Servlet? What is the difference in between doPost and doGet methods ?
39. What is the difference in between the HTTPServlet and Generic Servlet ? Explain their methods ? Tell me their parameter names also ?
40. Have you used threads in Servlet ?
41. Write a program on RMI and JDBC using StoredProcedure ?
42. How do you sing an Applet ?
43. In a Container there are 5 components. I want to display the all the components names, how will you do that one ?
44. Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
45. Tell me the latest versions in JAVA related areas ?
46. What is meant by class loader ? How many types are there? When will we use them ?
47. How do you load an Image in a Servlet ?
48. What is meant by flickering ?
49. What is meant by distributed Application ? Why we are using that in our applications ?
50. What is the functionality of the stub ?
51. Have you used any version control ?
52. What is the latest version of JDBC ? What are the new features are added in that ?
53. Explain 2 tier and 3 -tier Architecture ?
54. What is the role of the webserver ?
55. How have you done validation of the fields in your project ?
56. What is the main difficulties that you are faced in your project ?
57. What is meant by cookies ? Explain?

Programming related Java questions

What is a class?

A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.


What is a object?

An object is a software bundle of variables and related methods.An instance of a class depicting the state and behavior at that particular time in real world.

What is a method?
Encapsulation of a functionality which can be called to perform specific tasks.

What is encapsulation? Explain with an example.

Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object


What is inheritance? Explain with an example.

Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects.


What is polymorphism? Explain with an example.

In object-oriented programming, polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language

Is multiple inheritance allowed in Java?

No, multiple inheritance is not allowed in Java.


What is interpreter and compiler?

Java interpreter converts the high level language code into a intermediate form in Java called as bytecode, and then executes it, where as a compiler converts the high level language code to machine language making it very hardware specific

What is JVM?

The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)


What are the different types of modifiers?

There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other are final and static.


What are the access modifiers in Java?

There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly.


What is a wrapper class?

They are classes that wrap a primitive data type so it can be used as a object


What is a static variable and static method? What’s the difference between two?

The modifier static can be used with a variable and method. When declared as static variable, there is only one variable no matter how instances are created, this variable is initialized when the class is loaded. Static method do not need a class to be instantiated to be called, also a non static method cannot be called from static method.


What is garbage collection?

Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore.

What is abstract class?

Abstract class is a class that needs to be extended and its methods implemented, aclass has to be declared abstract if it has one or more abstract methods.


What is meant by final class, methods and variables?

This modifier can be applied to class method and variable. When declared as final class the class cannot be extended. When declared as final variable, its value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the same object, internal attributes of the object can be changed.


What is interface?

Interface is a contact that can be implemented by a class, it has method that need implementation.


What is method overloading?

Overloading is declaring multiple method with the same name, but with different argument list.


What is method overriding?

Overriding has same method name, identical arguments used in subclass.


What is singleton class?

Singleton class means that any given time only one instance of the class is present, in one JVM.


What is the difference between an array and a vector?

Number of elements in an array are fixed at the construction time, whereas the number of elements in vector can grow dynamically.


What is a constructor?

In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed.


What is casting?

Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data.


What is the difference between final, finally and finalize?

The modifier final is used on class variable and methods to specify certain behaviour explained above. And finally is used as one of the loop in the try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When the garbage collector is ready to release the storage ed for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the objects memory. So finalize( ), gives you the ability to perform some important cleanup at the time of garbage collection.


What is are packages?

A package is a collection of related classes and interfaces providing access protection and namespace management.


What is a super class and how can you call a super class?

When a class is extended that is derived from another class there is a relationship is created, the parent class is referred to as the super class by the derived class that is the child. The derived class can make a call to the super class using the keyword super. If used in the constructor of the derived class it has to be the first statement.


What is meant by a Thread?

Thread is defined as an instantiated parallel process of a given program.


What is multi-threading?

Multi-threading as the name suggest is the scenario where more than one threads are running.


What are two ways of creating a thread? Which is the best way and why?

Two ways of creating threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run method of a different class can be called which implements the interface Runnable, and the then implement the run() method. The latter one is mostly used as first due to Java rule of only one class inheritance, with implementing the Runnable interface that problem is sorted out.


What is deadlock?

Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread. In Java, this resource is usually the object lock obtained by the synchronized keyword.


What are the three types of priority?

MAX_PRIORITY which is 10, MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.


What is the use of synchronizations?

Every object has a lock, when a synchronized keyword is used on a piece of code the, lock must be obtained by the thread first to execute that code, other threads will not be allowed to execute that piece of code till this lock is released.

Some more JSP interview questions

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.





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.





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.





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.




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.




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

.


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.




What is a Expression?

Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.



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.



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 .



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




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.

Java Related Interview Questions

Hi Friends,

I am putting some needful stuff related to Java.

Fundamental Java Job Interview Questions

Java Technical Interview Questions

Java Job Interview Questions

Advanced Java Interview Questions

Java Web Programming Questions

Java Programming Interview Questions - 1

Java Programming Interview Questions - 2

Java Networking and Algorithms Questions

Advanced Enterprise Java Interview Questions

Java And Networking Interview Questions

JSP Interview Questions - 1

JSP Interview Questions - 2

Software Engineering Related Java Questions

Java And Perl Web Programming Interview Questions

Miscellaneous Collection of Java Interview Questions

Thursday, May 29, 2008

Java Interview Questions

Q:

What is the difference between an Interface and an Abstract class?

A:

An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q:

What is the purpose of garbage collection in Java, and when is it used?

A:

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q:

Describe synchronization in respect to multithreading.

A:

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.


Q:

Explain different way of using thread?

A:

The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.


Q:

What are pass by reference and passby value?

A:

Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

Q:

What is HashMap and Map?

A:

Map is Interface and Hashmap is class that implements that.

Q:

Difference between HashMap and HashTable?

A:

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Q:

Difference between Vector and ArrayList?

A:

Vector is synchronized whereas arraylist is not.

Q:

Difference between Swing and Awt?

A:

AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Q:

What is the difference between a constructor and a method?

A:

A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q:

What is an Iterator?

A:

Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.


Q:

State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

A:

public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package
.


Q:

What is an abstract class?

A:

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.


Q:

What is static in java?

A:

Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.


Q:

What is final?

A:

A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).




Q:

What if the main method is declared as private?




A:

The program compiles properly but at runtime it will give "Main method not public." message.


Q:

What if the static modifier is removed from the signature of the main method?

A:

Program compiles. But at runtime throws an error "NoSuchMethodError".


Q:

What if I write static public void instead of public static void?

A:

Program compiles and runs properly.




Q:

What if I do not provide the String array as the argument to the method?

A:

Program compiles but throws a runtime error "NoSuchMethodError".


Q:

What is the first argument of the String array in main method?

A:

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.


Q:

If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?

A:

It is empty. But not null.


Q:

How can one prove that the array is not null but empty using one line of code?

A:

Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

Q:

What environment variables do I need to set on my machine in order to be able to run Java programs?

A:

CLASSPATH and PATH are the two variables.

Q:

Can an application have multiple classes having main method?

A:

Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

Q:

Can I have multiple main methods in the same class?

A:

No the program fails to compile. The compiler says that the main method is already defined in the class.

Q:

Do I need to import java.lang package any time? Why ?

A:

No. It is by default loaded internally by the JVM.

Q:

Can I import same package/class twice? Will the JVM load the package twice at runtime?

A:

One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q:

What are Checked and UnChecked Exception?

A:

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. 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.

Q:

What is Overriding?

A:

When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

Q:

What are different types of inner classes?

A:

Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Q:

Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

A:

Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

Q:

Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

A:

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.

Q:

What is the difference between declaring a variable and defining a variable?

A:

In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

Q:

What is the default value of an object reference declared as an instance variable?

A:

null unless we define it explicitly.




Q:

Can a top level class be private or protected?

A:

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 as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

Q:

What type of parameter passing does Java support?

A:

In Java the arguments are always passed by value .

Q:

Primitive data types are passed by reference or pass by value?

A:

Primitive data types are passed by value.

Q:

Objects are passed by value or by reference?

A:

Java only supports pass 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 .

Q:

What is serialization?

A:

Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

Q:

How do I serialize an object to a file?

A:

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.

Q:

Which methods of Serializable interface should I implement?

A:

The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

Q:

How can I customize the seralization process? i.e. how can one have a control over the serialization process?

A:

Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

Q:

What is the common usage of serialization?

A:

Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.

Q:

What is Externalizable interface?

A:

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.

Q:

When you serialize an object, what happens to the object references included in the object?

A:

The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

Q:

What one should take care of while serializing the object?

A:

One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

Q:

What happens to the static fields of a class during serialization?

A:

There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of ay particular state state.
2. Base class fields are only hendled if the base class itself is serializable.
3. Transient fields.