Saturday, 31 January 2009
Interview Questions on Java
The program compiles properly but at runtime it will give “Main method not public.” message.
What is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.
If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()
What is Byte Code?
Or
What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.
Expain the reason for each keyword of public static void main(String args[])?
public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.
What are the differences between == and .equals() ?
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables - the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
public class EqualsTest {
public static void main(String[] args) {
String s1 = “abc”;
String s2 = s1;
String s5 = “abc”;
String s3 = new String(”abc”);
String s4 = new String(”abc”);
System.out.println(”== comparison : ” + (s1 == s5));
System.out.println(”== comparison : ” + (s1 == s2));
System.out.println(”Using equals method : ” + s1.equals(s2));
System.out.println(”== comparison : ” + s3 == s4);
System.out.println(”Using equals method : ” + s3.equals(s4));
}
}
Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true
What if the static modifier is removed from the signature of the main method?
Or
What if I do not provide the String array as the argument to the method?
Program compiles. But at runtime throws an error “NoSuchMethodError”.
Why oracle Type 4 driver is named as oracle thin driver?
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.
What is the difference between final, finally and finalize? What do you understand by the java final keyword?
Or
What is final, finalize() and finally?
Or
What is finalize() method?
Or
What is the difference between final, finally and finalize?
Or
What does it mean that a class or member is final?
o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
Why there are no global variables in Java?
Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.
How to convert String to Number in java program?
The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
What is the difference between a while statement and a do statement?
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.
What is the Locale class?
The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.
Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places
What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
Example
int i = 1000;
long j = i; //Implicit casting
Is sizeof a keyword in java?
The sizeof operator is not a keyword.
What is a native method?
A native method is a method that is implemented in a language other than Java.
In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.
What are Encapsulation, Inheritance and Polymorphism
Or
Explain the Polymorphism principle. Explain the different forms of Polymorphism.
Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
What is explicit casting?
Explicit casting in the process in which the complier are specifically informed to about transforming the object.
Example
long i = 700.20;
int j = (int) i; //Explicit casting
What is the Java Virtual Machine (JVM)?
The Java Virtual Machine is software that can be ported onto various hardware-based platforms
What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy
What are Java Access Specifiers?
Or
What is the difference between public, private, protected and default Access Specifiers?
Or
What are different types of access modifiers?
Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package
Which class is the superclass of every class?
Object.
Name primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
What is the difference between static and non-static variables?
Or
What are class variables?
Or
What is static in java?
Or
What is a static method?
A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.
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 non-static method. In other words, you can’t change a static method into an instance method in a subclass.
Non-static variables take on unique values with each object instance.
What is the difference between the boolean & operator and the && operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
What if I write static public void instead of public static void?
Program compiles and runs properly.
What is the difference between declaring a variable and defining a variable?
In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String (”bob”); Or String s = “bob”; are both definitions.
What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.
Explain the Encapsulation principle.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
What do you understand by a variable?
Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program.
What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
What do you understand by casting in java language? What are the types of casting?
The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.
How can one prove that the array is not null but empty?
Print array.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 array.length.
Can an application have multiple classes having main method?
Yes. 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.
When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
Can I have multiple main methods in the same class?
We can have multiple overloaded main methods but there can be only one main method with the following signature :
public static void main(String[] args) {}
No the program fails to compile. The compiler says that the main method is already defined in the class.
Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.
How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:
int a=5,b=10;a=a+b; b=a-b; a=a-b;
An other approach to the same question
You use an XOR swap.
for example:
int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
What is data encapsulation?
Encapsulation may be used by creating ‘get’ and ’set’ methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
}
What is difference between String and StringTokenizer?
A StringTokenizer is utility class used to break up string.
Example:
StringTokenizer st = new StringTokenizer(”Hello World”);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output:
Hello
World
Saturday, 6 September 2008
Which containers use a border layout as their default layout window?
Thursday, 19 June 2008
Advanced Java interview questions
Q: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.
Q: 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.
Q: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;
}
Q: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.
Q: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
1) 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.
2) 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.
>
3) 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.
4) 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.
5) 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
QUESTION: What is a JavaBean? (asked by Lifescan inc)
ANSWER: 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).
QUESTION: What are the seven layers(OSI model) of networking? (asked by Caspio.com)
ANSWER: 1.Physical, 2.Data Link, 3.Network, 4.Transport, 5.Session, 6.Presentation and 7.Application Layers.
QUESTION: What are some advantages and disadvantages of Java Sockets? (asked by Arashsoft.com)
ANSWER:
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.
QUESTION: What is the difference between a NULL pointer and a void pointer? (asked by Lifescan inc)
ANSWER: 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).
QUESTION: What is encapsulation technique? (asked by Microsoft)
ANSWER: 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.
C++ interview questions, some Java
2. What methods can be overridden in Java? In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.
3. In C, what is the difference between a static variable and global variable? A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files).
4. In C, why is the void pointer useful? When would you use it? The void pointer is useful becuase it is a generic pointer that any pointer can be cast into and back again without loss of information.
5. What are the defining traits of an object-oriented language? The defining traits of an object-oriented langauge are:
* encapsulation
* inheritance
* polymorphism
Java software engineering interview questions
Question 1: What is the three tier model?
Answer: It is the presentation, logic, backend
Question 2: Why do we have index table in the database?
Answer: 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.
Question 3: Give an example of using JDBC access the database.
Answer:
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);
}
Question 4: What is the different of an Applet and a Java Application
Answer: The applet doesn’t have the main function
Question 5: How do we pass a reference parameter to a function in Java?
Answer: 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.
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 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.
Q1: 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);
}
}
Q2: 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.
Q3: Can you write Java code for declaration of multiple inheritance in Java ?
Ans: Class C extends A implements B
{
}
Java Swing interview questions
1) Can a class be it’s own event handler? Explain how to implement this.
Answer: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the actionPerformed method, put the code to perform when the button is pressed.
2) Why does JComponent have add() and remove() methods but Component does not?
Answer: because JComponent is a subclass of Container, and can contain other components and jcomponents.
3) How would you create a button with rounded edges?
Answer: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how would I do that?
Answer: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate. (I don’t know it offhand, but I think it’s "com.sun.ui.motiflookandfeel.MotifTabbedPaneUI" - anything simiar is a good answer.)
5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?
Answer: The Font Class is used to render ‘glyphs’ - the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent)
6) What class is at the top of the AWT event hierarchy?
Answer: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a while.
7) Explain how to render an HTML page using only Swing.
Answer: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane.
8) How would you detect a keypress in a JComboBox?
Answer: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ - but the right answer is ‘add a KeyListener to the JComboBox’s editor component.’
9) Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
10) In what context should the value of Swing components be updated directly?
A: Swing components should be updated directly only in the context of callback methods invoked from the event dispatch thread. Any other context is not thread safe?
11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?
A: I want to update a Swing component but I’m not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when the update occurs, I’d use invokeLater.
12) If your UI seems to freeze periodically, what might be a likely reason?
A: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is taking a long time to execute thereby blocking the event dispatch thread from processing other UI events.
13) Which Swing methods are thread-safe?
A: The only thread-safe methods are repaint(), revalidate(), and invalidate()
14) Why won’t the JVM terminate when I close all the application windows?
A: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM.
Java on Oracle interview questions
- What is JServer and what is it used for? Oracle JServer Option is a Java Virtual Machine (Java VM) which runs within the Oracle database server’s address space. Oracle also provides a JServer Accelerator to compile Java code natively. This speeds up the execution of Java code by eliminating interpreter overhead.
- How does one install the Oracle JServer Option?Follow these steps to activate the Oracle JServer/ JVM option:
- Make sure your database is started with large java_pool_size (>20M) and shared_pool_size (>50M) INIT.ORA parameter values.
- Run the $ORACLE_HOME/javavm/install/initjvm.sql script from SYS AS SYSDBA to install the Oracle JServer Option on a database.
- Grant JAVAUSERPRIV to users that wants to use Java:
SQL> GRANT JAVAUSERPRIV TO SCOTT; - The rmjvm.sql script can be used to deinstall the JServer option from your database.
- Follow the steps in the Oracle Migrations Guide to upgrade or downgrade the JServer option from one release to
another.
- ce code into the database? Use the “CREATE OR REPLACE JAVA SOURCE” command or “loadjava” utility. Loaded code can be viewed by selecting from the USER_SOURCE view.
- Why does one need to publish Java in the database? Publishing Java classes on the database makes it visible on a SQL and PL/SQL level. It is important to publish your code before calling it from SQL statements or PL/SQL code.
- What is JDBC and what is it used for? JDBC is a set of classes and interfaces written in Java to allow other Java programs to send SQL statements to a relational database management system. Oracle provides three categories of JDBC drivers: (a) JDBC Thin Driver (No local Net8 installation required/ handy for applets), (b) JDBC OCI for writing stand-alone Java applications, (c) JDBC KPRB driver (default connection) for Java Stored Procedures and Database JSP’s.
- How does one connect with the JDBC Thin Driver?
The the JDBC thin driver provides the only way to access Oracle from the Web (applets). It is smaller and faster than the OCI drivers, and doesn’t require a pre-installed version of the JDBC drivers.import java.sql.*;
class dbAccess {
public static void main (String args []) throws SQLException
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection
(”jdbc:oracle:thin:@hostname:1526:orcl”, “scott”, “tiger”);
// @machineName:port:SID, userid, password
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(”select BANNER from SYS.V_$VERSION”);
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
stmt.close();
}
} - How does one connect with the JDBC OCI Driver? One must have Net8 (SQL*Net) installed and working before attempting to use one of the OCI drivers.
import java.sql.*;
class dbAccess {
public static void main (String args []) throws SQLException
{
try {
Class.forName (”oracle.jdbc.driver.OracleDriver”);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = DriverManager.getConnection
(”jdbc:oracle:oci8:@hostname_orcl”, “scott”, “tiger”);
// or oci7 @TNSNames_Entry, userid, password
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(”select BANNER from SYS.V_$VERSION”);
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
stmt.close();
}
} - How does one connect with the JDBC KPRB Driver? One can obtain a handle to the default or current connection (KPRB driver) by calling the OracleDriver.defaultConenction() method. Please note that you do not need to specify a database URL, username or password as you are already connected to a database session. Remember not to close the default connection. Closing the default connection might throw an exception in future releases of Oracle.
import java.sql.*;
class dbAccess {
public static void main (String args []) throws SQLException
{
Connection conn = (new oracle.jdbc.driver.OracleDriver()).defaultConnection();
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(”select BANNER from SYS.V_$VERSION”);
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
stmt.close();
}
} - What is SQLJ and what is it used for? SQLJ is an ANSI standard way of coding SQL access in Java. It provides a Java precompiler that translates SQLJ call to JDBC calls. The idea is similar to that of other Oracle Precompilers.
- How does one deploy SQLJ programs? Use the sqlj compiler to compile your *.sqlj files to *.java and *.ser files. The *.ser files contain vendor specific database code. Thereafter one invokes the javac compiler to compile the .java files to *.class files. The *.class and *.ser files needs to be deployed.
- What is JDeveloper and what is it used for? JDeveloper is the Oracle IDE (Integrated Development Environment) for developing SQLJ and JDBC programs, applets, stored procedures, EJB’s, JSP’s etc.
- What is InfoBus DAC and what is it used for? InfoBus DAC (Data Aware Controls) is a standard Java extension used in JDeveloper to create data aware forms. It replaced the JBCL interface that were used in JDeveloper V1 and V2.
- What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN’s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.
- What is the difference between ASP and JSP? Active Server Pages (ASP) is a Microsoft standard, which is easier to develop than Java Server Pages (JSP). However ASP is a proprietary technology and is less flexible than JSP. For more information about ASP, see the Oracle ASP FAQ.
- How does one invoke a JSP? A JSP gets invoked when you call a *.jsp file from your Web Server like you would call a normal *.html file. Obviously your web server need to support JSP pages and must be configured properly to handle them.
- How does a JSP gets executed? The first time you call a JSP, a servlet (*.java) will be created and compiled to a .class file. The class file is then executed on the server. Output produced by the servlet is returned to the web browser. Output will typically be HTML or XML code.
- What is a Java Stored Procedure/ Trigger? A Java Stored Procedure is a procedure coded in Java (as opposed to PL/SQL) and stored in the Oracle database. Java Stored procedures are executed by the database JVM in database memory space. Java Stored Procedures can be developed in JDBC or SQLJ. Interfacing between PL/SQL and Java are extremely easy. Please note that Java Stored procedures are by default executed with invokers rights. PL/SQL procedures are by default executed with defines rights.
Large collection of Java interview questions
- What is the difference between an Abstract class and Interface ?
- What is user defined exception ?
- What do you know about the garbage collector ?
- What is the difference between C++ & Java ?
- Explain RMI Architecture?
- How do you communicate in between Applets & Servlets ?
- What is the use of Servlets ?
- What is JDBC? How do you connect to the Database ?
- In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
- What is the difference between Process and Threads ?
- What is the difference between RMI & Corba ?
- What are the services in RMI ?
- How will you initialize an Applet ?
- What is the order of method invocation in an Applet ?
- When is update method called ?
- How will you pass values from HTML page to the Servlet ?
- Have you ever used HashTable and Dictionary ?
- How will you communicate between two Applets ?
- What are statements in JAVA ?
- What is JAR file ?
- What is JNI ?
- What is the base class for all swing components ?
- What is JFC ?
- What is Difference between AWT and Swing ?
- 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 ?
- How does thread synchronization occurs inside a monitor ?
- How will you call an Applet using a Java Script function ?
- Is there any tag in HTML to upload and download files ?
- Why do you Canvas ?
- How can you push data from an Applet to Servlet ?
- What are 4 drivers available in JDBC ?
- How you can know about drivers and database information ?
- If you are truncated using JDBC, How can you know ..that how much data is truncated ?
- And What situation , each of the 4 drivers used ?
- How will you perform transaction using JDBC ?
- 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 ?
- Suppose server object is not loaded into the memory, and the client request for it , what will happen?
- What is serialization ?
- Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?
- What is difference RMI registry and OSAgent ?
- 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 ?
- What are the benefits of Swing over AWT ?
- Where the CardLayout is used ?
- What is the Layout for ToolBar ?
- What is the difference between Grid and GridbagLayout ?
- How will you add panel to a Frame ?
- What is the corresponding Layout for Card in Swing ?
- What is light weight component ?
- Can you run the product development on all operating systems ?
- What is the webserver used for running the Servlets ?
- What is Servlet API used for connecting database ?
- What is bean ? Where it can be used ?
- What is difference in between Java Class and Bean ?
- Can we send object using Sockets ?
- What is the RMI and Socket ?
- How to communicate 2 threads each other ?
- What are the files generated after using IDL to Java Compilet ?
Java networking and algoritms interview questions
- What is the protocol used by server and client ?
- Can I modify an object in CORBA ?
- What is the functionality stubs and skeletons ?
- What is the mapping mechanism used by Java to identify IDL language ?
- Diff between Application and Applet ?
- What is serializable Interface ?
- What is the difference between CGI and Servlet ?
- What is the use of Interface ?
- Why Java is not fully objective oriented ?
- Why does not support multiple Inheritance ?
- What it the root class for all Java classes ?
- What is polymorphism ?
- 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 ?
- 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?
- What are virtual functions ?
- Write down how will you create a binary Tree ?
- What are the traverses in Binary Tree ?
- Write a program for recursive Traverse ?
- What are session variable in Servlets ?
- What is client server computing ?
- What is Constructor and Virtual function? Can we call Virtual function in a constructor ?
- Why we use OOPS concepts? What is its advantage ?
- What is the middleware ? What is the functionality of Webserver ?
- Why Java is not 100 % pure OOPS ? ( EcomServer )
- When we will use an Interface and Abstract class ?
- What is an RMI?
- How will you pass parameters in RMI ? Why u serialize?
- What is the exact difference in between Unicast and Multicast object ? Where we will use ?
- What is the main functionality of the Remote Reference Layer ?
- How do you download stubs from a Remote place ?
- What is the difference in between C++ and Java ? can u explain in detail ?
- I want to store more than 10 objects in a remote server ? Which methodology will follow ?
- What is the main functionality of the Prepared Statement ?
- What is meant by static query and dynamic query ?
- What are the Normalization Rules ? Define the Normalization ?
- What is meant by Servlet? What are the parameters of the service method ?
- What is meant by Session ? Tell me something about HTTPSession Class ?
- How do you invoke a Servlet? What is the difference in between doPost and doGet methods ?
- What is the difference in between the HTTPServlet and Generic Servlet ? Explain their methods ? Tell me their parameter names also ?
- Have you used threads in Servlet ?
- Write a program on RMI and JDBC using StoredProcedure ?
- How do you sing an Applet ?
- In a Container there are 5 components. I want to display the all the components names, how will you do that one ?
- Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
- Tell me the latest versions in JAVA related areas ?
- What is meant by class loader ? How many types are there? When will we use them ?
- How do you load an Image in a Servlet ?
- What is meant by flickering ?
- What is meant by distributed Application ? Why we are using that in our applications ?
- What is the functionality of the stub ?
- Have you used any version control ?
- What is the latest version of JDBC ? What are the new features are added in that ?
- Explain 2 tier and 3 -tier Architecture ?
- What is the role of the webserver ?
- How have you done validation of the fields in your project ?
- What is the main difficulties that you are faced in your project ?
- What is meant by cookies ? Explain ?
Basic Java interview questions 1231
- 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.
Java interview questions
- What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. For example, a thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
- What are different ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, blocking on I/O, unsuccessfully attempting to acquire an object’s lock, or invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
- Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
- What’s new with the stop(), suspend() and resume() methods in new JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
- What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally.
- What method is used to specify a container’s layout? The setLayout() method is used to specify a container’s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout.
- Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout.
- What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state.
- What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. One example of class in Collections API is Vector and Set and List are examples of interfaces in Collections API.
- What is the List interface? The List interface provides support for ordered collections of objects. It may or may not allow duplicate elements but the elements must be ordered.
- How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
- What is the Vector class? The Vector class provides the capability to implement a growable array of objects. The main visible advantage of this class is programmer needn’t to worry about the number of elements in the Vector.
- What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
- If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
- What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection.
- How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits, ASCII require 7 bits (although the ASCII character set uses only 7 bits, it is usually represented as 8 bits), UTF-8 represents characters using 8, 16, and 18 bit patterns, UTF-16 uses 16-bit and larger bit patterns
- What is the difference between yielding and sleeping? Yielding means a thread returning to a ready state either from waiting, running or after creation, where as sleeping refers a thread going to a waiting state from running state. With reference to Java, when a task invokes its yield() method, it returns to the ready state and when a task invokes its sleep() method, it returns to the waiting state
- What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as objects. For example, Integer, Double. These classes contain many methods which can be used to manipulate basic data types
- Does garbage collection guarantee that a program will not run out of memory? No, it doesn’t. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. The main purpose of Garbage Collector is recover the memory from the objects which are no longer required when more memory is needed.
- Name Component subclasses that support painting? The following classes support painting: Canvas, Frame, Panel, and Applet.
- What is a native method? A native method is a method that is implemented in a language other than Java. For example, one method may be written in C and can be called in Java.
- How can you write a loop indefinitely?
for(;;) //for loop
while(true); //always true - Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
- What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection.
- What invokes a thread’s run() method? After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.
- What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars.
- What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.
- What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
- What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system.
- What is the purpose of the System class? The purpose of the System class is to provide access to system resources.
- What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. For example,
try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or not
} - What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
- What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its implements clause.
Java AWT interview questions
- What is meant by Controls and what are different types of controls? - Controls are componenets that allow a user to interact with your application. The AWT supports the following types of controls:
- Labels
- Push buttons
- Check boxes
- Choice lists
- Lists
- Scroll bars
- Text components
These controls are subclasses of Component.
- Which method of the component class is used to set the position and the size of a component? - setBounds(). The following code snippet explains this:
txtName.setBounds(x,y,width,height);
places upper left corner of the text field txtName at point (x,y) with the width and height of the text field set as width and height.
- Which TextComponent method is used to set a TextComponent to the read-only state? - setEditable()
- How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a CheckboxGroup.
- What methods are used to get and set the text label displayed by a Button object? - getLabel( ) and setLabel( )
- What is the difference between a Choice and a List? - Choice: A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. List: A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
- What is the difference between a Scollbar and a Scrollpane? - A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.
- Which are true about the Container class?
- The validate( ) method is used to cause a Container to be laid out and redisplayed.
- The add( ) method is used to add a Component to a Container.
- The getBorder( ) method returns information about a Container’s insets.
- getComponent( ) method is used to access a Component that is contained in a Container.
Answers: a, b and d
- Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frame’s font is set to 12-point TimesRoman, the Panel’s font is set to 10-point TimesRoman, and the Button’s font is not set, what font will be used to display the Button’s label?
- 12-point TimesRoman
- 11-point TimesRoman
- 10-point TimesRoman
- 9-point TimesRoman
Answer: c.
- What are the subclasses of the Container class? - The Container class has three major subclasses. They are:
- Window
- Panel
- ScrollPane
- Which object is needed to group Checkboxes to make them exclusive? - CheckboxGroup.
- What are the types of Checkboxes and what is the difference between them? - Java supports two types of Checkboxes:
- Exclusive
- Non-exclusive.
In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called as Radio buttons. The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other.
- What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default Layout manager for the panel and the panel subclasses? - A layout Manager is an object that is used to organize components in a container. The different layouts available in java.awt are:
- FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
- BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.
- CardLayout: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
- GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
- GridBagLayout:
The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy more
than one row or column of the grid. In addition, the rows and columns may have different sizes.
The default Layout Manager of Panel and Panel sub classes is FlowLayout.
- Can I add the same component to more than one container? - No. Adding a component to a container automatically removes it from any previous parent (container).
- How can we create a borderless window? - Create an instance of the Window class, give it a size, and show it on the screen.
Frame aFrame = new Frame();
Window aWindow = new Window(aFrame);
aWindow.setLayout(new FlowLayout());
aWindow.add(new Button("Press Me"));
aWindow.getBounds(50,50,200,200);
aWindow.show(); - Can I create a non-resizable windows? If so, how? - Yes. By using setResizable() method in class Frame.
- Which containers use a BorderLayout as their default layout? Which containers use a FlowLayout as their default layout? - The Window, Frame and Dialog classes use a BorderLayout as their default layout. The Panel and the Applet classes use the FlowLayout as their default layout.
- How do you change the current layout manager for a container?
- Use the setLayout method
- Once created you cannot change the current layout manager of a component
- Use the setLayoutManager method
- Use the updateLayout method
Answer: a.
- What is the difference between a MenuItem and a CheckboxMenuItem?- The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
Basic Java servlet interview questions
- What is the difference between CGI and Servlet?
- What is meant by a servlet?
- What are the types of servlets? What is the difference between 2 types of Servlets?
- What is the type of method for sending request from HTTP server ?
- What are the exceptions thrown by Servlets? Why?
- What is the life cycle of a servlet?
- What is meant by cookies? Why is Cookie used?
- What is HTTP Session?
- What is the difference between GET and POST methods?
- How can you run a Servlet Program?
- What is the middleware? What is the functionality of Webserver?
- What webserver is used for running the Servlets?
- How do you invoke a Servelt? What is the difference in between doPost and doGet methods?
- What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me their parameter names also?
- What are session variable in Servlets?
- What is meant by Session? Tell me something about HTTPSession Class?
- What is Session Tracking?
- Difference between doGet and doPost?
- What are the methods in HttpServlet?
- What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet?
Important Core Java interview questions
- What is the Collections API? - The Collections API is a set of classes and interfaces that support operations on collections of objects
- What is the List interface? - The List interface provides support for ordered collections of objects.
- What is the Vector class? - The Vector class provides the capability to implement a growable array of objects
- What is an Iterator interface? - The Iterator interface is used to step through the elements of a Collection
- Which java.util classes and interfaces support event handling? - The EventObject class and the EventListener interface support event processing
- What is the GregorianCalendar class? - The GregorianCalendar provides support for traditional Western calendars
- What is the Locale class? - The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region
- What is the SimpleTimeZone class? - The SimpleTimeZone class provides support for a Gregorian calendar
- What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values
- What is the highest-level event class of the event-delegation model? - The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy
- What is the Collection interface? - The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates
- What is the Set interface? - The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements
- What is the purpose of the enableEvents() method? - The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
- What is the ResourceBundle class? - The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
- What is the difference between yielding and sleeping? - When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
- When a thread blocks on I/O, what state does it enter? - A thread enters the waiting state when it blocks on I/O.
- When a thread is created and started, what is its initial state? - A thread is in the ready state after it has been created and started.
- What invokes a thread’s run() method? - After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.
- What method is invoked to cause an object to begin executing as a separate thread? - The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
- What is the purpose of the wait(), notify(), and notifyAll() methods? - The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object’s wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object’s notify() or notifyAll() methods.
- What are the high-level thread states? - The high-level thread states are ready, running, waiting, and dead
- What happens when a thread cannot acquire a lock on an object? - If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.
- How does multithreading take place on a computer with a single CPU? - The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
- What happens when you invoke a thread’s interrupt method while it is sleeping or waiting? - When a task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.
- What state is a thread in when it is executing? - An executing thread is in the running state
- What are three ways in which a thread can enter the waiting state? - A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
- What method must be implemented by all threads? - All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
- What are the two basic ways in which classes that can be run as threads may be defined? - A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.
- How can you store international / Unicode characters into a cookie? - One way is, before storing the cookie URLEncode it. URLEnocder.encoder(str); And use URLDecoder.decode(str) when you get the stored cookie.
Java GUI designer interview questions
- What advantage do Java’s layout managers provide over traditional windowing systems? - Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.
- What is the difference between the paint() and repaint() methods? - The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
- How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a CheckboxGroup
- What is the difference between a Choice and a List? - A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
- What interface is extended by AWT event listeners? - All AWT event listeners extend the java.util.EventListener interface.
- What is a layout manager? - A layout manager is an object that is used to organize components in a container
- Which Component subclass is used for drawing and painting? - Canvas
- What are the problems faced by Java programmers who dont use layout managers? - Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system
- What is the difference between a Scrollbar and a ScrollPane? (Swing) - A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
Java Messaging System interview questions
- What are the types of messaging? - There are two kinds of Messaging. Synchronous messaging involves a client that waits for the server to respond to a message. Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server.
- What is publish/subscribe messaging? - With publish/subscribe message passing the sending application/client establishes a named topic in the JMS broker/server and publishes messages to this queue. The receiving clients register (specifically, subscribe) via the broker to messages by topic; every subscriber to a topic receives each message published to that topic. There is a one-to-many relationship between the publishing client and the subscribing clients.
- Why doesn’t the JMS API provide end-to-end synchronous message delivery and notification of delivery? -Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API. JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can insure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer. The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.
- What are the core JMS-related objects required for each JMS-enabled application? - Each JMS-enabled client must establish the following:
- A connection object provided by the JMS server (the message broker)
- Within a connection, one or more sessions, which provide a context for message sending and receiving
- Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
- Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively). Within a session, a message object (to send or to receive)
- What is the Role of the JMS Provider? - The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.
- How does a typical client perform the communication? -
- Use JNDI to locate administrative objects.
- Locate a single ConnectionFactory object.
- Locate one or more Destination objects.
- Use the ConnectionFactory to create a JMS Connection.
- Use the Connection to create one or more Session(s).
- Use a Session and the Destinations to create the MessageProducers and MessageConsumers needed.
- Perform your communication.
- Give an example of using the point-to-point model. - The point-to-point model is used when the information is specific to a single client. For example, a client can send a message for a print out, and the server can send information back to this client after completion of the print job.
- How does the Application server handle the JMS Connection? -
- App server creates the server session and stores them in a pool.
- Connection consumer uses the server session to put messages in the session of the JMS.
- Server session is the one that spawns the JMS session.
- Applications written by Application programmers creates the message listener.