You are on page 1of 7

1.How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed: Stream st = new Stream(new FileOutputStream(output.txt)); System.setErr(st); System.setOut(st); 2.How would you create a button with rounded edges? Theres 2 ways. The first thing is to know that a JButtons edges are drawn by a Border. so you can override the Buttons 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 buttons border to it. 3.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. 4. Question: How you can force the garbage collection? Garbage collection automatic process and cant be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately. Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cant directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. 5. Whats the difference between constructors and normal 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 and it can return a value or can be void. 6. When should the method invokeLater()be used? This method is used to ensure that Swing components are updated through the event-dispatching thread. 7.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. 8.What are some advantages and disadvantages of Java Sockets? Some 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. Some 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. 9.What is Collection API? The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. 10.Explain the usage of the keyword transient? Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers). 11.Whats 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. 12.Why would you use a synchronized block vs. synchronized method? Synchronized blocks place locks for shorter periods than synchronized methods. 13.Can an inner class declared inside of a method access local variables of this method? Its possible if these variables are final. 14.Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions. Example: class myCustomException extends Exception { / The class simply has to exist to be an exception } 15.Describe the wrapper classes in Java. Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type. Following table lists the primitive types and the corresponding wrapper classes: Primitive Wrapper boolean java.lang.Boolean byte java.lang.Byte char java.lang.Character double java.lang.Double float java.lang.Float int java.lang.Integer long java.lang.Long short java.lang.Short void java.lang.Void 16.Which of the following are valid definitions of an applications main( ) method? a) public static void main(); b) public static void main( String args ); c) public static void main( String args[] ); d) public static void main( Graphics g ); e) public static boolean main( String args[] );

1.

What is garbage collection? What is the process that is responsible for doing that in java? Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process

2. 3. 4. 5.

What kind of thread is the Garbage collector thread? It is a daemon thread. What is a daemon thread? These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly. How will you invoke any external process in Java? Runtime.getRuntime().exec(.) What is the finalize method do? Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.

6.

What is mutable object and immutable object? If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, ) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, )

7. 8. 9.

What is the basic difference between string and stringbuffer object? String is an immutable object. StringBufferis a mutable object. What is the purpose of Void class? The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. What is reflection? Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.

10. What is the base class for Error and Exception? Throwable 11. What is the byte range? -128 to 127 12. What is the implementation of destroy method in java.. is it native or java code? This
method is not implemented.

13. What is a package? To group set of classes into a single unit is known as packaging. Packages
provides wide namespace ability.

14. What are the approaches that you will follow for making a program very efficient? By
avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.

15. 16. 17. 18.

What is a DatabaseMetaData? Comprehensive information about the database as a whole. What is Locale? A Locale object represents a specific geographical, political, or cultural region How will you load a specific locale? Using ResourceBundle.getBundle(); What is JIT and its use? Really, just a very fast compiler In this incarnation, pretty much a one-pass compiler no offline computations. So you cant look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, its an on-line problem.

19. Is JVM a compiler or an interpreter? Interpreter 20. When you think about optimization, what is the best way to findout the time/memory
consuming process? Using profiler

21. What is the purpose of assert keyword used in JDK1.4.x? In order to validate certain
expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.

22. How will you get the platform dependent values like line separator, path separator,
etc., ? Using Sytem.getProperty() (line.separator, path.separator, )

23. What is skeleton and stub? what is the purpose of those? Stub is a client side
representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use it is deprecated long before in JDK.

24. What is the final keyword denotes? final keyword denotes that it is the final implementation
for that method or variable or class. You cant override that method/variable/class any more.

25. What is the significance of ListIterator? You can iterate back and forth. 26. What is the major difference between LinkedList and ArrayList? LinkedList are meant for
sequential accessing. ArrayList are meant for random accessing.

27. What is nested class? If all the methods of a inner class is static then it is a nested class. 28. What is inner class? If the methods of the inner class can only be accessed via the instance of
the inner class, then it is called inner class.

29. What is composition? Holding the reference of the other class within some other class is
known as composition.

30. What is aggregation? It is a special type of composition. If you expose all the methods of a
composite class and route the method call to the composite method through its reference, then it is called aggregation.

31. What are the methods in Object? clone, equals, wait, finalize, getClass, hashCode, notify,
notifyAll, toString

32. Can you instantiate the Math class? You cant instantiate the math class. All the methods in
this class are static. And the constructor is not public.

33. What is singleton? It is one of the design pattern. This falls in the creational pattern of the
design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods }

34. What is DriverManager? The basic service to manage set of JDBC drivers. 35. What is Class.forName() does and how it is useful? It loads the class into the ClassLoader.
It returns the Class. Using that you can get the instance ( class-instance.newInstance() ).

36. Inq adds a question: Expain the reason for each keyword ofpublic static void main(String args[])

Exception handling
Function: catch key thunk handler Invoke thunk in the dynamic context of handler for exceptions matching key. If thunk throws to the symbol key, then handler is invoked this way:

(handler key args ...)

key may be a symbol. The thunk takes no arguments. If thunk returns normally, that is the return value of catch.
Handler is invoked outside the scope of its own catch. If handler again throws to the same key, a new handler from further up the call chain is invoked. If the key is #t, then a throw to any symbol will match this call to catch. Function: throw key &rest args ... Invoke the catch form matching key, passing args to the handler. If the key is a symbol it will match catches of the same symbol or of #t. If there is no handler at all, an error is signaled. procedure: error message args ... Raise an error with key misc-error and a message constructed by displaying msg and writing args. This normally prints a stack trace, and brings you back to the top level, or exits kawa if you are not running interactively. This procedure is part of SRFI-23, and other Scheme implementations. Function: primitive-throw exception Throws the exception, which must be an instance of a sub-class of . Syntax: try-finally body handler Evaluate body, and return its result. However, before it returns, evaluate handler. Even if body returns abnormally (by throwing an exception), handler is evaluated. (This is implemented just like Java try-finally.) Syntax: try-catch body handler ... Evaluate body, in the context of the given handler specifications. Each handler has the form:

var type exp ...


If an exception is thrown in body, the first handler is selected such that the thrown exception is an instance of the handlers type. If no handler is selected, the exception is propagated through the dynamic execution context until a matching handler is found. (If no matching handler is found, then an error message is printed, and the computation terminated.) Once a handler is selected, the var is bound to the thrown exception, and the exp in the handler are executed. The result of the try-catch is the result of body if no exception is thrown, or the value of the last exp in the selected handler if an exception is thrown. (This is implemented just like Javatry-catch.) Function: dynamic-wind in-guard thunk out-guard

All three arguments must be 0-argument procedures. First calls in-guard, then thunk, then out-guard. The result of the expression is that of thunk. If thunk is exited abnormally (by throwing an exception or invoking a continuation), outguard is called. If the continuation of the dynamic-wind is re-entered (which is not yet possible in Kawa), the in-guard is called again. This function was added in R5RS. Two JVM options are often used to tune JVM heap size: -Xmx for maximum heap size, and -Xms for initial heap size. Here are some common mistakes made by developers while using them:

1.

Missing m, M, g or G at the end (they are case insensitive). For example,

java -Xmx128 BigApp java.lang.OutOfMemoryError: Java heap space


The correct command should be: java -Xmx128m BigApp. To be precise, -Xmx128 is a valid setting for very small apps, like HelloWorld. But in real life, I guess you really mean -Xmx128m 2. Extra space in JVM options, or incorrectly use =. For example,

java -Xmx 128m BigApp Invalid maximum heap size: -Xmx Could not create the Java virtual machine. java -Xmx=512m HelloWorld Invalid maximum heap size: -Xmx=512m Could not create the Java virtual machine.
The correct command should be java -Xmx128m BigApp, with no whitespace nor =. -X options are different than -Dkey=value system properties, where = is used.

3.

Only setting -Xms JVM option and its value is greater than the default maximum heap size, which is 64m. The default minimum heap size seems to be 0. For example,

java -Xms128m BigApp Error occurred during initialization of VM Incompatible initial and maximum heap sizes specified
The correct command should be java -Xms128m -Xmx128m BigApp. Its a good idea to set the minimum and maximum heap size to the same value. In any case, dont let the minimum heap size exceed the maximum heap size. 4. Heap size is larger than your computers physical memory. For example,

java -Xmx2g BigApp Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine.
The fix is to make it lower than the physical memory: java -Xmx1g BigApp

5.

Incorrectly use mb as the unit, where m or M should be used instead.

java -Xms256mb -Xmx256mb BigApp Invalid initial heap size: -Xms256mb Could not create the Java virtual machine.

You might also like