Tuesday, May 29, 2007

java faqs 2

What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

What is Serialization and deserialization ?
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

Is Java a super set of JavaScript?
No. They are completely different. Some syntax may be similar.

What is a Container in a GUI?
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

How the object oriented approach helps us keep complexity of software development under control?
We can discuss such issue from the following aspects:
Objects allow procedures to be encapsulated with their data to reduce potential interference.
Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.
The well-defined separations of interface and implementation allow constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

What is polymorphism?
Polymorphism means "having many forms". It allows methods (may be variables) to be written that needn't be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of un-conceived classes.

What is design by contract?
The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions.
In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

What are use cases?
A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust.

What is scalability and performance?
Performance is a measure of "how fast can you perform this task." and scalability describes how an application behaves as its workload and available computing resources increase.

What is the benefit of subclass?
Generally: The sub class inherits all the public methods and the implementation.
The sub class inherits all the protected methods and their implementation.
The sub class inherits all the default(non-access modifier) methods and their implementation.
The sub class also inherits all the public, protected and default member variables from the super class.
The constructors are not part of this inheritance model.

How to add menushortcut to menu item?
If you have a button instance called aboutButton, you may add menu short cut by calling aboutButton.setMnemonic('A'), so the user may be able to use Alt+A to click the button.

In System.out.println(),what is System,out and println,pls explain?
System is a predefined final class,out is a PrintStream object acting as a field member and println is a built-in overloaded method in the out object.

Can you write a Java class that could be used both as an applet as well as an application?
A. Yes. Add a main() method to the applet.

Can you make an instance of an abstract class? For example - java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class.
No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method.

What is the output of x > y? a:b = p*q when x=1,y=2,p=3,q=4?
When this kind of question has been asked, find the problems you think is necessary to ask back before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x

What is the difference between Swing and AWT components?
AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

Why Java does not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C-sharp shine.

Parsers? DOM vs SAX parser
Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.
DOM
1. Tree of nodes
2. Memory: Occupies more memory, preffered for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy
6. Ease of navigation
SAX
1. Sequence of events
2. Doesn't use any memory preferred for large documents
3. Faster at runtime
4. Objects are to be created
5. Need to write code for creating objects
6. Backward navigation is not possible as it sequentially processes the document

Can you declare a class as private?
Yes, we can declare a private class as an inner class. For example,

class MyPrivate {
private static class MyKey {
String key = "12345";
}
public static void main(String[] args) {
System.out.println(new MyKey().key);//prints 12345
}
}

What is the difference between shallow copy and deep copy?
Shallow copy shares the same reference with the original object like cloning, whereas the deep copy get a duplicate instance of the original object. If the shallow copy has been changed, the original object will be reflected and vice versa.

Can one create a method which gets a String and modifies it?
No. In Java, Strings are constant or immutable; their values cannot be changed after they are created, but they can be shared. Once you change a string, you actually create a new object. For example:
String s = "abc"; //create a new String object representing "abc"
s = s.toUpperCase(); //create another object representing "ABC"

Why is multiple inheritance not possible in Java?
It depends on how you understand "inheritance". Java can only "extends" one super class, but can "implements" many interfaces; that doesn't mean the multiple inheritance is not possible. You may use interfaces to make inheritance work for you. Or you may need to work around. For example, if you cannot get a feature from a class because your class has a super class already, you may get that class's feature by declaring it as a member field or getting an instance of that class. So the answer is that multiple inheritance in Java is possible.

What's the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.


What is the relationship between synchronized and volatile keyword?
The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic.(Some JVM might treat reads and writes of data of 64 bits or less as atomic in future) For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or block, or declare them volatile.

This class (IncrementImpl) will be used by various threads concurrently; can you see the inherent flaw(s)? How would you improve it?
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public int getCounter() {
return counter;
}
}

The counter is static variable which is shared by multiple instances of this class. The increment() method is synchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will not guarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed at Sun's thread tutorial site will tell more.
one of solutions
public class IncrementImpl {
private static int counter = 0;
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
}

What are the drawbacks of inheritance?
Since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation. In addition, the inheritance may make peers hardly understand your code if they don't know how your super-class acts and add learning curve to the process of development.
Usually, when you want to use a functionality of a class, you may use subclass to inherit such function or use an instance of this class in your class. Which is better, depends on your specification.

Is there any other way that you can achieve inheritance in Java?
There are a couple of ways. As you know, the straight way is to "extends" and/or "implements". The other way is to get an instance of the class to achieve the inheritance. That means to make the supposed-super-class be a field member. When you use an instance of the class, actually you get every function available from this class, but you may lose the dynamic features of OOP

Two methods have key words static synchronized and synchronized separately. What is the difference between them?
Both are synchronized methods. One is instance method, the other is class method. Method with static modifier is a class method. That means the method belongs to class itself and can be accessed directly with class name and is also called Singleton design. The method without static modifier is an instance method. That means the instance method belongs to its object. Every instance of the class gets its own copy of its instance method.
When synchronized is used with a static method, a lock for the entire class is obtained. When synchronized is used with a non-static method, a lock for the particular object (that means instance) of the class is obtained.
Since both methods are synchronized methods, you are not asked to explain what is a synchronized method. You are asked to tell the difference between instance and class method. Of course, your explanation to how synchronized keyword works doesn't hurt. And you may use this opportunity to show your knowledge scope.

How do you create a read-only collection?
The Collections class has six methods to help out here:
1. unmodifiableCollection(Collection c)
2. unmodifiableList(List list)
3. unmodifiableMap(Map m)
4. unmodifiableSet(Set s)
5. unmodifiableSortedMap(SortedMap m)
6. unmodifiableSortedSet(SortedSet s)
If you get an Iterator from one of these unmodifiable collections, when you call remove(), it will throw an UnsupportedOperationException.

Can a private method of a superclass be declared within a subclass?
Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding (polymorphism) features.

Why Java does not support multiple inheritance ?
This is a classic question. Yes or No depends on how you look at Java. If you focus on the syntax of "extends" and compare with C++, you may answer 'No' and give explanation to support you. Or you may answer 'Yes'. Recommend you to say 'Yes'.
Java DOES support multiple inheritance via interface implementation. Some people may not think in this way. Give explanation to support your point.


What is the difference between final, finally and finalize?
Short answer:
final - declares constant
finally - relates with exception handling
finalize - helps in garbage collection
If asked to give details, explain:
final field, final method, final class
try/finally, try/catch/finally
protected void finalize() in Object class

What kind of security tools are available in J2SE 5.0?
There are three tools that can be used to protect application working within the scope of security policies set at remote sites.
keytool -- used to manage keystores and certificates.
jarsigner -- used to generate and verify JAR signatures.
policytool -- used for managing policy files.
There are three tools that help obtain, list and manage Kerberos tickets.
kinit -- used to obtain Kerberos V5 tickets.
tklist -- used to list entries in credential cache and key tab.
ktab -- used to help manage entries in the key table.

How to make an array copy from System?
There is a method called arraycopy in the System class. You can do it:
System.arraycopy(sourceArray, srcOffset, destinationArray, destOffset, numOfElements2Copy);
When you use this method, the destinationArray will be filled with the elements of sourceArray at the length specified.

Can we use System.arraycopy() method to copy the same array?
Yes, you can. The source and destination arrays can be the same if you want to copy a subset of the array to another area within that array.

What is shallow copy or shallow clone in array cloning?
Cloning an array invloves creating a new array of the same size and type and copying all the old elements into the new array. But such copy is called shallow copy or shallow clone because any changes to the object would be reflected in both arrays.

When is the ArrayStoreException thrown?
When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

How to check two arrays to see if contents have the same types and contain the same elements?
One of options is to use the equals() method of Arrays class.
Arrays.equals(a, b);
If the array types are different, a compile-time error will happen.

Can you call one constructor from another if a class has multiple constructors?
Yes. Use this() syntax.

What are the different types of inner classes?
There are four different types of inner classes in Java. They are: a)Static member classes , a static member class has access to all static methods of the parent, or top-level, class b) Member classes, the member class is instance specific and has access to any and all methods and members, even the parent's this reference c) Local classes, are declared within a block of code and are visible only within that block, just as any other method variable. d) Anonymous classes, is a local class that has no name

In which case would you choose a static inner class?
Interesting one, static inner classes can access the outer class's protected and private fields. This is both a positive and a negitive point for us since we can, in essence, violate the encapsulation of the outer class by mucking up the outer class's protected and private fields. The only proper use of that capability is to write white-box tests of the class -- since we can induce cases that might be very hard to induce via normal black-box tests (which don't have access to the internal state of the object). Second advantage,if I can say, is that, we can this static concept to impose restriction on the inner class. Again as discussed in earlier point, an Inner class has access to all the public, private and protected members of the parent class. Suppose you want to restrict the access even to inner class, how would you go ahead? Making the inner class static enforces it to access only the public static members of the outer class( Since, protected and private members are not supposed to be static and that static members can access only other static members). If it has to access any non-static member, it has to create an instance of the outer class which leads to accessing only public members.

What is weak reference in Java
A weak reference is one that does not prevent the referenced object from being garbage collected. You might use them to manage a HashMap to look up a cache of objects. A weak reference is a reference that does not keep the object it refers to alive. A weak reference is not counted as a reference in garbage collection. If the object is not referred to elsewhere as well, it will be garbage collected.

hat is the difference between final, finally and finalize?
final is used for making a class no-subclassable, and making a member variable as a constant which cannot be modified. finally is usually used to release all the resources utilized inside the try block. All the resources present in the finalize method will be garbage collected whenever GC is called. Though finally and finalize seem to be for a similar task there is an interesting tweak here, usually I prefer finally than finalize unless it is unavoidable. This is because the code in finally block is guaranteed of execution irrespective of occurrence of exception, while execution of finalize is not guarenteed.finalize method is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. Presumably the garbage collector will, like its civil servant namesake, visit the heap on a regular basis to clean up resources that are no longer in use. Garbage collection exists to prevent programmers from calling delete. This is a wonderful feature. For example, if you can't call delete, then you can't accidentally call delete twice on the same object. However, removing delete from the language is not the same thing as automatically cleaning up. To add to it, Garbage collection might not ever run. If garbage collection runs at all, and an object is no longer referenced, then that object's finalize will run. Also, across multiple objects, finalize order is not predictable. The correct approach to resource cleanup in Java language programs does not rely on finalize. Instead, you simply write explicit close methods for objects that wrap native resources. If you take this approach, you must document that the close method exists and when it should be called. Callers of the object must then remember to call close when they are finished with a resource.

What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

The following statement prints true or false, why?
byte[] a = { 1, 2, 3 };,
byte[] b = (byte[]) a.clone();
System.out.println(a == b);
The false will be printed out. Because the two arrays have distinctive memory addresses. Starting in Java 1.2, we can use java.util.Arrays.equals(a, b) to compare whether two arrays have the same contents.

Why do we need to use getSystemResource() and getSystemResources() method to load resources?
Because we want to look for resources strictly from the system classpath, These methods use the system ClassLoader to locate resources, which gives you stricter control of the resources used by the application.

ArithmeticException?
The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

What is a transient variable?
A transient variable is a variable that may not be serialized.

Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.

Why do threads block on I/O?
Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

What is the output from System.out.println("Hello"+null);?
Hellonull

What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

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 JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

Is null a keyword?
The null value is not a keyword.

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.

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.

Which characters may be used as the second character of an identifier, but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

What is the List interface?
The List interface provides support for ordered collections of objects.

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

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.

What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.

What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

Which method of the Component class is used to set the position and size of a component?
setBounds()

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and 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?
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.

Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.

Is sizeof a keyword?
The sizeof operator is not a keyword.

What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as objects.

Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. 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.

What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).


Can an object's finalize() method be invoked while it is reachable?
An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

What is the immediate superclass of the Applet class?
Panel

What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.

What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.

What is the immediate superclass of the Dialog class?
Window.

What is clipping?
Clipping is the process of confining paint operations to a limited area or shape.

What is a native method?
A native method is a method that is implemented in a language other than Java.

Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.

To what value is a variable of the String type automatically initialized?
The default value of a String type is null.

What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

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.

What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

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.

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 range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.

What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.

In which package are most of the AWT events that support the event-delegation model defined?
Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

What is the immediate super class of Menu?
What is the immediate super class of Menu? MenuItem

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.

Which class is the immediate super class of the MenuComponent class.
Object

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 difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. 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. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

Name three subclasses of the Component class.
Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent

What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.

Which Container method is used to cause a container to be laid out and redisplayed?
validate()

What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.

How many times may an object's finalize() method be invoked by the garbage collector?
An object's finalize() method may only be invoked once by the garbage collector.

What is the purpose of the finally clause of a try-catch-finally statement? garbage collector?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type.

Which Java operator is right associative?
The = operator is right associative.

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.

Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.

No comments: