Sunteți pe pagina 1din 54

Java Sample Questions

1. Can a abstract method have the static qualifier? Answer: No 2. What are the different types of qualifier and What is the default qualifier? Answer: public, protected, private, package (default) 3. What is the super class of Hashtable? Answer: Dictionary 4. What is a lightweight component? Answer: Lightweight components are the one which doesn't go with the native call to obtain the graphical units.They share their parent component graphical units to render them.Example, Swing components 5. What is a heavyweight component? Answer: For every paint call, there will be a native call to get the graphical units.Example, AWT. 6. What is an applet? Answer: Applet is a program which can get downloaded into a client environment and start executing there. 7. What do you mean by a Classloader? Answer: Classloader is the one which loads the classes into the JVM. 8. What are the implicit packages that need not get imported into a class file? Answer: java.lang 9. What is the difference between lightweight and heavyweight component? Answer: Lightweight components reuses its parents graphical units.Heavyweight components go with the native graphical unit for every component.Lightweight components are faster than the heavyweight components. 10. What are the ways in which you can instantiate a thread?

Answer: Using Thread class By implementing the Runnable interface and giving that handle to the Thread class.

What is a Marker Interface? Answer: An interface with no methods.Example: Serializable, Remote, Cloneable What interface do you implement to do the sorting? Answer: Comparable What is the eligibility for a object to get cloned? Answer: It must implement the Cloneable interface. What is the purpose of abstract class? Answer: It is not an instantiable class.It provides the concrete implementation for some/all the methods.So that they can reuse the concrete functionality by inheriting the abstract class. What is the difference between interface and abstract class? Answer: Abstract class defined with methods.Interface will declare only the methods.Abstract classes are very much useful when there is some functionality across various classes.Interfaces are well suited for the class, which varies in functionality but with the same method signatures. What do you mean by RMI and How it is useful? Answer: RMI is a remote method invocation.Using RMI, you can work with remote object.The function calls are as though you are invoking a local variable.So it gives you a impression that you are working really with a object that resides within your own JVM though it is somewhere. What is the protocol used by RMI? Answer: RMI-IIOP What is a hashCode? Answer: hash code value for this object which is unique for every object. What is a thread? Answer: Thread is a block of code which can execute concurrently with other threads in the JVM.

What is the algorithm used in Thread scheduling? Answer: Fixed priority scheduling. What is hash-collision in Hashtable and How it is handled in Java? Answer: Two different keys with the same hash value.Two different entries will be kept in a single hash bucket to avoid the collision. What are the different driver types available in JDBC? Answer: The driver types available in JDBC are:

A JDBC-ODBC bridge A native-API partly Java technology-enabled driver A net-protocol fully Java technology-enabled driver A native-protocol fully Java technology-enabled driver

Is JDBC-ODBC bridge multi-threaded? Answer: No Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? Answer: No What is the use of serializable? Answer: To persist the state of an object into any perminant storage device. What is the use of transient? Answer: It is an indicator to the JVM that those variables should not be persisted.It is the users responsibility to initialize the value when read back from the storage. What are the different level lockings using the synchronization keyword? Answer: Class level lock Object level lock Method level lock Block level lock What is the use of preparedstatement? Answer: Preparedstatements are precompiled statements.It is mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk processing. What is callable statement? Tell me the way to get the callable statement? Answer: Callable statements are used to invoke the stored procedures.You can obtain the callable statement from Connection using the following methods:

prepareCall(String sql) prepareCall(String sql, int resultSetType, int resultSetConcurrency)

In a statement, I am executing a batch.What is the result of the execution? Answer: It returns the int array.The array contains the affected row count in the corresponding index of the SQL.

What are the states of a thread? Answer: There are four states of thread: New

Runnable Not runnable Dead

What is a socket? Answer: A socket is an endpoint for communication between two machines. How will you establish the connection between the servlet and an applet? Answer: Using the URL, I will create the connection URL.Then by openConnection method of the URL, I will establish the connection, through which I can be able to exchange data. What are the threads will start, when you start the java program? Answer: Finalizer, Main, Reference Handler, Signal Dispatcher. Is it necessary that each try block must be followed by a catch block? Answer: It is not necessary that each try block must be followed by a catch block.It should be followed by either a catch block OR a finally block.And whatever exceptions are likely to be thrown should be declared in the throws clause of the method. If I write return at the end of the try block, will the finally block still execute? Answer: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute.The finally block will execute and then the control return. If I write System.exit (0); at the end of the try block, will the finally block still execute?

Answer: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. How are Observer and Observable used? Answer: Objects that subclass the Observable class maintain a list of observers.When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state.The Observer interface is implemented by objects that observe Observable objects. What is synchronization and why is it important? Answer: With respect to multithreading, synchronization is the capability to controlthe 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 tosignificant errors. Why do we need wrapper classes? Answer: It is sometimes easier to deal with primitives as objects.Moreover most of the collection classes store objects and not primitive data types.And also the wrapper classes provide many utility methods also.Because of these resons we need wrapper classes.And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection.Also we can pass them around as method parameters where a method expects an object.

What is the difference between preemptive scheduling and time slicing?


Answer:

Under preemptive scheduling, the highest priority task executes until it entersthe 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. When a thread is created and started, what is its initial state? Answer: A thread is in the ready state after it has been created and started. What is the purpose of finalization? Answer: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. What is the Locale class? Answer: The Locale class is used to tailor program output to the conventions of aparticular geographic, political, or cultural region.

What is the difference between a while statement and a do statement? Answer: A while statement checks at the beginning of a loop to see whether the nextloop iteration should occur.A do statement 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 body of a loop at least once. What is the difference between static and non-static variables? Answer: A static variable is associated with the class as a whole rather than with specific instances of a class.Non-static variables take on unique values with each object instance. How are this() and super() used with constructors? Answer: Othis() is used to invoke a constructor of the same class.super() is used toinvoke a superclass constructor. What are synchronized methods and synchronized statements? Answer: Synchronized methods are methods that are used to control access to an object.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. How does Java handle integer overflows and underflows? Answer: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. Does garbage collection guarantee that a program will not run out of memory? Answer: Garbage collection does not guarantee that a program will not run out ofmemory.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 is the difference between an Interface and an Abstract class? Answer: 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. What is the purpose of garbage collection in Java, and when is it used?

Answer: 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. Describe synchronization in respect to multithreading. Answer: 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. Explain different way of using thread? Answer: The thread could be implemented by using runnable interface or by inheriting from the Thread class.The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help. What are pass by reference and passby value? Answer: Pass By Reference means the passing the address itself rather than passing the value.Passby Value means passing a copy of the value to be passed. What is HashMap and Map? Answer: Map is Interface and Hashmap is class that implements that. Difference between HashMap and HashTable? Answer: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.(HashMap allows null values as key and value whereas Hashtable doesnt allow).HashMap does not guarantee that the order of the map will remain constant over time.HashMap is non synchronized and Hashtable is synchronized. Difference between Vector and ArrayList? Answer: Vector is synchronized whereas arraylist is not. Difference between Swing and Awt? Answer: AWT are heavy-weight componenets.Swings are light-weight components.Hence swing works faster than AWT. What is the difference between a constructor and a method? Answer: A constructor is a member function of a class that is used to create objects of that class.It has the same name as the class itself, has no return type, and is invoked

using the new operator.A method is an ordinary member function of a class.It has its own name, a return type (which may be void), and is invoked using the dot operator. What is an Iterators? Answer: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface.This interface allows you to walk a collection of objects, operating on each object in turn.Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator. State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. Answer: public : Public class is visible in other packages, field is visible everywhere (class must be public too)private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package. What is an abstract class? Answer: Abstract class must be extended/subclassed (to be useful).It serves as a template.A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data.Any class with an abstract method is automatically abstract itself, and must be declared as such.A class may be declared abstract even if it has no abstract methods.This prevents it from being instantiated. What is static in java? Answer: Static means one per class, not one for each object no matter how many instance of a class might exist.This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final.However, you can't override a static method with a nonstatic method.In other words, you can't change a static method into an instance method in a subclass. What is final? Answer: A final class can't be extended ie., final class may not be subclassed.A final method can't be overridden when its class is inherited.You can't change value of a final variable (is a constant).

What if the main method is declared as private? Answer: The program compiles properly but at runtime it will give "Main method not public." message. What if the static modifier is removed from the signature of the main method? Answer: Program compiles.But at runtime throws an error "NoSuchMethodError". What if I write static public void instead of public static void? Answer: Program compiles and runs properly. What if I do not provide the String array as the argument to the method? Answer: Program compiles but throws a runtime error "NoSuchMethodError". What is the first argument of the String array in main method? Answer: 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 I do not provide any arguments on the command line, then the String array of Main method will be empty of null? Answer: It is empty.But not null. How can one prove that the array is not null but empty? Answer: Print args.length.It will print 0.That means it is empty.But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length. What environment variables do I need to set on my machine in order to be able to run Java programs? Answer: CLASSPATH and PATH are the two variables. Can an application have multiple classes having main method? Answer: Yes it is possible.While starting the application we mention the class name to be run.The JVM will look for the Main method only in the class whose name you have mentioned.Hence there is not conflict amongst the multiple classes having main method. Can I have multiple main methods in the same class?

Answer: No the program fails to compile.The compiler says that the main method is already defined in the class. Do I need to import java.lang package any time? Why ? Answer: No.It is by default loaded internally by the JVM. Can I import same package/class twice? Will the JVM load the package twice at runtime? Answer: One can import the same package or same class multiple times.Neither compiler nor JVM complains abt it.And the JVM will internally load the class only once no matter how many times you import the same class. What are Checked and UnChecked Exception? Answer: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown.eg, IOException thrown by java.io.FileInputStream's read() methodUnchecked exceptions are RuntimeException and any of its subclasses.Class Error and its subclasses also are unchecked.With an unchecked exception, however, the compiler doesn't force client programmers either to catch theexception or declare it in a throws clause.In fact, client programmers may not even know that the exception could be thrown.eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caught at compile time.Runtime exceptions do not need to be.Errors often cannot be. What is Overriding? Answer: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass.Methods may be overridden to be more public, not more private. What are different types of inner classes? Answer: Nested -level classes, Member classes, Local classes, Anonymous classesNested -level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other -level class.Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package.eg, outer.inner.-level inner classes implicitly have access only to static variables.There can also be inner interfaces.All of these are of the nested -level variety.Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables.This means a public member class acts similarly to a nested -level class.The primary difference between member classes and nested -level classes is that member classes have access to the specific instance of the enclosing class.Local classes - Local classes are like local variables, specific to a block of

code.Their visibility is only within the block of their declaration.In order for the class to be useful beyond the declaration block, it would need to implement amore publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.Anonymous classes - Anonymous inner classes extend local inner classes one level further.As anonymous classes have no name, you cannot provide a constructor. Which methods of Serializable interface should I implement? Answer: The serializable interface is an empty interface, it does not contain any methods.So we do not implement any methods. How can I customize the seralization process? i.e.how can one have a control over the serialization process? Answer: Yes it is possible to have control over serialization process.The class should implement Externalizable interface.This interface contains two methods namely readExternal and writeExternal.You should implement these methods and write the logic for customizing the serialization process. What is the common usage of serialization? Answer: Whenever an object is to be sent over the network, objects need to be serialized.Moreover if the state of an object is to be saved, objects need to be serilazed. What is Externalizable interface? Answer: Externalizable is an interface which contains two methods readExternal and writeExternal.These methods give you a control over the serialization mechanism.Thus if your class implements this interface, you can customize the serialization process by implementing these methods. What happens to the object references included in the object? Answer: The serialization mechanism generates an object graph for serialization.Thus it determines whether the included object references are serializable or not.This is a recursive process.Thus when an object is serialized, all the included objects are also serialized alongwith the original obect. What one should take care of while serializing the object? Answer: One should make sure that all the included objects are also serializable.If any of the objects is not serializable then it throws a NotSerializableException. What happens to the static fields of a class during serialization? Are these fields serialized as a part of each serialized object?

Answer: Yes the static fields do get serialized.If the static field is an object then it must have implemented Serializable interface.The static fields are serialized as a part of every object.But the commonness of the static fields across all the instances is maintained even after serialization. Does Java provide any construct to find out the size of an object? Answer: No there is not sizeof operator in Java.So there is not direct way to determine the size of an object directly in Java. Does importing a package imports the subpackages as well? e.g.Does importing com.MyTest.* also import com.MyTest.UnitTests.*? Answer: Read the system time just before the method is invoked and immediately after method returns.Take the time difference, which will give you the time taken by a method for execution.To put it in code...long start = System.currentTimeMillis ();method ();long end = System.currentTimeMillis ();System.out.println ("Time taken for execution is " + (end - start));Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution.Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing. What are wrapper classes? Answer: Java provides specialized classes corresponding to each of the primitive data types.These are called wrapper classes.They are e.g.Integer, Character, Double etc Are the imports checked for validity at compile time? e.g.will the code containing an import such as java.lang.ABCD compile? Answer: Yes the imports are checked for the semantic validity at compile time.The code containing above line of import will not compile.It will throw an error saying,can not resolve symbolsymbol : class ABCDlocation: package ioimport java.io.ABCD; Does importing a package imports the subpackages as well? e.g.Does importing com.MyTest.* also import com.MyTest.UnitTests.*? Answer: No you will have to import the subpackages explicitly.Importing com.MyTest.* will import classes in the package MyTest only.It will not import any class in any of it's subpackage. What is the difference between declaring a variable and defining a variable? Answer: In declaration we just mention the type of the variable and it's name.We do not initialize it.But defining means declaration + initialization.e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

What is the default value of an object reference declared as an instance variable? Answer: null unless we define it explicitly. Can a level class be private or protected? Answer: No.A level class can not be private or protected.It can have either "public" or no modifier.If it does not have a modifier it is supposed to have a default access.If a level class is declared as private the compiler will complain that the "modifier private is not allowed here".This means that a level class can not be private.Same is the case with protected. What type of parameter passing does Java support? Answer: In Java the arguments are always passed by value. Primitive data types are passed by reference or pass by value? Answer: Primitive data types are passed by value. Objects are passed by value or by reference? Answer: Java only supports pass by value.With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object. What is serialization? Answer: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream. How do I serialize an object to a file? Answer: The class whose instances are to be serialized should implement an interface Serializable.Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream.This will save the object to a file. What are checked exceptions? Answer: Checked exception are those which the Java compiler forces you to catch.e.g.IOException are checked Exceptions. What are runtime exceptions? Answer: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc.These are not checked by the compiler at compile time.

What is the difference between error and an exception? Answer: An error is an irrecoverable condition occurring at runtime.Such as OutOfMemory error.These JVM errors and you can not repair them at runtime.While exceptions are conditions that occur because of bad input etc.e.g.FileNotFoundException will be thrown if the specified file does not exist.Or a NullPointerException will take place if you try using a null reference.In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.). How to create custom exceptions? Answer: Your class should extend class Exception, or some more specific type thereof. If I want an object of my class to be thrown as an exception object, what should I do? Answer: The class should extend from Exception class.Or you can extend your class from some more precise exception type also. If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object? Answer: One can not do anytihng in this scenarion.Because Java does not allow multiple inheritance and does not provide any exception interface as well. What happens to an unhandled exception? Answer: One can not do anytihng in this scenarion.Because Java does not allow multiple inheritance and does not provide any exception interface as well. How does an exception permeate through the code? Answer: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block.If a matching type is found then that block will be invoked.If a matching type is not found then the exception moves up the method stack and reaches the caller method.Same procedure is repeated if the caller method is included in a try catch block.This process continues until a catch block handling the appropriate type of exception is found.If it does not find such a block then finally the program terminates. What are the different ways to handle exceptions? Answer: There are two ways to handle exceptions, 1.By wrapping the desired code in a try block followed by a catch block to catch the exceptions.and 2.List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

What is the basic difference between the 2 approaches to exception handling...


try catch block and specifying the candidate exceptions in the throws clause?When should you use which approach?

Answer: In the first approach as a programmer of the method, you urself are dealing with the exception.This is fine if you are in a best position to decide should be done in case of an exception.Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach.In this case use the second approach.In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw.This is often the approach library creators use.They list the exception in the throws clause and we must catch them.You will find the same approach throughout the java libraries we use.

One of the components of a computer is its CPU.What is a CPU and what role does it play in a computer? Answer: The CPU, or Central Processing Unit, is the active part of the computer.Its function is to execute programs that are coded in machine language and stored in the main memory (RAM) of the computer.It does this by repeating the fetchandexecute cycle over and over; that is, it repeatedly fetches a machine language instruction from memory and executes it. Explain what is meant by an "asynchronous event." Give some examples. Answer: An asynchronous event is one that occurs at an unpredictable time outside the control of the program that the CPU is running.It is not "synchronized" with the program.An example would be when the user presses a key on the keyboard or clicks the mouse button.(These events generate "interrupts" that cause the CPU to interrupt what it is doing and to take some action to handle the asynchronous event.After handling the event, the CPU returns to what it was doing before it was interrupted.) What is the difference between a "compiler" and an "interpreter"? Answer: Compilers and interpreters have similar functions: They take a program written in some programming language and translate it into machine language.A compiler does the translation all at once.It produces a complete machine language program that can then be executed.An interpreter, on the other hand, just translates one instruction at a time, and then executes that instruction immediately.(Java uses a compiler to translate java programs into Java Bytecode, which is a machine language for the imaginary Java Virtual Machine.Java Bytecode programs are then executed by an interpreter.) Explain the difference between highlevel languages and machine language.

Answer: Programs written in the machine language of a given type of computer can be directly executed by the CPU of that type of computer.Highlevel language programs must be translated into machine language before they can be executed. (Machine language instructions are encoded as binary numbers that are meant to be used by a machine, not read or written by people.Highlevel languages use a syntax that is closer to human language.) If you have the source code for a Java program, and you want to run that program, you will need both a compiler and an interpreter.What does the Java compiler do, and what does the Java interpreter do? Answer: The Java compiler translates Java programs into a language called Java bytecode.Although bytecode is similar to machine language, it is not the machine language of any actual computer.A Java interpreter is used to run the compiled Java bytecode program.(Each type of computer needs its own Java bytecode interpreter, but all these interpreters interpret the same bytecode language.) What is a subroutine? Answer: A subroutine is a set of instructions for performing some task that have been grouped together and given a name.Later, when that task needs to be performed, it is only necessary to call the subroutine by giving its name, rather than repeating the whole sequence of instructions. Java is an objectoriented programming language.What is an object? Answer: An object consists of some data together with a set of subroutines that manipulate that data.(An object is a kind of "module," or selfcontained entity that communicates with the rest of the world through a welldefined interface.An object should represent some coherent concept or realworld object.) What is a variable? Answer: A variable is a memory location that has been given a name so that it can easily be referred to in a program.The variable holds a value, which must be of some specified type.The value can be changed during the course of the execution of the program. Java is a "platformindependent language." What does this mean? Answer: A Java program can be compiled once into a Java Bytecode program.The compiled program can then be run on any computer that has an interpreter for the Java virtual machine.Other languages have to be recompiled for each platform on which they are going to run.The point about Java is that it can be executed on many different types of computers without being recompiled. 10: What is the "Internet"? Give some examples of how it is used.

Answer: The Internet is a network connecting millions of computers around the world.Computers connected to the Internet can communicate with each other.The Internet can be used for:

Telnet:which lets a user of one computer log onto another computer remotely. FTP:which is used to copy files between computers. World Wide Web:which lets a user view "pages" of information published on computers around the world.

One of the components of a computer is its CPU.What is a CPU and what role does it play in a computer? Answer: The CPU, or Central Processing Unit, is the active part of the computer.Its function is to execute programs that are coded in machine language and stored in the main memory (RAM) of the computer.It does this by repeating the fetchandexecute cycle over and over; that is, it repeatedly fetches a machine language instruction from memory and executes it. Explain what is meant by an "asynchronous event." Give some examples. Answer: An asynchronous event is one that occurs at an unpredictable time outside the control of the program that the CPU is running.It is not "synchronized" with the program.An example would be when the user presses a key on the keyboard or clicks the mouse button.(These events generate "interrupts" that cause the CPU to interrupt what it is doing and to take some action to handle the asynchronous event.After handling the event, the CPU returns to what it was doing before it was interrupted.) What is the difference between a "compiler" and an "interpreter"? Answer: Compilers and interpreters have similar functions: They take a program written in some programming language and translate it into machine language.A compiler does the translation all at once.It produces a complete machine language program that can then be executed.An interpreter, on the other hand, just translates one instruction at a time, and then executes that instruction immediately.(Java uses a compiler to translate java programs into Java Bytecode, which is a machine language for the imaginary Java Virtual Machine.Java Bytecode programs are then executed by an interpreter.) Explain the difference between highlevel languages and machine language. Answer: Programs written in the machine language of a given type of computer can be directly executed by the CPU of that type of computer.Highlevel language programs must be translated into machine language before they can be executed. (Machine language instructions are encoded as binary numbers that are meant to be used by a machine, not read or written by people.Highlevel languages use a syntax that is closer to human language.)

If you have the source code for a Java program, and you want to run that program, you will need both a compiler and an interpreter.What does the Java compiler do, and what does the Java interpreter do? Answer: The Java compiler translates Java programs into a language called Java bytecode.Although bytecode is similar to machine language, it is not the machine language of any actual computer.A Java interpreter is used to run the compiled Java bytecode program.(Each type of computer needs its own Java bytecode interpreter, but all these interpreters interpret the same bytecode language.) What is a subroutine? Answer: A subroutine is a set of instructions for performing some task that have been grouped together and given a name.Later, when that task needs to be performed, it is only necessary to call the subroutine by giving its name, rather than repeating the whole sequence of instructions. Java is an objectoriented programming language.What is an object? Answer: An object consists of some data together with a set of subroutines that manipulate that data.(An object is a kind of "module," or selfcontained entity that communicates with the rest of the world through a welldefined interface.An object should represent some coherent concept or realworld object.) What is a variable? Answer: A variable is a memory location that has been given a name so that it can easily be referred to in a program.The variable holds a value, which must be of some specified type.The value can be changed during the course of the execution of the program. Java is a "platformindependent language." What does this mean? Answer: A Java program can be compiled once into a Java Bytecode program.The compiled program can then be run on any computer that has an interpreter for the Java virtual machine.Other languages have to be recompiled for each platform on which they are going to run.The point about Java is that it can be executed on many different types of computers without being recompiled. What is the "Internet"? Give some examples of how it is used. Answer: The Internet is a network connecting millions of computers around the world.Computers connected to the Internet can communicate with each other.The Internet can be used for:

Telnet:which lets a user of one computer log onto another computer remotely. FTP:which is used to copy files between computers. World Wide Web:which lets a user view "pages" of information published on computers around the world.

What is garbage collection? What is the process that is responsible for doing that in java? Answer: Reclaiming the unused memory by the invalid objects.Garbage collector is responsible for this process What kind of thread is the Garbage collector thread? Answer: It is a daemon thread. What is a daemon thread? Answer: 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? Answer: Runtime.getRuntime().exec(.) What is the finalize method do? Answer: Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected. What is mutable object and immutable object? Answer: 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,) What is the basic difference between string and stringbuffer object? Answer: String is an immutable object.StringBuffer is a mutable object. What is the purpose of Void class? Answer: 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? Answer: 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. What is Class.forName() does and how it is useful?

Answer: It loads the class into the ClassLoader.It returns the Class.Using that you can get the instance ( class-instance.newInstance() ). What is the base class for Error and Exception? Answer: Throwable What is the byte range?? Answer: 128 to 127 What is the implementation of destroy method in java..is it native or java code? Answer: This method is not implemented. What is a package? Answer: To group set of classes into a single unit is known as packaging.Packages provides wide namespace ability. What are the approaches that you will follow for making a program very efficient? Answer: 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. What is a DatabaseMetaData? Answer: Comprehensive information about the database as a whole. What is Locale? Answer: A Locale object represents a specific geographical, political, or cultural region How will you load a specific locale? Answer: Using ResourceBundle.getBundle(); What is JIT and its use? Answer: 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. Is JVM a compiler or an interpreter? Answer: Interpreter When you think about optimization, what is the best way to findout the time/memory consuming process? Answer: Using profiler What is the purpose of assert keyword used in JDK1.4.x? Answer: 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. How will you get the platform dependent values like line separator, path separator, etc., ? Answer: Using Sytem.getProperty() (line.separator, path.separator, ) What is skeleton and stub? what is the purpose of those? Answer: 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. What is the final keyword denotes? Answer: 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. What is the significance of ListIterator? Answer: You can iterate back and forth. What is the major difference between LinkedList and ArrayList? Answer: LinkedList are meant for sequential accessing.ArrayList are meant for random accessing. What is nested class? Answer: If all the methods of a inner class is static then it is a nested class. What is inner class?

Answer: If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class. What is composition? Answer: Holding the reference of the other class within some other class is known as composition. What is aggregation? Answer: 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. Can you instantiate the Math class? Answer: You cant instantiate the math class.All the methods in this class are static.And the constructor is not public. What is singleton? Answer: 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 } What is DriverManager? Answer: The basic service to manage set of JDBC drivers. Suppose that temperature measurements were made on each day of 1999 in each of 100 cities.The measurements have been stored in an array int[][]temps=newint[100][365]; where temps[c][d] holds the measurement for city number c on the dth day of the year.Write a code segment that will print out the average temperature, over the course of the whole year, for each city.The average temperature for a city can be obtained by adding up all 365 measurements for that city and dividing the answer by 365.0. Answer: A pseudocode outline of the answer is For each city { Add up all the temperatures for that city Divide the total by 365 and print the answer }

Adding up all the temperatures for a given city itself requires a for loop, so the code segment looks like this: for (int city = 0; city < 100; city++) { int total = 0; for (int day = 0; day < 365; day++) total = total + temps[city][day]; double avg = total / 365.0; System.out.println("Average temp for city number " + city + " is " + avg); } Suppose that a class, Employee, is defined as follows: class Employee { String lastName; String firstName; double hourlyWage; int yearsWithCompany; } Suppose that data about 100 employees is already stored in an array: Employee[] employeeData = new Employee[100]; Write a code segment that will output the first name, last name, and hourly wage of each employee who has been with the company for 20 years or more. Answer: The code segment is as follows: for (int i=0; i < 100; i++) { if ( employeeData[i].yearsWithCompany >= 20 ) System.out.println(employeeData[i].firstName + " " + employeeData[i].lastName + ": " + employeeData[i].hourlyWage); } Suppose that A has been declared and initialized with the statement double[] A = new double[20]; And suppose that A has already been filled with 20 values.Write a program segment that will find the average of all the non-zero numbers in the array.(The average is the sum of the numbers, divided by the number of numbers.Note that you will have to count the number of non-zero entries in the array.) Declare any variables that you use. Answer: int nonzeroCt = 0; double total = 0; double average; for (int i = 0; i < 20; i++) { if (A[i] != 0) { total += A[i]; nonzeroCt++; }

} if (nonzeroCt > 0) average = total / nonzeroCt; else average = 0; What does it mean to say that a program is robust? Answer: A robust program is one that can handle errors and other unexpected conditions in some reasonable way.This means that the program must anticipate possible errors and respond to them if they occur. Why do programming languages require that variables be declared before they are used? What does this have to do with correctness and robustness? Answer: It's a little inconvenient to have to declare every variable before it is used, but its much safer.If the compiler would accept undeclared variables, then it would also accept misspelled names and treat them as valid variables.This can easily lead to incorrect programs.When variables must be declared, the unintentional creation of a variable is simply impossible, and a whole class of possible bugs is avoided. What is "Double.NaN"? Answer: Double.NaN is a special value of type double.(It is defined as a public static member variable of the standard class, Double.) It is used to represent the result of an undefined operation on real numbers.For example, if you divide a number of type double by zero, the result will be Double.NaN. What does it mean to use a null layout manager, and why would you want to do so? Answer: If the layout manager for a container is set to null, then the programmer takes full responsibility for setting the sizes and positions of all of the components in that container.This gives the programmer more control over the layout, but the programmer has to do more work.For simple layouts in a container that does not change size, the setBounds() method of each component can be called when it is added to the container.If the container can change size, then the sizes and positions should be recomputed when a size change occurs.This is done automatically by a layout manager, and this is one good reason to use a layout manager for a container that can change size. What is a JCheckBox and how is it used? Answer: A JCheckBox is a component that has two possible states, "checked" and "unchecked".The user can change the state by clicking on the JCheckBox.If box is a variable of type JCheckBox, then a program can check the box by calling box.setSelected(true) and can uncheck the box by calling box.setSelected(false).The current state can be determined by calling box.isSelected(), which is a boolean-valued function.A JCheckBox generates an event of type ActionEvent when it changes

state.A program can listen for these events if it wants to take some action at the time the state changes.Often, however, it's enough for a program simply to look at the state of the JCheckBox when it needs it. What is a thread ? Answer: A thread, like a program, executes a sequence of instructions from beginning to end.Several threads can execute "in parallel" at the same time.In Java, a thread is represented by an object of type Thread.A Thread object has a run() method to execute (usually the run() method of a Runnable object that is provided when the Thread is constructed).The thread begins executing the run() routine when its start() method is called.At the same time, the rest of the program continues to execute in parallel with the thread. Explain how Timers are used to do animation? Answer: Displaying an animation requires showing a sequence of frames.The frames are shown one after the other, with a short delay between each frame and the next.A Timer can generate a sequence of ActionEvents.When a timer is used to do animation, each event triggers the display of another frame.The ActionListener that processes events from the timer just needs to be programmed to display a frame when its actionPerformed() method is called. Menus can contain sub-menus.What does this mean, and how are sub-menus handled in Java? Answer: Menus can be "hierarchical." A menu can contain other menus, which are called sub-menus.A sub-menu is represented as a single item in the menu that contains it.When the user selects this item, the full sub-menu appears, and the user can select an item from the sub-menu.In Java, a sub-menu is no different from any other menu.A menu can be added to a menu bar, or it can be added to another menu.In the latter case, it becomes a sub-menu. What is the purpose of the JFrame class? Answer: An object belonging to the class JFrame is an independent window on the screen.You don't need a Web browser to create a JFrame like you do for an JApplet.A JFrame can be used as a user interface for a stand-alone program.It is also possible for an applet to open a JFrame. What does the computer do when it executes the following statement? Try to give as complete an answer as possible. Color[]pallette=newColor[12]; Answer: This is a declaration statement, that declares and initializes a variable named pallette of type Color[].The initial value of this variable is a newly created array that has space for 12 items.To be specific about what the computer does: It creates a new 12-element array object on the heap, and it fills each space in that array with null.It

allocates a memory space for the variable, pallette.And it stores a pointer to the new array object in that memory space. What is meant by the basetype of an array? Answer: The base type of an array refers to the type of the items that can be stored in that array.For example, the base type of the array in the previous problem is Color. What does it mean to sort an array? Answer: To sort an array means to rearrange the items in the array so that they are in increasing or decreasing order. What is meant by a dynamic array? What is the advantage of a dynamic array over a regular array? Answer: A dynamic array is like an array in that it is a data structure that stores a sequence of items, all of the same type, in numbered locations.It is different from an array in that there is no preset upper limit on the number of items that it can contain.This is an advantage in situations where a reasonable value for the size of the array is not known at the time it is created. Briefly explain what is meant by the syntax and the semantics of a programming language.Give an example to illustrate the difference between a syntax error and a semantics error? Answer: The syntax of a language is its grammar, and the semantics is its meaning.A program with a syntax error cannot be compiled.A program with a semantic error can be compiled and run, but gives an incorrect result.A missing semicolon in a program is an example of a syntax error, because the compiler will find the error and report it.If N is an integer variable, then the statement "frac = 1/N;" is probably an error of semantics.The value of 1/N will be 0 for any N greater than 1.It's likely that the programmer meant to say 1.0/N. What does the computer do when it executes a variable declaration statement.Give an example. Answer: A variable is a "box", or location, in the computer's memory that has a name.The box holds a value of some specified type.A variable declaration statement is a statement such as int x; which creates the variable x.When the computer executes a variable declaration, it creates the box in memory and associates a name (in this case, x) with that box.Later in the program, that variable can be referred to by name. What is a type, as this term relates to programming?

Answer: A "type" represents a set of possible values.When you specify that a variable has a certain type, you are saying what values it can hold.When you say that an expression is of a certain type, you are saying what values the expression can have.For example, to say that a variable is of type int says that integer values in a certain range can be stored in that variable. One of the primitive types in Java is boolean.What is the boolean type? Where are boolean values used? What are its possible values? Answer: The only values of type boolean are true and false.Expressions of type boolean are used in places where true/false values are expected, such as the conditions in while loops and if statements. Give the meaning of each of the following Java operators - ++, &&, != Answer: The Operators are Explained as follows:

++:The operator ++ is used to add 1 to the value of a variable.For example, "count++" has the same effect as "count = count + 1". &&:The operator && represents the word and.It can be used to combine two boolean values, as in "(x > 0 && y > 0)", which means, "x is greater than 0 and y is greater than 0." !=:The operation != means "is not equal to", as in "if (x != 0)", meaning "if x is not equal to zero.".

Explain what is meant by an assignment statement, and give an example.What are assignment statements used for? Answer: An assignment statement computes a value and stores that value in a variable. Examples include: x = 17; newRow = row; ans = 17*x + 42; An assignment statement is used to change the value of a variable as the program is running.Since the value assigned to the variable can be another variable or an expression, assignments statements can be used to copy data from one place to another in the computer, and to do complex computations. What is meant by precedence of operators? Answer: If two or more operators are used in an expression, and if there are no parentheses to indicate the order in which the operators are to be evaluated, then the computer needs some way of deciding which operator to evaluate first.The order is determined by the precedence of the operators.For example, * has higher precedence than +, so the expression 3+5*7 is evaluated as if it were written 3+(5*7). What is a literal?

Answer: A literal is a sequence of characters used in a program to represent a constant value.For example, 'A' is a literal that represents the value A, of type char, and 17L is a literal that represents the number 17 as a value of type long.A literal is a way of writing a value, and should not be confused with the value itself. In Java, classes have two fundamentally different purposes.What are they? Answer: A class can be used to group together variables and subroutines that are contained in the class.These are called the static members of the class.For example, the subroutine Math.sqrt is a static member of the class called Math.Also, the main routine in any program is a static member of a class.The second possible purpose of a class is to describe and create objects.The class specifies what variables and subroutines are contained in those objects.In this role, classes are used in objectoriented programming (which we haven't studied yet in any detail.) What is the difference between the statement "x = TextIO.getDouble();" and the statement "x = TextIO.getlnDouble();" Answer: Either statements will read a real number input by the user, and store that number in the variable, x.They would both read and return exactly the same value.The difference is that in the second statement, using getlnDouble, after reading the value, the computer will continue reading characters from input up to and including the next carriage return.These extra characters are discarded. Explain briefly what is meant by "pseudocode" and how is it useful in the development of algorithms. Answer: Pseudocode refers to informal descriptions of algorithms, written in a language that imitates the structure of a programming language, but without the strict syntax.Pseudocode can be used in the process of developing an algorithm with stepwise refinement.You can start with a brief pseudocode description of the algorithm and then add detail to the description through a series of refinements until you have something that can be translated easily into a program written in an actual programming language. What is a block statement? How are block statements used in Java programs? Answer: A block statement is just a sequence of Java statements enclosed between braces, { and }.The body of a subroutine is a block statement.Block statements are often used in control structures.A block statement is generally used to group together several statements so that they can be used in a situation that only calls for a single statement.For example, the syntax of a while loop calls for a single statement: "while (condition) do statement".However, the statement can be a block statement, giving the structure: "while (condition) { statement; statement;...}". What is the main difference between a while loop and a do..while loop?

Answer: Both types of loop repeat a block of statements until some condition becomes false.The main difference is that in a while loop, the condition is tested at the beginning of the loop, and in a do..while loop, the condition is tested at the end of the loop.It is possible that the body of a while loop might not be executed at all.However, the body of a do..while loop is executed at least once since the condition for ending the loop is not tested until the body of the loop has been executed. What does it mean to prime a loop? Answer: The condition at the beginning of a while loop has to make sense even the first time it is tested, before the body of the loop is executed.To prime the loop is to set things up before the loop starts so that the test makes sense (that is, the variables that it contains have reasonable values).For example, if the test in the loop is "while the user's response is yes," then you will have to prime the loop by getting a response from the user (or making one up) before the loop. Explain what is meant by an animation and how a computer displays an animation? Answer: An animation consists of a series of "frames." Each frame is a still image, but there are slight differences from one frame to the next.When the images are displayed rapidly one frame after another, the eye perceives motion.A computer displays an animation by showing one image on the screen, then replacing it with the next image, then the next, and so on. Write a for loop that will print out all the multiples of 3 from 3 to 36, that is: 3 6 9 12 15 18 21 24 27 30 33 36. Answer: Here are two possible answers.Assume that N has been declared to be a variable of type int: for ( N = 3;N <= 36;N = N + 3 ) { System.out.println( N ); } or for ( N = 3;N <= 36;N++ ) { if ( N % 3 == 0 ) System.out.println( N ); } Fill in the following main() routine so that it will ask the user to enter an integer, read the user's response, and tell the user whether the number entered is even or odd.(You can use TextIO.getInt() to read the integer.Recall that an integer n is even if n % 2 == 0.) public static void main(String[] args) {

} Answer: The problem already gives an outline of the program.The last step, telling the user whether the number is even or odd, requires an if statement to decide between the two possibilities. public static void main (String[] args) { int n; TextIO.put("Type an integer: "); n = TextIO.getInt(); if (n % 2 == 0) System.out.println("That's an even number."); Else System.out.println("That's an odd number."); } Show the exact output that would be produced by the following main() routine: public static void main(String[] args) { int N; N = 1; while (N <= 32) { N = 2 * N; System.out.println(N); } } Answer: The exact output printed by this program is: 2 4 8 16 32 64 What output is produced by the following program segment? Why? String name; int i; boolean startWord; name = "Richard M.Nixon"; startWord = true; for (i = 0; i < name.length(); i++) { if (startWord) System.out.println(name.charAt(i)); if (name.charAt(i) == ' ')

startWord = true; else startWord = false; } Answer: This is a tough one! The output from this program consists of the three lines: R M N As the for loop in this code segment is executed, name.charAt(i) represents each of the characters in the string "Richard M.Nixon" in succession.The statement System.out.println(name.charAt(i)) outputs the single character name.charAt(i) on a line by itself.However, this output statement occurs inside an if statement, so only some of the characters are output.The character is output if startWord is true.This variable is initialized to true, so when i is 0, startWord is true, and the first character in the string, 'R', is output.Then, since 'R' does not equal ' ', startWorld becomes false, so no more characters are output until startWord becomes true again.This happens when name.charAt(i) is a space, that is, just before the 'M' is processed and again just before the 'N' is processed.In fact whatever the value of name, this for statement would print the first character in name and every character in name that follows a space A "black box" has an interface and an implementation.Explain what is meant by the terms interface and implementation. Answer: The interface of a black box is its connection with the rest of the world, such as the name and parameters of a subroutine or the dial for setting the temperature on a thermostat.The implementation refers to internal workings of the black box.To use the black box, you need to understand its interface, but you don't need to know anything about the implementation.

Explain what is meant by the client / server model of network communication. Answer: In the client/server model, a server program runs on a computer somewhere on the Internet and "listens" for connection requests from client programs.The server makes some service available.A client program connects to the server to access that service.For example, a Web server has a collection of Web pages.A Web browser acts as a client for the Web server.It makes a connection to the server and sends a request for one of its pages.The server responds by transmitting a copy of the requested page back to the client. What is a socket? Answer: A socket represents one endpoint of a network connection.A program uses a socket to communicate with another program over the network.Data written by a

program to the socket at one end of the connection is transmitted to the socket on the other end of the connection, where it can be read by the program at that end. What is a ServerSocket and how is it used? Answer: A SeverSocket is used by a server program to listen for connection requests from client programs.If listener refers to an object that belongs to Java's ServerSocket class, then calling the function listener.accept() will wait for a connection request and will return a Socket object that can be used to communicate with the client that made the request. Network server programs are often multithreaded.Explain what this means and why it is true? Answer: A multi-threaded server creates a new thread to handle each client connection that it accepts.A server program is generally designed to process connection requests from many clients.It runs in an infinite loop in which it accepts a connection request and processes it.If the processing takes a significant amount of time, it's not a good idea to make the other clients wait while the current client is processed.The solution is for the server to make a new thread to handle each client connection.The server can continue to accept other client connections even while the first client is being serviced. Explain what is meant by a recursive subroutine. Answer: A recursive subroutine is simply one that calls itself either directly or through a chain of calls involving other subroutines. What are the three operations on a stack? Answer: The three stack operations are push, pop, and isEmpty.The definitions of these operations are: push(item) adds the specified item to the top of the stack; pop() removes the top item of the stack and returns it; and isEmpty() is a boolean-valued function that returns true if there are no items on the stack. What is the basic difference between a stack and a queue? Answer: In a stack, items are added to the stack and removed from the stack on the same end (called the "top" of the stack).In a queue, items are added at one end (the "back") and removed at the other end (the "front").Because of this difference, a queue is a FIFO structure (items are removed in the same order in which they were added), and a stack is a LIFO structure (the item that is popped from a stack is the one that was added most recently). What is an activation record? What role does a stack of activation records play in a computer? Answer: When a subroutine is called, an activation record is created to hold the information that is needed for the execution of the subroutine, such as the values of the parameters and local variables.This activation record is stored on a stack of

activation records.A stack is used since one subroutine can call another, which can then call a third, and so on.Because of this, many activation records can be in use at the same time.The data structure is a stack because an activation record has to continue to exist while all the subroutines that are called by the subroutine are executed.While they are being executed, the stack of activation records can grow and shrink as subroutines are called and return. What is a postorder traversal of a binary tree? Answer: In a traversal of a binary tree, all the nodes are processed in some way.(For example, they might be printed.) In a postorder traversal, the order of processing is defined by the rule: For each node, the nodes in the left subtree of that node are processed first.Then the nodes in the right subtree are processed.Finally, the node itself is processed. Explaining what is meant by parsing a computer program. Answer: To parse a computer program means to determine its syntactic structure, that is, to figure out how it can be constructed using the rules of a grammar (such as a BNF grammar). A subroutine is said to have a contract.What is meant by the contract of a subroutine? When you want to use a subroutine, why is it important to understand its contract? The contract has both "syntactic" and "semantic" aspects.What is the syntactic aspect? What is the semantic aspect? Answer: The contract of a subroutine says what must be done to call the subroutine correctly and what it will do when it is called.It is, in short, everything a programmer needs to know about the subroutine in order to use it correctly.(It does not include the "insides," or implementation, of the subroutine.) The syntactic component of a subroutine's contract includes the name of the subroutine, the number of parameters, and the type of each parameter.This is the information needed to write a subroutine call statement that can be successfully compiled.The semantic component of the contract specifies the meaning of the subroutine, that is, the task that the subroutine performs.It might also specify limitations on what parameter values the subroutine can process correctly.The semantic component is not part of the program.It is generally expressed in comments. Briefly explain how subroutines can be a useful tool in the top-down design of programs. Answer: Top-down refers to starting from the overall problem to be solved, and breaking it up into smaller problems that can be solved separately.When designing a program to solve the problem, you can simply make up a subroutine to solve each of the smaller problems.Then you can separately design and test each subroutine. Discuss the concept of parameters.What are parameters for? What is the difference between formal parameters and actual parameters?

Answer: Parameters are used for communication between a subroutine and the part of the program that calls the subroutine.If a subroutine is thought of as a black box, then parameters are part of the interface to that black box.Formal parameters are found in the subroutine definition.Actual parameters are found in subroutine call statements.When the subroutine is called, the values of the actual parameters are assigned to the formal parameters before the body of the subroutine is executed. Give two different reasons for using named constants Answer: A constant has a meaningful name, which makes the program easier to read.It's easier to understand what a name like INTEREST_RATE is for than it is to figure out how a literal number like 0.07 is being used. A second reason for using named constants is that it's easy to modify the value of the constant if that becomes necessary.If a literal value is used throughout the program, the programmer has to track down each occurrence of the value and change it.When a constant is used correctly, it is only necessary to change the value assigned to the constant at one point in the program. A third reason is that using the final modifier protects the value of a variable from being changed.This is especially important for member variables that are accessible from outside the class where they are declared. What is an API? Give an example. Answer: An API is an Applications Programming Interface.It is the interface to a "toolbox" of subroutines that someone has written.It tells you what routines are available, how to call them, and what they do, but it does not tell you how the subroutines are implemented.An example is the standard Java API which describes the interfaces of all the subroutines in all the classes that are available in such packages as java.lang and java.awt. Write a subroutine named "stars" that will output a line of stars to standard output.(A star is the character "*".) The number of stars should be given as a parameter to the subroutine.Use a for loop.For example, the command "stars(20)" would output ******************** Answer: The subroutine could be written as follows. static void stars(int numberOfStars) { for (int i = 0; i < numberOfStars; i++) { System.out.print('*'); } System.out.println(); } Write a main() routine that uses the subroutine that you wrote for Question 7 to output 10 lines of stars with 1 star in the first line, 2 stars in the second line,

and so on, as shown below. * ** *** **** ***** ****** ******* ******** ********* ********** Answer: The main() routine can use a for loop that calls the stars() subroutine ten times, once to produce each line of output.(An occasional beginner's mistake in this problem is to rewrite the body of the subroutine inside the main() routine, instead of just calling it by name.) Here is the main routine -- which would, of course, have to be put together with the subroutine in a class in order to be used. public static void main(String[] args) { int line; for ( line = 1;line <= 10;line++ ) { stars( line ); } } Write a function named countChars that has a String and a char as parameters.The function should count the number of times the character occurs in the string, and it should return the result as the value of the function. Answer: The returned value will be of type int.The function simply uses a for loop to look at each character in the string.When the character in the string matches the parameter value, it is counted. static int countChars( String str, char searchChar ) { int i; char ch; int count; count = 0; for ( i = 0;i < str.length();i++ ) { ch = str.charAt(i); if ( ch == searchChar ) count++; } return count; } Write a subroutine with three parameters of type int.The subroutine should determine which of its parameters is smallest.The value of the smallest parameter should be returned as the value of the subroutine.

Answer: I'll call the subroutine smallest and the three parameters x, y, and z.The value returned by the subroutine has to be either x or y or z.The answer will be x if x is less than or equal to both y and z.The correct syntax for checking this is "if (x <= y && x <= z).Similarly for y.The only other remaining possibility is z, so there is no necessity for making any further test before returning z. static int smallest(int x, int y, int z) { if (x <= y && x <= z) { return x; } else if (y <= x && y <= z) { return y; } else return z; } Note: Since a return statement causes the computer to terminate the execution of a subroutine anyway, this could also be written as follows, without the elses: static int smallest(int x, int y, int z) { if (x <= y && x <= z) { return x; } if (y <= x && y <= z) { return y; } return z; } Object-oriented programming uses classes and objects.What are classes and what are objects? What is the relationship between classes and objects? Answer: When used in object-oriented programming, a class is a factory for creating objects.(We are talking here about the non-static part of the class.) An object is a collection of data and behaviors that represent some entity (real or abstract).A class defines the structure and behaviors of all entities of a given type.An object is one particular "instance" of that type of entity.For example, if Dog is a class, than Lassie would be an object of type Dog. Explain carefully what null means in Java, and why this special value is necessary. Answer: When a variable is of object type (that is, declared with a class as its type rather than one of Java's primitive types), the value stored in the variable is not an object.Objects exist in a part of memory called the heap, and the variable holds a pointer or reference to the object.Null is a special value that can be stored in a variable to indicate that it does not actually point to any object.

What is a constructor? What is the purpose of a constructor in a class? Answer: A constructor is a special kind of subroutine in a class.It has the same name as the name of the class, and it has no return type, not even void.A constructor is called with the new operator in order to create a new object.Its main purpose is to initialize the newly created object, but in fact, it can do anything that the programmer wants it to do. Suppose that Kumquat is the name of a class and that fruit is a variable of type Kumquat.What is the meaning of the statement "fruit = new Kumquat();"? That is, what does the computer do when it executes this statement? (Try to give a complete answer.The computer does several things.) Answer: This statement creates a new object belonging to the class Kumquat, and it stores a reference to that object in the variable fruit.More specifically, when the computer executes this statement, it allocates memory to hold a new object of type Kumquat.It calls a constructor, which can initialize the instance variables of the object as well as perform other tasks.A reference to the new object is returned as the value of the expression "new Kumquat()".Finally, the assignment statement stores the reference in the variable, fruit.So, fruit can now be used to access the new object. What is meant by the terms instance variable and instance method? Answer: Instance variables and instance methods are non-static variables and methods in a class.This means that they do not belong to the class itself.Instead, they specify what variables and methods are in an object that belongs to that class.That is, the class contains the source code that defines instance variables and instance methods, but actual instance variables and instance methods are contained in object. Explain what is meant by the terms subclass and superclass. Answer: In object oriented programming, one class can inherit all the properties and behaviors from another class.It can then add to and modify what it inherits.The class that inherits is called a subclass, and the class that it inherits from is said to be its superclass.In Java, the fact that ClassA is a subclass of ClassB is indicated in the definition of ClassA as follows: class ClassA extends ClassB {...} Explain the term polymorphism. Answer: Polymorphism refers to the fact that different objects can respond to the same method in different ways, depending on the actual type of the object.This can occur because a method can be overridden in a subclass.In that case, objects belonging to the subclass will respond to the method differently from objects belonging to the superclass. Java uses "garbage collection" for memory management.Explain what is meant here by garbage collection.What is the alternative to garbage collection?

Answer: The purpose of garbage collection is to identify objects that can no longer be used, and to dispose of such objects and reclaim the memory space that they occupy.If garbage collection is not used, then the programmer must be responsible for keeping track of which objects are still in use and disposing of objects when they are no longer needed.If the programmer makes a mistake, then there is a "memory leak," which might gradually fill up memory with useless objects until the program crashes for lack of memory. For this problem, you should write a very simple but complete class.The class represents a counter that counts 0, 1, 2, 3, 4,....The name of the class should be Counter.It has one private instance variable representing the value of the counter.It has two instance methods: increment() adds one to the counter value, and getValue() returns the current counter value.Write a complete definition for the class, Counter. Answer: Here is a possible answer. public class Counter { private int value = 0; public void increment() { value++; } public int getValue() { return value; } } This problem uses the Counter class from Question 9.The following program segment is meant to simulate tossing a coin 100 times.It should use two Counter objects, headCount and tailCount, to count the number of heads and the number of tails.Fill in the blanks so that it will do so. Counter headCount, tailCount; tailCount = new Counter(); headCount = new Counter(); for ( int flip = 0;flip < 100;flip++ ) { if (Math.random() < 0.5) ______________________; else ______________________; } System.out.println("There were " + ___________________ + " heads."); System.out.println("There were " + ___________________ + " tails."); Answer: The variable headCount is a variable of type Counter, so the only thing that you can do with it is call the instance methods headCount.increment() and headCount.getValue().Call headCount.increment() to add one to the counter.Call headCount.getValue() to discover the current value of the counter.Note that you can't get at the value of the counter directly, since the variable that holds the value is a

private instance variables in the Counter object.Similarly for tailCount.Here is the program with calls to these instance methods filled in: Counter headCount, tailCount; tailCount = new Counter(); headCount = new Counter(); for ( int flip = 0;flip < 100;flip++ ) { if (Math.random() < 0.5) headCount.increment(); else tailCount.increment(); } System.out.println(("There were " + headCount.getValue() + " heads."); System.out.println(("There were " + tailCount.getValue() + " tails."); Programs written for a graphical user interface have to deal with "events." Explain what is meant by the term event.Give at least two different examples of events, and discuss how a program might respond to those events. Answer: An event is anything that can occur asynchronously, not under the control of the program, to which the program might want to respond.GUI programs are said to be "event-driven" because for the most part, such programs simply wait for events and respond to them when they occur.In many (but not all) cases, an event is the result of a user action, such as when the user clicks the mouse button, types a character, or clicks a button.The program might respond to a mouse-click on a canvas by drawing a shape, to a typed character by adding the character to an input box, or to a click on a button by clearing a drawing.More generally, a programmer can set up any desired response to an event by writing an event-handling routine for that event. What is an event loop? Answer: An event-driven program doesn't have a main() routine that says what will happen from beginning to end, in a step-by-step fashion.Instead, the program runs in a loop that says: while the program is still running: Wait for the next event Process the event This is called an event loop.In Java, the event loop is executed by the system.The system waits for events to happen.When an event occurs, the system calls a routine that has been designated to handle events of that type. Explain carefully what the repaint() method does. Answer: The repaint() method is called to notify the system that the applet (or other component for which it is called) needs to be redrawn.It does not itself do any drawing (neither directly nor by calling a paint() or paintComponent() routine).You should call repaint() when you have made some change to the state of the applet that

requires its appearance to change.Sometime shortly after you call it, the system will call the applet's paint() routine or the component's paintComponent() routine. Suppose that you are writing an applet, and you want the applet to respond in some way when the user clicks the mouse on the applet.What are the four things you need to remember to put into the source code of your applet? Answer: The four things are as follows:

Since the event and listener classes are defined in the java.awt.event package, you have to put "import java.awt.event.*;" at the beginning of the source code, before the class definition. The applet class must be declared to implement the MouseListener interface, by adding the words "implements MouseListener" to the heading.For example: "public class MyApplet extends JApplet implements MouseListener".(It is also possible for another object besides the applet to listen for the mouse events.) The class must include definitions for each of the five methods specified in the MouseListener interface.Even if a method is not going to do anything, it has to be defined, with an empty body. The applet (or other listening object) must be registered to listen for mouse events by calling addMouseListener().This is usually done in the init() method of the applet.

Java has a standard class called MouseEvent.What is the purpose of this class? What does an object of type MouseEvent do? Answer: When an event occurs, the system packages information about the event into an object.That object is passed as a parameter to the event-handling routine.Different classes of objects represent different types of events.An object of type MouseEvent represents a mouse or mouse motion event.It contains information about the location of the mouse cursor and any modifier keys that the user is holding down.This information can be obtained by calling the instance methods of the object.For example, if evt is a MouseEvent object, then evt.getX() is the x-coordinate of the mouse cursor, and evt.isShiftDown() is a boolean value that tells you whether the user was holding down the Shift key. Explain what is meant by input focus.How is the input focus managed in a Java GUI program? Answer: When the user uses the keyboard, the events that are generated are directed to some component.At a given time, there is just one component that can get keyboard events.That component is said to have the input focus.Usually, the appearance of a component changes if it has the input focus and wants to receive user input from the keyboard.For example, there might be a blinking text cursor in the component, or the component might be hilited with a colored border.In order to change its appearance in this way, the component needs to be notified when it gains or loses the focus.In Java, a component gets this notification by listening for focus events.

Some components, including applets and canvasses, do not get the input focus unless they request it by calling requestFocus().If one of these components needs to process keyboard events, it should also listen for mouse events and call requestFocus() when the user clicks on the component.(Unfortunately, this rule is not enforced uniformly on all platforms.) Java has a standard class called JPanel.Discuss two ways in which JPanels can be used. Answer: A JPanel is a type of component.That is, it is a visible element of a GUI.By itself, a JPanel is simply a blank rectangular region on the screen.However, a JPanel is a "container", which means that other components can be added to it and will then appear on the screen inside the JPanel.A JPanel can also be used as a drawing surface. The two ways are as follows:

paintComponent()An object belonging to that subclass can then be added to an applet or other component.The paintComponent()This method defines how that object will draw itself on the screen.

What is the FontMetrics class used for? Answer: An object that belongs to the class FontMetrics can be used to obtain information about the sizes of characters and strings that are drawn in a specific font.The font is specified when the FontMetrics object is created.If fm is a variable of type FontMetrics, then, for example, fm.stringWidth(str) gives the width of the string str and fm.getHeight() is the usual amount of vertical space allowed for one line of text.This information could be used, for example, for positioning the string is a component. What are off-screen images? How are they used? Why are they important? What does this have to do with animation? Answer: In Java, an off-screen image is an object belonging to the class Image and created with the createImage() function.An off-screen image is a segment of the computer's memory that can be used as a drawing surface.What is drawn to the offscreen image is not visible on the screen, but the Image can be quickly copied onto the screen with a drawImage() command.It is important to use an off-screen image in a situation where the user should not see the process of drawing the image.This is true, for example, in animation.Each frame of the animation can be composed in an off-screen Image and then copied to the screen when it is complete.The alternative would be to erase the screen and draw the next frame directly on the screen.This causes unacceptable flickering of the image.By default, Swing already uses an offscreen image for double-buffering an applet or frame, so you don't have to program it yourself just to do simple animation. One of the main classes in Swing is the JComponent class.What is meant by a component? What are some examples?

Answer: A JComponent represents a visual component of the computer's graphical user interface.A JComponent is not completely independent.It must be added to a "container," such as an applet or a frame.Examples of JComponents are JButtons, JTextFields, and JPanels. What is the function of a LayoutManager in Java? Answer: A LayoutManager implements some policy for laying out all the visual components that have been added to a container, such as a JPanel or the content pane of a JApplet.That is, it sets the sizes and positions of the components.Different types of layout managers have different rules about how components are to be arranged.Some standard layout manager classes are BorderLayout and GridLayout. Explain how preconditions can be used as an aid in writing correct programs. Answer: Suppose that a programmer recognizes a precondition at some point in a program.This is a signal to the programmer that an error might occur if the precondtion is not met.In order to have a correct and robust program, the programmer must deal with the possible error.There are several approaches that the programmer can take.One approach is to use an if statement to test whether the precondition is satisfied.If not, the programmer can take some other action such as printing an error message and terminating the program.Another approach is to use a try statement to catch and respond to the error.This is really just a cleaner way of accomplishing the same thing as the first approach.The best approach, when it is possible, is to ensure that the precondition is satisfied as a result of what has already been done in the program.For example, if the precondition is that x >= 0, and the preceding statement is "x = Math.abs(y);", then we know that the precondition is satisfied, since the absolute value of any number is greater than or equal to zero. Java has a predefined class called Throwable.What does this class represent? Why does it exist? Answer: The class Throwable represents all possible objects that can be thrown by a throw statement and caught by a catch clause in a try...catch statement.That is, the thrown object must belong to the class Throwable or to one of its (many) subclasses such as Exception and RuntimeException.The object carries information about an exception from the point where the exception occurs to the point where it is caught and handled. Some classes of exceptions require mandatory exception handling.Explain what this means. Answer: Subclasses of the class Exception which are not subclasses of RuntimeException require mandatory exception handling.This has two consequences: First, if a subroutine can throw such an exception, then it must declare this fact by adding a throws clause to the subroutine heading.Second, if a routine includes any code that can generate such an exception, then the routine must deal with the exception.It can do this by including the code in a try statement that has a catch clause

to handle the exception.Or it can use a throws clause to declare that calling the subroutine might throw the exception. Consider a subroutine processData that has the header static void processData() throws IOException Write a try...catch statement that calls this subroutine and prints an error message if an IOException occurs. Answer: try { processData(); } catch (IOException e) { System.out.println( "An IOException occurred while precessing the data."); } Why should a subroutine throw an exception when it encounters an error? Why not just terminate the program? Answer: Terminating the program is too drastic, and this tactic certainly doesn't lead to robust programs! It's likely that the subroutine doesn't know what to do with the error, but that doesn't mean that it should abort the whole program.When the subroutine throws an exception, the subroutine is terminated, but the program that called the subroutine still has a chance to catch the exception and handle it.In effect, the subroutine is saying "Alright, I'm giving up.Let's hope someone else can deal with the problem." In Java, input/output is done using streams.Streams are an abstraction.Explain what this means and why it is important. Answer: A stream represents a source from which data can be read or a destination to which data can be written.A stream is an abstraction because it represents the abstract idea of a source or destination of data, as opposed to specific, concrete sources and destinations such as a particular file or network connection.The stream abstraction is important because it allows programmers to do input/output using the same methods for a wide variety of data sources and destinations.It hides the details of working with files, networks, and the screen and keyboard. Java has two types of streams: character streams and byte streams.Why? What is the difference between the two types of streams? Answer: Character streams are for working with data in human-readable format, that is, data expressed as sequences of characters.Byte streams are for data expressed in the machine-readable format that is used internally in the computer to represent the data while a program is running.It is very efficient for a computer to read and write data in machine format, since no translation of the data is necessary.However, if a person must deal directly with the data, then character streams should be used so that the data is presented in human-readable form.

What is a file? Why are files necessary? Answer: A file is a collection of data that has been given a name and stored on some permanent storage device such as a hard disk or floppy disk.Files are necessary because data stored in the computer's RAM is lost whenever the computer is turned off.Data that is to be saved permanently must be stored in a file. What is the point of the following statement? out = new PrintWriter( new FileWriter("data.dat") ); Why would you need a statement that involves two different stream classes, PrintWriter and FileWriter? Answer: The PrintWriter class is being used as a "wrapper" for the FileWriter class.A FileWriter is a stream object that knows how to send individual characters to a file.By wrapping this in a PrintWriter, you get the ability to write other data types such as ints, doubles, and Strings to the file using the PrintWriter's print() and println() methods.Wrapping the FileWriter in a PrintWriter adds capabilities to the file output stream but still sends the data to the same destination. The package java.io includes a class named URL.What does an object of type URL represent, and how is it used? Answer: A url is an address for a web page (or other information) on the Internet.For example, "http://math.hws.edu/javanotes/index.html" is a url that refers to the main page of the current edition of this on-line textbook.A URL object represents such an address.Once you have a URL object, you can call its openConnection() method to access the information at the url address that it represents.

What is the purpose of the following subroutine? What is the meaning of the value that it returns, in terms of the value of its parameter? static String concat( String[] str ) { if (str == null) return ""; String ans = ""; for (int i = 0; i < str.length; i++) { ans = ans + str[i]; return ans; } Answer: The purpose of the subroutine is to chain all the strings in an array of strings into one long string.If the array parameter is null, then there are no strings, and the empty string is returned.Otherwise, the value returned is the string made up of all the strings from the array.For example, if stringList is an array declared as String[] stringList = { "Put 'em ", "all", " together" }; then the value of concat(stringList) is "Put 'em all together".

Show the exact output produced by the following code segment. char[][] pic = new char[6][6]; for (int i = 0; i < 6; i++) for (int j = 0; j < 6; j++) { if ( i == j || i == 0 || i == 5 ) pic[i][j] = '*'; else pic[i][j] = '.'; } for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) System.out.print(pic[i][j]); System.out.println(); } Answer: The output consists of six lines, with each line containing six characters.In the first line, i is 0, so all the characters are *'s.In the last line, i is 5, so all the characters are *'s.In each of the four lines in the middle, one of the characters is a * and the rest are periods.The output is ****** .*.... ..*... ...*.. ....*. ****** It might help to look at the array items that are printed on each line.Note that pic[row] [col] is '*' if row is 0 or if row is 5 or if row and col are equal. pic[0][0] pic[0][1] pic[0][2] pic[0][3] pic[0][4] pic[0][5] pic[1][0] pic[1][1] pic[1][2] pic[1][3] pic[1][4] pic[1][5] pic[2][0] pic[2][1] pic[2][2] pic[2][3] pic[2][4] pic[2][5] pic[3][0] pic[3][1] pic[3][2] pic[3][3] pic[3][4] pic[3][5] pic[4][0] pic[4][1] pic[4][2] pic[4][3] pic[4][4] pic[4][5] pic[5][0] pic[5][1] pic[5][2] pic[5][3] pic[5][4] pic[5][5] Write a complete subroutine that finds the largest value in an array of ints.The subroutine should have one parameter, which is an array of type int[].The largest number in the array should be returned as the value of the subroutine. Answer: public static int getMax(int[] list) { int max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; }

return max; } What is a precondition? Give an example. Answer: A precondition is a condition that has to hold at given point in the execution of a program, if the execution of the program is to continue correctly.For example, the statement "x = A[i];" has two preconditions: that A is not null and that 0 <= i < A.length.If either of these preconditions is violated, then the execution of the statement will generate an error. Also, a precondition of a subroutine is a condition that has to be true when the subroutine is called in order for the subroutine to work correctly. Is "abc" a primitive value? Answer: The String literal "abc" is not a primitive value. It is a String object. What restrictions are placed on the values of each case of a switch statement? Answer: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. What modifiers may be used with an interface declaration? Answer: An interface may be declared as public or abstract. Is a class a subclass of itself? Answer: A class is a subclass of itself. What is the difference between a while statement and a do statement? Answer: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement 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 body of a loop at least once. What modifiers can be used with a local inner class? Answer: A local inner class may be final or abstract. What is the purpose of the File class? Answer: The File class is used to create objects that provide access to the files and directories of a local file system. Can an exception be rethrown?

Answer: Yes, an exception can be rethrown. When does the compiler supply a default constructor for a class? Answer: The compiler supplies a default constructor for a class if no other constructors are provided. If a method is declared as protected, where may the method be accessed? Answer: Classes or interfaces of the same package or may only access a protected method by subclasses of the class in which it is declared. Which non-Unicode letter characters may be used as the first character of an identifier? Answer: The non-Unicode letter characters $ and _ may appear as the first character of an identifier. What restrictions are placed on method overloading? Answer: Two methods may not have the same name and argument list but different return types. What is casting? Answer: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. What is the return type of a program's main() method? Answer: A program's main() method has a void return type. What class of exceptions are generated by the Java run-time system? Answer: The Java runtime system generates RuntimeException and Error exceptions. What class allows you to read objects directly from a stream? Answer: The ObjectInputStream class supports the reading of objects from input streams. Is "abc" a primitive value? Answer: The String literal "abc" is not a primitive value. It is a String object. What restrictions are placed on the values of each case of a switch statement?

Answer: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. What modifiers may be used with an interface declaration? Answer: An interface may be declared as public or abstract. Is a class a subclass of itself? Answer: A class is a subclass of itself. What is the difference between a while statement and a do statement?
Answer:

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement 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 body of a loop at least once. What modifiers can be used with a local inner class? Answer: A local inner class may be final or abstract. What is the purpose of the File class? Answer: The File class is used to create objects that provide access to the files and directories of a local file system. Can an exception be rethrown? Answer: Yes, an exception can be rethrown. When does the compiler supply a default constructor for a class? Answer: The compiler supplies a default constructor for a class if no other constructors are provided. If a method is declared as protected, where may the method be accessed? Answer: Classes or interfaces of the same package or may only access a protected method by subclasses of the class in which it is declared. Which non-Unicode letter characters may be used as the first character of an identifier? Answer: The non-Unicode letter characters $ and _ may appear as the first character of an identifier. What restrictions are placed on method overloading?

Answer: Two methods may not have the same name and argument list but different return types. What is casting? Answer: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. What is the return type of a program's main() method? Answer: A program's main() method has a void return type. What class of exceptions are generated by the Java run-time system? Answer: The Java runtime system generates RuntimeException and Error exceptions. What class allows you to read objects directly from a stream? Answer: The ObjectInputStream class supports the reading of objects from input streams. What is the difference between a field variable and a local variable? Answer: A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method. How are this() and super() used with constructors? Answer: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution? Answer: A method's throws clause must declare any checked exceptions that are not caught within the body of the method. Why are the methods of the Math class static? Answer: So they can be invoked as if they are a mathematical code library. What are the legal operands of the instanceof operator? Answer: The left operand is an object reference or null value and the right operand is a class, interface, or array type.

What an I/O filter? Answer: An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. If an object is garbage collected, can it become reachable again? Answer: Once an object is garbage collected, it ceases to exist. It can no longer become reachable again. What are E and PI? Answer: E is the base of the natural logarithm and PI is mathematical value pi. Are true and false keywords? Answer: The values true and false are not keywords. What is the difference between the File and RandomAccessFile classes? Answer: The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. What happens when you add a double value to a String? Answer: The result is a String object. What is your platform's default character encoding? Answer: If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1. Which package is always imported by default? Answer: The java.lang package is always imported by default. What interface must an object implement before it can be written to a stream as an object? Answer: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. How can my application get to know when a HttpSession is removed? Answer: Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in

valueUnbound() method. Create an instance of that class and put that instance in HttpSession. Whats the difference between notify() and notifyAll()? Answer: notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume. Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()? Answer: The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That's just the way it works, you'll get used to it. It's really a lot safer this way. However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn't need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can't use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can't use it on java.lang.Math at all, because Math is a "final" class which means it can't be extended. Why are there no global variables in Java? Answer: Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of ObjectOriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables. What does it mean that a class or member is final? Answer: A final class can no longer be subclassed. Mostly 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. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it's initialized, and it must include an initializer statement where it's declared. For example, public final double c = 2.998; It's also possible to make a static field final to get the effect of C++'s const statement or some uses of C's #define, e.g. public static final double c = 2.998; What does it mean that a method or class is abstract?

Answer: An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this: public abstract class Container extends Component {Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example, public abstract float price();Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract. What is a transient variable? Answer: transient variable is a variable that may not be serialized. How are Observer and Observable used? Answer: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. Can a lock be acquired on a class? Answer: Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. What state does a thread enter when it terminates its processing? Answer: When a thread terminates its processing, it enters the dead state. How does Java handle integer overflows and underflows? Answer: 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 difference between the >> and >>> operators? Answer: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. Is sizeof a keyword? Answer: The sizeof operator is not a keyword. Does garbage collection guarantee that a program will not run out of memory? Answer: 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. Can an object's finalize() method be invoked while it is reachable? Answer: 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 value does readLine() return when it has reached the end of a file? Answer: The readLine() method returns null when it has reached the end of a file. Can a for statement loop indefinitely? Answer: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;); To what value is a variable of the String type automatically initialized? Answer: The default value of an String type is null. What is a task's priority and how is it used in scheduling? Answer: 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 is the range of the short type? Answer: The range of the short type is (215) to 215 - 1. What is the purpose of garbage collection? Answer: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. What do you understand by private, protected and public? Answer: These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package. What is Downcasting ? Answer: Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy.

Can a method be overloaded based on different return type but same argument type? Answer: No, because the methods can be called without using their return type in which case there is ambiquity for the compiler. What happens to a static var that is defined within a method of a class? Answer: Can't do it. You'll get a compilation error. How many static init can you have? Answer: As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime? Answer: The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation. What does the "final" keyword mean in front of a variable? A method? A class? Answer: FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived. What is the difference between instanceof and isInstance? Answer: instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise. Why does it take so much time to access an Applet having Swing Components the first time? Answer: Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.

S-ar putea să vă placă și