Java Interview Questions and Answers What is Collection API ?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. xample of classes! "ash#et, "ash$ap, Array%ist, %in&ed%ist, Tree#et and Tree$ap. xample of interfaces! Collection, #et, %ist and $ap. Is Iterator a Class or Interface? What is its use?
Answer! Iterator is an interface interface which is used to step step through the elements of a Collection. Collection. What is similarities/difference between an Abstract class and Interface?
'ifferences are as follows! Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. A Class Class may implement several interfaces. interfaces. (ut in case of abstract abstract class, a class class may extend only one abstract class. Interfaces are slow as it re)uires extra indirection to to find corresponding method in in the actual class. Abstract Abstract classes are fast. #imilarities! *either Abstract classes or Interface can be instantiated. Java Interview Questions - How to define an Abstract class? A class class containing abstract method is called Abstract Abstract class. An Abstract Abstract class can+t be instantiated. xample of Abstract class! abstract class testAbstractClass protected #tring my#tringpublic #tring get$y#tring/ return my#tring0 public abstract string anyAbstract1unction/0 How to define an Interface in Java ?
In 2ava Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface. maple of Interface! public interface sampleInterface public void function3ne/public long C3*#TA*T43* 5 67770 If a class is located in a paca!e" what do #ou need to chan!e in the $% environment to be able to use it?
8ou 8ou need to add a directory or a jar file that contains the pac&age directories to the C%A##PAT" C%A##PAT" environment variable. %et+s say a class mployee belongs to a pac&age com.xy9.hr- and is located in the file c!:dev:com:xy9:hr:mployee.java. In this case, you+d need to add c!:dev to the variable C%A##PAT". C%A##PAT". If this class contains the method main/, you could test it from a command prompt window as follows! c!:;java com.xy9.hr.mployee com.xy9.hr.mployee How man# methods in the %eriali&able interface?
There is no method in the #eriali9able interface. The #eriali9able interface acts as a mar&er, telling the object seriali9ation tools that your class is seriali9able. How man# methods in the '(ternali&able interface?
There are two methods in the xternali9able interface. 8ou 8ou have to implement these two methods in order to ma&e your class externali9able. These two methods are readxternal/ and writexternal/. What is the difference between %eriali&alble and '(ternali&able interface?
A transient transient variable is a variable that may not be seriali9ed. If you you don+t want some field to be seriali9ed, you can mar& that field transient or static. Which containers use a border la#out as their default la#out?
The
3bjects that subclass the 3bservable class maintain a list of observers.
2ava is an object=oriented programming language developed initially by 2ames >osling and colleagues at #un $icrosystems. The language, initially called 3a& named after the oa& trees outside >osling+s office/, was intended to replace C??, although the feature set better resembles that of 3bjective C. 2ava should not be confused with 2ava#cript, which shares only the name and a similar C=li&e syntax. #un $icrosystems currently maintains and updates 2ava regularly. What does a well-written $$ pro!ram loo lie?
A well=written well=written 33 program exhibits recurring structures structures that promote abstraction, abstraction, flexibility, flexibility, modularity and elegance. Can #ou have virtual functions in Java?
8es, 8es, all functions in 2ava are virtual by default. This is actually a pseudo tric& )uestion because the word @virtual@ is not part of the naming convention in 2ava as it is in C??, C=sharp and (.*T/, so this would be a foreign concept for someone who has only coded in 2ava. irtual functions or virtual methods are functions or methods that will be redefined in derived classes.
8ou 8ou need to add a directory or a jar file that contains the pac&age directories to the C%A##PAT" C%A##PAT" environment variable. %et+s say a class mployee belongs to a pac&age com.xy9.hr- and is located in the file c!:dev:com:xy9:hr:mployee.java. In this case, you+d need to add c!:dev to the variable C%A##PAT". C%A##PAT". If this class contains the method main/, you could test it from a command prompt window as follows! c!:;java com.xy9.hr.mployee com.xy9.hr.mployee How man# methods in the %eriali&able interface?
There is no method in the #eriali9able interface. The #eriali9able interface acts as a mar&er, telling the object seriali9ation tools that your class is seriali9able. How man# methods in the '(ternali&able interface?
There are two methods in the xternali9able interface. 8ou 8ou have to implement these two methods in order to ma&e your class externali9able. These two methods are readxternal/ and writexternal/. What is the difference between %eriali&alble and '(ternali&able interface?
A transient transient variable is a variable that may not be seriali9ed. If you you don+t want some field to be seriali9ed, you can mar& that field transient or static. Which containers use a border la#out as their default la#out?
The
3bjects that subclass the 3bservable class maintain a list of observers.
2ava is an object=oriented programming language developed initially by 2ames >osling and colleagues at #un $icrosystems. The language, initially called 3a& named after the oa& trees outside >osling+s office/, was intended to replace C??, although the feature set better resembles that of 3bjective C. 2ava should not be confused with 2ava#cript, which shares only the name and a similar C=li&e syntax. #un $icrosystems currently maintains and updates 2ava regularly. What does a well-written $$ pro!ram loo lie?
A well=written well=written 33 program exhibits recurring structures structures that promote abstraction, abstraction, flexibility, flexibility, modularity and elegance. Can #ou have virtual functions in Java?
8es, 8es, all functions in 2ava are virtual by default. This is actually a pseudo tric& )uestion because the word @virtual@ is not part of the naming convention in 2ava as it is in C??, C=sharp and (.*T/, so this would be a foreign concept for someone who has only coded in 2ava. irtual functions or virtual methods are functions or methods that will be redefined in derived classes.
Jac developed a pro!ram b# usin! a )ap container to hold e#/value pairs* He wanted to mae a chan!e to the map* He decided to mae a clone of the map in order to save the ori!inal data on side* What do #ou thin of it? ?
If 2ac& made a clone of the map, any changes to the clone or the original map would be seen on both maps, because the clone of $ap is a shallow copy. #o 2ac& made a wrong decision. What is more advisable to create a thread" b# implementin! a +unnable interface or b# e(tendin! ,hread class?
#trategically spea&ing, threads created by implementing Bunnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Bunnable interface, you save a space for your class to extend another class now or in future. What is ullPointer'(ception and how to handle it?
3ne option is to use a static bloc& to load a library before anything is called. 1or example, class Test static #ystem.load%ibrary@path=to=library=file@/0 .... 0
The class #ystem has a variable out that represents the standard output, and the variable err that represents the standard error device. (y default, they both point at the system s ystem console. This how the standard output could be re=directed! #tream st 5 new #treamnew 1ile3utput#tream@output.txt@//- #ystem.setrrst/#ystem.setrrst/#ystem.set3utst/What.s the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which which is not allowed in an interface.
Containers which uses (order %ayout as their default are! window, 1rame and 'ialog classes.
What do #ou understand b# %#nchroni&ation?
#ynchroni9ation is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchroni9ed multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object+s value. #ynchroni9ation prevents such type of data corruption. .g. #ynchroni9ing a function! public synchroni9ed void $ethod6 / Appropriate method=related code. 0 .g. #ynchroni9ing a bloc& of code inside a function! public my1unction / synchroni9ed this/ #ynchroni9ed code here. 0 0 What is s#nchroni&ation and wh# is it important?
#ynchroni9ed methods are methods that are used to control access to a method or an object. A thread only executes a synchroni9ed method after it has ac)uired the loc& for the method+s object or class. #ynchroni9ed statements are similar to synchroni9ed methods. A synchroni9ed statement can only be executed after a thread has ac)uired the loc& for the object or class referenced in the synchroni9ed statement. What are three wa#s in which a thread can enter the waitin! state?
A thread can enter the waiting state by invo&ing its sleep/ method, by bloc&ing on I3, by unsuccessfully attempting to ac)uire an object+s loc&, or by invo&ing an object+s wait/ method. It can also enter the waiting state by invo&ing its deprecated/ suspend/ method. Can a loc be ac1uired on a class?
8es, a loc& can be ac)uired on a class. This loc& is ac)uired on the class+s Class object. What.s new with the stop23" suspend23 and resume23 methods in J45 6*7?
The stop/, suspend/ and resume/ methods have been deprecated in 2'D 6.E. What is the preferred si&e of a component?
The preferred si9e of a component is the minimum component si9e that will allow the component to display normally. What.s the difference between J7%45 6*8 and J7%45 8*9?
There+s no difference, #un $icrosystems just re=branded this version. What would #ou use to compare two %trin! variables - the operator :: or the method e1uals23?
I+d use the method e)uals/ to compare the values of the #trings and the 55 to chec& if two variables point at the same instance of a #tring object.
What is thread?
A thread is an independent path of execution in a system. What is multi-threadin!?
$ulti=threading means various threads that run in a system. How does multi-threadin! tae place on a computer with a sin!le CP;?
The operating system+s tas& scheduler allocates execution time to multiple tas&s. (y )uic&ly switching between executing tas&s, it creates the impression that tas&s execute se)uentially. How to create a thread in a pro!ram?
8ou have two ways to do so. 1irst, ma&ing your class @extends@ Thread class. #econd, ma&ing your class @implements@ Bunnable interface. Put jobs in a run/ method and call start/ method to start the thread. Can Java ob
8es. 8ou can loc& an object by putting it in a @synchroni9ed@ bloc&. The loc&ed object is inaccessible to any thread other than the one that explicitly claimed it. Can each Java ob
8es. Fse Thread.currentThread/ method to trac& the accessing thread. 4oes it matter in what order catch statements for =ileot=ound'(ception and I$'(ceptipon are written?
8es, it does. The 1ile*o1oundxception is inherited from the I3xception. xception+s subclasses have to be caught first. What invoes a thread.s run23 method?
After a thread is started, via its start/ method of the Thread class, the 2$ invo&es the thread+s run/ method when the thread is initially executed. What is the purpose of the wait23" notif#23" and notif#All23 methods?
The wait/,notify/, and notifyAll/ methods are used to pr ovide an efficient way for threads to communicate each other. What are the hi!h-level thread states?
The high=level thread states are ready, running, waiting, and dead. What is the difference between #ieldin! and sleepin!?
If a thread attempts to execute a synchroni9ed method or synchroni9ed statement and is unable to ac)uire an object+s loc&, it enters the waiting state until the loc& becomes available. What is the difference between Process and ,hread?
A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space- a thread doesn+t. Threads typically share the heap belonging to their parent process. 1or instance, a 2$ runs in a single process in the host 3#. Threads in the 2$ share the heap belonging to that process- that+s why several threads may access the same object. Typically, even though they share a common heap, threads have their own stac& space.
This is how one thread+s invocation of a method is &ept separate from another+s. This is all a gross oversimplification, but it+s accurate enough at a high level. %ots of details differ between operating systems. Process vs. Thread A program vs. similar to a se)uential program an run on its own vs. Cannot run on its own Fnit of allocation vs. Fnit of execution "ave its own memory space vs. #hare with others ach process has one or more threads vs. ach thread belongs to one process xpensive, need to context switch vs. Cheap, can use process memory and may not need to context switch $ore secure. 3ne process cannot corrupt another process vs. %ess secure. A thread can write the memory used by another thread Can an inner class declared inside of a method access local variables of this method?
It+s possible if these variables are final. What can !o wron! if #ou replace >emp>emp with >emp in the followin! code@ %trin! a:null if 2a:null >> a*len!th23B693 ***D
A single ampersand here would lead to a *ullPointerxception. What is the Eector class?
The ector class provides the capability to implement a growable array of objects What modifiers ma# be used with an inner class that is a member of an outer class? A non=local/ inner class may be declared as public, protected, private, static, final, or abstract. If a method is declared as protected" where ma# the method be accessed? A protected method may only be accessed by classes or interfaces of the same pac&age or by subclasses of the class in which it is declared. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection. How man# bits are used to represent ;nicode" A%CII" ;,=-6F" and ;,=-G characters?
Fnicode re)uires 6G bits and A#CII re)uire H bits. Although the A#CII character set uses only H bits, it is usually represented as bits. FT1= represents characters using , 6G, and 6 bit patterns. FT1=6G uses 6G=bit and larger bit patterns. What.s the main difference between a Eector and an Arra#0ist?
2ava ector class is internally synchroni9ed and Array%ist is not. What are wrapped classes?
*o, it doesn+t. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. What is the difference between preemptive schedulin! and time slicin!?
Fnder preemptive scheduling, the highest priority tas& executes until it enters the waiting or dead states or a higher priority tas& comes into existence. Fnder time slicing, a tas& executes for a predefined slice of time and then reenters the pool of ready tas&s. The scheduler then determines which tas& should execute next, based on priority and other factors.
ame Component subclasses that support paintin! ?
The Canvas, 1rame, Panel, and Applet classes support painting. What is a native method?
A native method is a method that is implemented in a language other than 2ava. How can #ou write a loop indefinitel#?
for--/==for loop- whiletrue/==always true, etc. Can an anon#mous class be declared as implementin! an interface and e(tendin! a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. What is the purpose of finali&ation?
The purpose of finali9ation is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. When should the method invoe0ater23be used?
This method is used to ensure that #wing components are updated through the event=dispatching thread. How man# methods in $b
This )uestion is not as&ed to test your memory. It tests you how well you &now 2ava. Ten in total. clone/ e)uals/ J hashcode/ getClass/ finali9e/ wait/ J notify/ to#tring/ How does Java handle inte!er overflows and underflows?
It uses low order bytes of the result that can fit into the si9e of the type allowed by the operation. What is the numeric promotion?
*umeric promotion is used with both unary and binary bitwise operators. This means that byte, char, and short values are converted to int values before a bitwise operator is applied. If a binary bitwise operator has one long operand, the other operand is converted to a long value. The type of the result of a bitwise operation is the type to which the operands have been promoted. 1or example! short a 5 Kbyte b 5 67long c 5 6KThe type of the result of a?b/ is int, not short or byte. The type of the result of a?c/ or b?c/ is long. Is the numeric promotion available in other platform?
8es. (ecause 2ava is implemented using a platform=independent virtual machine, bitwise operations always yield the same result, even when run on machines that use radically different CPFs. What is the difference between the oolean > operator and the >> operator?
If an expression involving the (oolean J operator is evaluated, both operands are evaluated.
Then the J operator is applied to the operand.
The >regorianCalendar provides support for traditional
The #impleTimeLone class provides support for a >regorian calendar. How can a subclass call a method or a constructor defined in a superclass?
Fse the following syntax! super.my$ethod/- To call a constructor of the superclass, just write super/- in the first line of the subclass+s constructor. What is the Properties class?
The properties class is a subclass of "ashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used. What is the purpose of the +untime class?
The purpose of the Buntime class is to provide access to the 2ava runtime system. What is the purpose of the %#stem class?
The purpose of the #ystem class is to provide access to system resources. What is the purpose of the finall# clause of a tr#-catch-finall# statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. What is the 0ocale class?
The %ocale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. 3r, a method that has no implementation. What is the difference between interface and abstract class?
interface contains methods that must be abstract- abstract class may contain concrete methods. interface contains variables that must be static and final- abstract class may contain non=final and final variables. members in an interface are public by default, abstract class may contain non= public members. interface is used to @implements@- whereas abstract class is used to @extends@. interface can be used to achieve multiple inheritance- abstract class can be used as a single inheritance. interface can @extends@ another interface, abstract class can @extends@ another class and @implements@ multiple interfaces. interface is absolutely abstract- abstract class can be invo&ed if a main/ exists. interface is more flexible than abstract class because one class can only @extends@ one super class, but @implements@ multiple interfaces. If given a choice, use interface instead of abstract class.
What is a static method?
A static method is a method that belongs to the class rather than any object of the class and doesn+t apply to an object or even re)uire that any objects of the class have been instantiated. What is a protected method?
A protected method is a method that can be accessed by any method in its pac&age and inherited by any subclass of its class. What is the difference between a static and a non-static inner class?
A non=static inner class may have object instances that are associated with instances of the class+s outer class. A static inner class does not have any object instances. What is an ob
An object+s loc& is a mechanism that is used by multiple threads to obtain synchroni9ed access to the object. A thread may execute a synchroni9ed method of an object only after it has ac)uired the object+s loc&. All objects and classes have loc&s. A class+s loc& is ac)uired on the class+s Class object. When can an ob
An object reference can be cast to an interface reference when the object implements the referenced interface. What is the difference between a Window and a =rame?
The 1rame class extends
"eavy weight components li&e Abstract
javax.#wing pac&age. All components in #wing, except 2Applet, 2'ialog, 21rame and 2
The peerless components are called light weight components. What is the difference between the =ont and =ont)etrics classes?
The 1ont$etrics class is used to define implementation=specific properties, such as ascent and descent, of a 1ont object What is the difference between the +eader/Writer class hierarch# and the Input%tream/$utput%tream class hierarch#?
The Beader
What classes of e(ceptions ma# be cau!ht b# a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the rror and xception types. What is the difference between throw and throws e#words?
The throw &eyword denotes a statement that causes an exception to be initiated. It ta&es the xception object to be thrown as argument. The exception will be caught by an immediately encompassing try=catch construction or propagated further up the calling hierarchy. The throws &eyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw. If a class is declared without an# access modifiers" where ma# the class be accessed? A class that is declared without any access modifiers is said to have pac&age or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same pac&age. What is the )ap interface?
The $ap interface replaces the 2'D 6.6 'ictionary class and is used associate &eys with values. 4oes a class inherit the constructors of its super class?
A class does not inherit constructors from any of its superclasses. ame primitive Java t#pes*
The primitive types are byte, char, short, int, long, float, double, and (oolean. Which class should #ou use to obtain desi!n information about an ob
The Class class is used to obtain information about an object+s design. How can a ;I component handle its own events?
A component can handle its own events by implementing the re)uired event=listener interface and adding itself as its own event listener. How are the elements of a rida!0a#out or!ani&ed?
The elements of a >rid(ag%ayout are organi9ed according to a grid. "owever, the elements are of different si9es and may occupy more than one row or column of the grid. In addition, the rows and columns may have different si9es. What advanta!e do Java.s la#out mana!ers provide over traditional windowin! s#stems?
2ava uses layout managers to lay out components in a consistent manner across all windowing platforms. #ince 2ava+s layout managers aren+t tied to absolute si9ing and positioning, they are able to accommodate platform=specific differences among windowing systems. What are the problems faced b# Java pro!rammers who don.t use la#out mana!ers?
FI will be displayed across multiple windowing systems and finding a common si9ing and positioning that will wor& within the constraints imposed by each windowing system. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. *on=static variables ta&e on uni)ue values with each object instance.
What is the difference between the paint23 and repaint23 methods?
The paint/ method supports painting via a >raphics object. The repaint/ method is used to cause paint/ to be invo&ed by the A
The 1ile class is used to create objects that provide access to the files and directories of a local file system. Wh# would #ou use a s#nchroni&ed bloc vs* s#nchroni&ed method?
#ynchroni9ed bloc&s place loc&s for shorter periods than synchroni9ed methods. What restrictions are placed on method overridin!?
3verridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. What is castin!?
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. '(plain the usa!e of the e#word transient?
This &eyword indicates that the value of this member variable does not have to be seriali9ed with the object.
The 3bjectInput#tream class supports the reading of objects from input streams. How are this23 and super23 used with constructors?
this/ is used to invo&e a constructor of the same class. super/ is used to invo&e a superclass constructor. How is it possible for two %trin! ob
The 55 operator compares two objects to determine if they are the same objects in memory. It is possible for two #tring objects to have the same value, but located in different areas of memory. What is an I$ filter?
An I3 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. What is the %et interface?
The #et interface provides methods for accessing the elements of a finite mathematical set. #ets do not allow duplicate elements. How can #ou force !arba!e collection?
8ou can+t force >C, but could re)uest it by calling #ystem.gc/. 2$ does not guar antee that >C will be started immediately.
What is the purpose of the enable'vents23 method?
The enablevents/ method is used to enable an event for a particular object. *ormally, an event is enabled when a listener is added to an object for a particular event. The enablevents/ method is used by objects that handle events by overriding their event=dispatch methods. What is the difference between the =ile and +andomAccess=ile classes?
The 1ile class encapsulates the files and directories of the local file system. The BandomAccess1ile class provides the methods needed to directly access data contained in any part of a file. What interface must an ob
An object must implement the #eriali9able or xternali9able interface before it can be written to a stream as an object. What is the +esourceundle class?
The Besource(undle class is used to store locale=specific resources that can be loaded by a program to tailor the program+s appearance to the particular locale in which it is being run. How do #ou now if an e(plicit ob
If you assign a superclass object to a variable of a subclass+s data type, you need to do explicit casting. 1or example! 3bject a- Customer b- b 5 Customer/ a
A 2ava pac&age is a naming context for classes and interfaces. A pac&age is used to create a separate name space for groups of classes and interfaces. Pac&ages are also used to organi9e related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. How do #ou restrict a user to cut and paste from the html pa!e?
Fsing #ervlet or client side scripts to loc& &eyboard &eys. It is one of solutions. What are the $b
The 3bject class is the highest=level class in the 2ava class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a 2ava program. What is %eriali&ation and deseriali&ation ?
#eriali9ation is the process of writing the state of an object to a byte stream. 'eseriali9ation is the process of restoring these objects. '(plain the usa!e of Java paca!es*
This is a way to organi9e files when a project consists of multiple modules. It also helps resolve naming conflicts when different pac&ages have classes with the same names. Pac&ages access level also allows you to protect data from being used by the non=authori9ed classes. 4oes the code in finall# bloc !et e(ecuted if there is an e(ception and a return statement in a catch bloc?
If an exception occurs and there is a return statement in catch bloc&, the finally bloc& is still executed. The finally bloc& will not be executed when the #ystem.exit6/ statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally bloc&.
Is Java a super set of Java%cript?
*o. They are completely different. #ome syntax may be similar. What is a Container in a ;I?
A Container contains and arranges other components including other containers/ through the use of layout managers, which use specific layout policies to determine where components should go as a function of the si9e of the container. How the ob
Polymorphism means @having many forms@. It allows methods may be variables/ to be written that needn+t be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to wor& even on objects of un=conceived classes. What is desi!n b# contract?
The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. 1or example, the preconditions specify what the method re)uired to be true when the method is called. "ence ma&ing sure that preconditions are. #imilarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions. In 2ava, the exception handling facilities support the use of design by contract, especially in the case of chec&ed exceptions. The assert &eyword can be used to ma&e such contracts. What are use cases?
A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust. What is scalabilit# and performance?
Performance is a measure of @how fast can you perform this tas&.@ and scalability describes ho w an application behaves as its wor&load and available computing resources increase. What is the benefit of subclass?
>enerally! The sub class inherits all the public methods and the implementation. The sub class inherits all the protected methods and their implementation. The sub class inherits all the defaultnon=access modifier/ methods and their implementation. The sub class also inherits all the public, protected and default member variables from the super class. The constructors are not part of this inheritance model. How to add menushortcut to menu item?
If you have a button instance called about(utton, you may add menu short cut by calling about(utton.set$nemonic+A+/, so the user may be able to use Alt?A to clic& the button.
In %#stem*out*println23"what is %#stem"out and println"pls e(plain?
#ystem is a predefined final class,out is a Print#tream object acting as a field member and println is a built=in overloaded method in the out object. Can #ou write a Java class that could be used both as an applet as well as an application?
A. 8es. Add a main/ method to the applet. Can #ou mae an instance of an abstract class? =or e(ample -
*oM 8ou cannot ma&e an instance of an abstract class. An abstract class has to be sub=classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method. What is the output of ( B #? a@b : p1 when (:6"#:7"p:K"1:L?
(ecause pointers are unsafe. 2ava uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why 2ava and C=sharp shine. Parsers? 4$) vs %AM parser
Parsers are fundamental xml components, a bridge between N$% documents and applications that process that N$%. The parser is responsible for handling xml syntax, chec&ing the contents of the document against constraints established in a 'T' or #chema. '3$ 6. Tree of nodes E. $emory! 3ccupies more memory, preffered for small N$% documents O. #lower at runtime . #tored as objects K. Programmatically easy G. ase of navigation #AN 6. #e)uence of events E. 'oesn+t use any memory preferred for large documents O. 1aster at runtime . 3bjects are to be created K. *eed to write code for creating objects G. (ac&ward navigation is not possible as it se)uentially processes the document Can #ou declare a class as private?
8es, we can declare a private class as an inner class. 1or example, class $yPrivate private static class $yDey
#tring &ey 5 @6EOK@0 public static void main#tringQR args/ #ystem.out.printlnnew $yDey/.&ey/-prints 6EOK 0 0 What is the difference between shallow cop# and deep cop#?
#hallow copy shares the same reference with the original object li&e cloning, whereas the deep copy get a duplicate instance of the original object. If the shallow copy has been changed, the original object will be reflected and vice versa. Can one create a method which !ets a %trin! and modifies it?
*o. In 2ava, #trings are constant or immutable- their values cannot be changed after they are created, but they can be shared. 3nce you change a string, you actually create a new object. 1or example! #tring s 5 @abc@- create a new #tring object representing @abc@ s 5 s.toFpperCase/- create another object representing @A(C@ Wh# is multiple inheritance not possible in Java?
It depends on how you understand @inheritance@. 2ava can only @extends@ one super class, but can @implements@ many interfaces- that doesn+t mean the multiple inheritance is not possible. 8ou may use interfaces to ma&e inheritance wor& for you. 3r you may need to wor& around. 1or example, if you cannot get a feature from a class because your class has a super class already, you may get that class+s feature by declaring it as a member field or getting an instance of that class. #o the answer is that multiple inheritance in 2ava is possible. What.s the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times. What is the relationship between s#nchroni&ed and volatile e#word?
The 2$ is guaranteed to treat reads and writes of data of OE bits or less as atomic.#ome 2$ might treat reads and writes of data of G bits or less as atomic in future/ 1or long or double variable, programmers should ta&e care in multi=threading environment. ither put these variables in a synchroni9ed method or bloc&, or declare them volatile. ,his class 2IncrementImpl3 will be used b# various threads concurrentl# can #ou see the inherent flaw2s3? How would #ou improve it?
public class IncrementImpl private static int counter 5 7public synchroni9ed void increment/ counter??0 public int getCounter/ return counter0 0 The counter is static variable which is shared by multiple instances of this class. The increment/ method is synchroni9ed, but the getCounter/ should be synchroni9ed too. 3therwise the 2ava run=time system will not guarantee the data integrity and the race conditions will occur. The famous producerconsumer example listed at #un+s thread tutorial site will tell more.
one of solutions public class IncrementImpl private static int counter 5 7public synchroni9ed void increment/ counter??0 public synchroni9ed int getCounter/ return counter0 0 What are the drawbacs of inheritance?
#ince inheritance inherits everything from the super class and interface, it may ma&e the subclass too clustering and sometimes error=prone when dynamic overriding or dynamic overloading in some situation. In addition, the inheritance may ma&e peers hardly understand your code if they don+t &now how your super=class acts and add learning curve to the process of development. Fsually, when you want to use a functionality of a class, you may use subclass to inherit such function or use an instance of this class in your class.
There are a couple of ways. As you &now, the straight way is to @extends@ andor @implements@. The other way is to get an instance of the class to achieve the inheritance. That means to ma&e the supposed=super=class be a field member.
(oth are synchroni9ed methods. 3ne is instance method, the other is class method. $ethod with static modifier is a class method. That means the method belongs to class itself and can be accessed directly with class name and is also called #ingleton design. The method without static modifier is an instance method. That means the instance method belongs to its object. very instance of the class gets its own copy of its instance method.
The Collections class has six methods to help out here! 6. unmodifiableCollectionCollection c/ E. unmodifiable%ist%ist list/ O. unmodifiable$ap$ap m/ . unmodifiable#et#et s/ K. unmodifiable#orted$ap#orted$ap m/ G. unmodifiable#orted#et#orted#et s/ If you get an Iterator from one of these unmodifiable collections, when you call remove/, it will throw an Fnsupported3perationxception.
Can a private method of a superclass be declared within a subclass?
#ure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have a runtime overloading or overriding polymorphism/ features. Wh# Java does not support multiple inheritance ?
This is a classic )uestion. 8es or *o depends on how you loo& at 2ava. If you focus on the syntax of @extends@ and compare with C??, you may answer +*o+ and give explanation to support you. 3r you may answer +8es+. Becommend you to say +8es+. 2ava '3# support multiple inheritance via interface implementation. #ome people may not thin& in this way. >ive explanation to support your point. What is the difference between final" finall# and finali&e?
#hort answer! final = declares constant finally = relates with exception handling finali9e = helps in garbage collection If as&ed to give details, explain! final field, final method, final class tryfinally, trycatchfinally protected void finali9e/ in 3bject class What ind of securit# tools are available in J7%' 8*9?
There are three tools that can be used to protect application wor&ing within the scope of security policies set at remote sites. &eytool == used to manage &eystores and certificates. jarsigner == used to generate and verify 2AB signatures. policytool == used for managing policy files. There are three tools that help obtain, list and manage Derberos tic&ets. &init == used to obtain Derberos K tic&ets. t&list == used to list entries in credential cache and &ey tab. &tab == used to help manage entries in the &ey table. How to mae an arra# cop# from %#stem?
There is a method called arraycopy in the #ystem class. 8ou can do it! #ystem.arraycopysourceArray, src3ffset, destinationArray, dest3ffset, num3flementsECopy/
8es, you can. The source and destination arrays can be the same if you want to copy a subset of the array to another area within that array. What is shallow cop# or shallow clone in arra# clonin!?
Cloning an array invloves creating a new array of the same si9e and type and copying all the old elements into the new array. (ut such copy is called shallow copy or shallow clone because any changes to the object would be reflected in both arrays. When is the Arra#%tore'(ception thrown?
How to chec two arra#s to see if contents have the same t#pes and contain the same elements?
3ne of options is to use the e)uals/ method of Arrays class. Arrays.e)ualsa, b/If the array types are different, a compile=time error will happen. Can #ou call one constructor from another if a class has multiple constructors?
8es. Fse this/ syntax. What are the different t#pes of inner classes?
There are four different types of inner classes in 2ava. They are! a/#tatic member classes , a static member class has access to all static methods of the parent, or top=level, class b/ $ember classes, the member class is instance specific and has access to any and all methods and members, even the parent+s this reference c/ %ocal classes, are declared within a bloc& of code and are visible only within that bloc&, just as any other method variable. d/ Anonymous classes, is a local class that has no name In which case would #ou choose a static inner class?
Interesting one, static inner classes can access the outer class+s protected and private fields. This is both a positive and a negative point for us since we can, in essence, violate the encapsulation of the outer class by muc&ing up the outer class+s protected and private fields. The only pr oper use of that capability is to write white=box tests of the class == since we can induce cases that might be very hard to induce via normal blac&=box tests which don+t have access to the internal state of the object/. #econd advantage,if I can say, is that, we can this static concept to impose restriction on the inner class. Again as discussed in earlier point, an Inner class has access to all the public, private and protected members of the parent class. #uppose you want to restrict the access even to inner class, how would you go aheadS $a&ing the inner class static enforces it to access only the public static members of the outer class #ince, protected and private members are not supposed to be static and that static members can access only other static members/. If it has to access any non=static member, it has to create an instance of the outer class which leads to accessing only public members. What is wea reference in Java
A wea& reference is one that does not prevent the referenced object from being garbage collected. 8ou might use them to manage a "ash$ap to loo& up a cache of objects. A wea& reference is a reference that does not &eep the object it refers to alive. A wea& reference is not counted as a reference in garbage collection. If the object is not referred to elsewhere as well, it will be garbage collected. What is the difference between final" finall# and finali&e?
final is used for ma&ing a class no=subclassable, and ma&ing a member variable as a constant which cannot be modified. finally is usually used to release all the resources utili9ed inside the try bloc&. All the resources present in the finali9e method will be garbage collected whenever >C is called. Though finally and finali9e seem to be for a similar tas& there is an interesting twea& here, usually I prefer finally than finali9e unless it is unavoidable. This is because the code in finally bloc& is guaranteed of execution irrespective of occurrence of exception, while execution of finali9e is not guarenteed.finali9e method is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. Presumably the garbage collector will, li&e its civil servant namesa&e, visit the heap on a regular basis to clean up resources that are no longer in use. >arbage collection exists to prevent programmers from calling delete. This is a wonderful feature. 1or example, if you can+t call delete, then you can+t accidentally call delete twice on the same object. "owever, removing delete from the language is not the same thing as automatically cleaning up. To add to it, >arbage collection might not ever
run. If garbage collection runs at all, and an object is no longer referenced, then that object+s finali9e will run. Also, across multiple objects, finali9e order is not predictable. The correct approach to resource cleanup in 2ava language programs does not rely on finali9e. Instead, you simply write explicit close methods for objects that wrap native resources. If you ta&e this approach, you must document that the close method exists and when it should be called. Callers of the object must then remember to call close when they are finished with a resource. What.s the difference between the methods sleep23 and wait23
The code sleep6777/- puts thread aside for exactly one second. The code wait6777/, causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify/ or notifyAll/ call. The method wait/ is defined in the class 3bject and the method sleep/ is defined in the class Thread. ,he followin! statement prints true or false" wh#?
byteQR a 5 6, E, O 0byteQR b 5 byteQR/ a.clone/#ystem.out.printlna 55 b/The false will be printed out. (ecause the two arrays have distinctive memory addresses. #tarting in 2ava 6.E, we can use java.util.Arrays.e)ualsa, b/ to compare whether two arrays have the same contents. Wh# do we need to use !et%#stem+esource23 and !et%#stem+esources23 method to load resources?
(ecause we want to loo& for resources strictly from the system classpath, These methods use the system Class%oader to locate resources, which gives you stricter control of the resources used by the application. Arithmetic'(ception?
The Arithmeticxception is thrown when integer is divided by 9ero or ta&ing the remainder of a number by 9ero. It is never thrown in floating=point operations. What is a transient variable?
A transient variable is a variable that may not be seriali9ed. Which containers use a border 0a#out as their default la#out?
The window, 1rame and 'ialog classes use a border layout as their default layout. Wh# do threads bloc on I/$?
Threads bloc& on I3 that is enters the waiting state/ so that other threads may execute while the I3 3peration is performed. What is the output from %#stem*out*println2NHelloNOnull3?
"ellonull What is s#nchroni&ation and wh# is it important?
8es, a loc& can be ac)uired on a class. This loc& is ac)uired on the class+s Class object.
What.s new with the stop23" suspend23 and resume23 methods in J45 6*7?
The stop/, suspend/ and resume/ methods have been deprecated in 2'D 6.E. Is null a e#word?
The null value is not a &eyword. What is the preferred si&e of a component?
The preferred si9e of a component is the minimum component si9e that will allow the component to display normally. What method is used to specif# a container.s la#out?
The set%ayout/ method is used to specify a container+s layout. Which containers use a =low0a#out as their default la#out?
The Panel and Applet classes use the 1low%ayout as their default layout. What state does a thread enter when it terminates its processin!?
The Collections API is a set of classes and interfaces that support operations on collections of objects. Which characters ma# be used as the second character of an identifier" but not as the first character of an identifier?
The digits 7 through may not be used as the first character of an identifier but they may be used after the first character of an identifier. What is the 0ist interface?
The %ist interface provides support for ordered collections of objects. How does Java handle inte!er overflows and underflows?
It uses those low order bytes of the result that can fit into the si9e of the type allowed by the operation. What is the Eector class?
The ector class provides the capability to implement a growable array of objects What modifiers ma# be used with an inner class that is a member of an outer class?
A non=local/ inner class may be declared as public, protected, private, static, final, or abstract. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection. What is the difference between the BB and BBB operators?
The ;; operator carries the sign bit when shifting right. The ;;; 9ero=fills bits that have been shifted out. Which method of the Component class is used to set the position and si&e of a component?
set(ounds/
How man# bits are used to represent ;nicode" A%CII" ;,=-6F" and ;,=-G characters?
Fnicode re)uires 6G bits and A#CII re)uire H bits. Although the A#CII character set uses only H bits, it is usually represented as bits. FT1= represents characters using , 6G, and 6 bit patterns. FT1=6G uses 6G=bit and larger bit patterns. What is the difference between #ieldin! and sleepin!?
The vent3bject class and the vent%istener interface support event processing. Is si&eof a e#word?
The si9eof operator is not a &eyword. What are wrapper classes?
>arbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. What restrictions are placed on the location of a paca!e statement within a source code file?
A pac&age statement must appear as the first line in a source code file excluding blan& lines and comments/. Can an ob
Panel What is the difference between preemptive schedulin! and time slicin!?
Fnder preemptive scheduling, the highest priority tas& executes until it enters the waiting or dead states or a higher priority tas& comes into existence. Fnder time slicing, a tas& executes for a predefined slice of time and then reenters the pool of ready tas&s. The scheduler then determines which tas& should execute next, based on priority and other factors. ame three Component subclasses that support paintin!*
The Canvas, 1rame, Panel, and Applet classes support painting. What value does read0ine23 return when it has reached the end of a file?
The read%ine/ method returns null when it has reached the end of a file. What is the immediate superclass of the 4ialo! class?
Clipping is the process of confining paint operations to a limited area or shape.
What is a native method?
A native native method is a method that is implemented in a language other than 2ava. Can a for statement loop indefinitel#?
8es, 8es, a for statement can loop indefinitely. 1or example, consider the following! for--/ What are order of precedence and associativit#" and how are the# used?
3rder of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether whether an expression is evaluated left=to=right or right=to=left When a thread blocs on I/$" what state does it enter?
A thread thread enters the waiting state when when it bloc&s on I3. ,o what value is a variable of the %trin! t#pe automaticall# initiali&ed?
The default value of a #tring type is null. What is the catch or declare rule for method declarations?
If a chec&ed exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. What is the difference between a )enuItem and a Checbo()enuItem?
The Chec&box$enuItem class extends the $enuItem class to support a menu item that may be chec&ed or unchec&ed. What is a tas.s priorit# and how is it used in schedulin!?
A tas&+s tas&+s priority is an integer value value that identifies the relative relative order in which it should be executed executed with respect to other tas&s. The scheduler attempts to schedule higher priority tas&s before lower priority tas&s. What class is the top of the AW, event hierarch#?
The java.awt.A
A thread thread is in the ready state after after it has been created and started. Can an anon#mous class be declared as implementin! an interface and e(tendin! a class?
An anonymous class may implement implement an interface or extend a superclass, superclass, but may not be declared to do both. What is the ran!e of the short t#pe?
The range of the short type is =EU6K/ to EU6K = 6. What is the ran!e of the char t#pe?
The range of the char type is 7 to EU6G = 6. In which paca!e are most of the AW, events that support the event-dele!ation model defined?
$ost of the A
What is the immediate super class of )enu?
The purpose of finali9ation is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Which class is the immediate super class of the )enuComponent class*
3bject What invoes a thread.s run23 method?
After a thread is started, via its start/ method or that of the Thread class, class, the 2$ invo&es the the thread+s run/ method when the thread is initially executed. What is the difference between the oolean > operator and the >> operator?
If an expression involving the (oolean J operator is evaluated, both operands are evaluated. Then the J operator is applied to the operand.
(ox.1iller, (utton, Canvas, Chec&box, Choice, Container, %abel, %ist, #crollbar, or TextComponent TextComponent What is the re!orianCalendar class?
The >regorianCalendar provides support for traditional
validate/ What is the purpose of the +untime class?
The purpose of the Buntime class is to provide access to the 2ava runtime system. How man# times ma# an ob
An object+s finali9e/ method may may only be invo&ed once by the garbage collector. collector. What is the purpose of the finall# clause of a tr#-catch-finall# statement? !arba!e collector?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. What is the ar!ument t#pe of a pro!ram.s main23 method?
A program+s program+s main/ method ta&es an argument of of the #tringQR type. Which Java operator is ri!ht associative?
The 5 operator is right associative. What is the 0ocale class?
The %ocale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
Can a double value be cast to a b#te?
8es, 8es, a double value can be cast to a byte. What is the difference between a brea statement and a continue statement?
A brea& statement results in the termination termination of the statement to which it applies switch, switch, for, do, or while/. A continue statement is used to end the current loop iteration and return control to the loop statement. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause. What method is invoed to cause an ob
The start/ method of the Thread class is invo&ed to cause an object to begin executing as a separate thread. ame two subclasses of the ,e(tComponent class*
Text1ield Text1ield and TextArea What is the advanta!e of the event-dele!ation model over the earlier event-inheritance model?
The event=delegation model has two advantages over the event=inheritance model. 1irst, it enables event handling to be handled by objects other than the ones that generate the events or their containers/. This allows a clean separation between a component+s design and its use. The other advantage of the event=delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event=delegation model does not have to repeatedly process unhandled events, as is the case of the event=inheritance model. Which containers ma# have a )enuar?
1rame How are commas used in the initiali&ation and iteration parts of a for statement?
Commas are used to separate multiple statements within the initiali9ation and iteration parts of a for statement. What is the purpose of the wait23" notif#23" and notif#All23 methods?
The wait/,notify/, and notifyAll/ methods are used to pr ovide an efficient way for threads to wait for a shared resource.
An abstract method is a method method whose implementation is deferred to a subclass. How are Java source code files named?
A 2ava 2ava source code file ta&es the name of a public class or interface interface that is defined within within the file. A source source code file may contain at most most one public class or interface. interface. If a public class or or interface is defined within a source code file, then the source code file must ta&e the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must ta&e on a name that is different than its classes and interfaces. #ource code files use the .java extension.
What is the relationship between the Canvas class and the raphics class?
A Canvas object provides access to a >raphics object via its paint/ method. What are the hi!h-level thread states?
The high=level thread states are ready, running, waiting, and dead. What value does read23 return when it has reached the end of a file?
The read/ method returns =6 when it has reached the end of a file. Can a #te ob
*o, an object cannot be cast to a primitive value. What is the difference between a static and a non-static inner class?
A non=static inner class may have object instances that are associated with instances of the class+s outer class. A static inner class does not have any object instances. What is the difference between the %trin! and %trin!uffer classes?
#tring objects are constants. #tring(uffer objects are not. If a variable is declared as private" where ma# the variable be accessed?
A private variable may only be accessed within the class in which it is declared. What is an ob
An object+s loc& is a mechanism that is used by multiple threads to obtain synchroni9ed access to the object. A thread may execute a synchroni9ed method of an object only after it has ac)uired the object+s loc&. All objects and classes have loc&s. A class+s loc& is ac)uired on the class+s Class object. What is the 4ictionar# class?
The 'ictionary class provides the capability to store &ey=value pairs. How are the elements of a order0a#out or!ani&ed?
The elements of a (order%ayout are organi9ed at the borders *orth, #outh, ast, and
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. When can an ob
An object reference be cast to an interface reference when the object implements the referenced interface. What is the difference between a Window and a =rame?
The 1rame class extends
The 3bject class is extended by all other classes. Can an ob
A reachable object cannot be garbage collected. 3nly unreachable objects may be garbage collected..
Is the ternar# operator written ( @ # ? & or ( ? # @ & ?
It is written x S y ! 9. What is the difference between the =ont and =ont)etrics classes?
The 1ont$etrics class is used to define implementation=specific properties, such as ascent and descent, of a 1ont object. How is roundin! performed under inte!er division?
The fractional part of the result is truncated. This is &nown as rounding toward 9ero. What happens when a thread cannot ac1uire a loc on an ob
If a thread attempts to execute a synchroni9ed method or synchroni9ed statement and is unable to ac)uire an object+s loc&, it enters the waiting state until the loc& becomes available. What is the difference between the +eader/Writer class hierarch# and the Input%tream/$utput%tream class hierarch#?
The Beader
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the rror and xception types. If a class is declared without an# access modifiers" where ma# the class be accessed?
A class that is declared without any access modifiers is said to have pac&age access. This means that the class can only be accessed by other classes and interfaces that are defined within the same pac&age. What is the %imple,imeone class?
The #impleTimeLone class provides support for a >regorian calendar. What is the )ap interface?
The $ap interface replaces the 2'D 6.6 'ictionary class and is used associate &eys with values. 4oes a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its super classes. =or which statements does it mae sense to use a label?
The only statements for which it ma&es sense to use a label are those statements that can enclose a brea& or continue statement. What is the purpose of the %#stem class?
The purpose of the #ystem class is to provide access to system resources. Which ,e(tComponent method is used to set a ,e(tComponent to the read-onl# state?
setditable/ How are the elements of a Card0a#out or!ani&ed?
The elements of a Card%ayout are stac&ed, one on top of the other, li&e a dec& of cards. Is >>: a valid Java operator?
*o, it is not.
ame the ei!ht primitive Java t#pes*
The eight primitive types are byte, char, short, int, long, float, double, and boolean. Which class should #ou use to obtain desi!n information about an ob
The Class class is used to obtain information about an object+s design. What is the relationship between clippin! and repaintin!?
The #tring literal @abc@ is not a primitive value. It is a #tring object. What is the relationship between an event-listener interface and an event-adapter class?
An event=listener interface defines the methods that must be implemented by an event handler for a particular &ind of event. An event adapter provides a default implementation of an event=listener interface. What restrictions are placed on the values of each case of a switch statement?
'uring 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 ma# be used with an interface declaration?
An interface may be declared as public or abstract. Is a class a subclass of itself?
A class is a subclass of itself. What is the hi!hest-level event class of the event-dele!ation model?
The java.util.vent3bject class is the highest=level class in the event=delegation class hierarchy. What event results from the clicin! of a button?
The Actionvent event is generated as the result of the clic&ing of a button. How can a ;I component handle its own events?
A component can handle its own events by implementing the re)uired event=listener interface and adding itself as its own event listener. What is the difference between a while statement and a do statement?
A while statement chec&s at the beginning of a loop to see whether the next loop iteration should occur. A do statement chec&s 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. How are the elements of a rida!0a#out or!ani&ed?
The elements of a >rid(ag%ayout are organi9ed according to a grid. "owever, the elements are of different si9es and may occupy more than one row or column of the grid. In addition, the rows and columns may have different si9es. What advanta!e do Java.s la#out mana!ers provide over traditional windowin! s#stems?
2ava uses layout managers to lay out components in a consistent manner across all windowing platforms. #ince 2ava+s layout managers aren+t tied to absolute si9ing and positioning, they are able to accommodate platform=specific differences among windowing systems.
What is the Collection interface?
The Collection interface provides support for the implementation of a mathematical bag = an unordered collection of objects that may contain duplicates. What modifiers can be used with a local inner class?
A local inner class may be final or abstract. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. *on=static variables ta&e on uni)ue values with each object instance. What is the difference between the paint23 and repaint23 methods?
The paint/ method supports painting via a >raphics object. The repaint/ method is used to cause paint/ to be invo&ed by the A
The 1ile class is used to create objects that provide access to the files and directories of a local file system. Can an e(ception be rethrown?
8es, an exception can be rethrown. Which )ath method is used to calculate the absolute value of a number?
The abs/ method is used to calculate absolute values. How does multithreadin! tae place on a computer with a sin!le CP;?
The operating system+s tas& scheduler allocates execution time to multiple tas&s. (y )uic&ly switching between executing tas&s, it creates the impression that tas&s execute se)uentially. When does the compiler suppl# a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided. When is the finall# clause of a tr#-catch-finall# statement e(ecuted?
The finally clause of the try=catch=finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. Which class is the immediate superclass of the Container class?
Component If a method is declared as protected" where ma# the method be accessed?
A protected method may only be accessed by classes or interfaces of the same pac&age or by subclasses of the class in which it is declared. How can the Checbo( class be used to create a radio button?
(y associating Chec&box objects with a Chec&box>roup. Which non-;nicode letter characters ma# be used as the first character of an identifier?
The non=Fnicode letter characters V and 4 may appear as the first character of an identifier What restrictions are placed on method overloadin!?
Two methods may not have the same name and argument list but different return types.
What happens when #ou invoe a thread.s interrupt method while it is sleepin! or waitin!?
A program+s main/ method has a void return type. ame four Container classes*
A Choice is displayed in a compact form that re)uires you to pull it down to see the list of available choices. 3nly one item may be selected from a Choice. A %ist may be displayed in such a way that several %ist items are visible. A %ist supports the selection of one or more %ist items. What class of e(ceptions are !enerated b# the Java run-time s#stem?
The 2ava runtime system generates Buntimexception and rror exceptions. What class allows #ou to read ob
The 3bjectInput#tream class supports the reading of objects from input streams. What is the difference between a field variable and a local variable?
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. ;nder what conditions is an ob
The garbage collector invo&es an object+s finali9e/ method when it detects that the object has become unreachable. How are this 23 and super 23 used with constructors?
this/ is used to invo&e a constructor of the same class. super/ is used to invo&e a superclass constructor. What is the relationship between a method.s throws clause and the e(ceptions that can be thrown durin! the method.s e(ecution?
A method+s throws clause must declare any chec&ed exceptions that are not caught within the body of the method. What is the difference between the J45 6*97 event model and the event-dele!ation model introduced with J45 6*6?
The 2'D 6.7E event model uses an event inheritance or bubbling approach. In this model, components are re)uired to handle their own events. If they do not handle a particular event, the event is inherited by or bubbled up to/ the component+s container. The container then either handles the event or it is bubbled up to its container and so on, until the highest=level container has been tried. In the event=delegation model, specific objects are designated as event handlers for >FI components. These objects implement event=listener interfaces. The event=delegation model is more efficient than the event=inheritance model because it eliminates the processing re)uired to support the bubbling of unhandled events. How is it possible for two %trin! ob
The 55 operator compares two objects to determine if they are the same object in memory. It is possible for two #tring objects to have the same value, but located indifferent areas of memory. Wh# are the methods of the )ath class static?
#o they can be invo&ed as if they are a mathematical code library. What Checbo( method allows #ou to tell if a Checbo( is checed?
get#tate/ What state is a thread in when it is e(ecutin!?
An executing thread is in the running state. What are the le!al operands of the instanceof operator?
The left operand is an object reference or null value and the right operand is a class, interface, or array type. How are the elements of a rid0a#out or!ani&ed?
The elements of a >rid(ad layout are of e)ual si9e and are laid out using the s)uares of a grid. What an I/$ filter?
An I3 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 ob
3nce an object is garbage collected, it ceases to exist. It can no longer become reachable again. What are ' and PI?
is the base of the natural logarithm and PI is mathematical value pi. Are true and false e#words?
The values true and false are not &eywords. What is a void return t#pe?
A void return type indicates that a method does not return a value. What is the purpose of the enable'vents23 method?
The enablevents/ method is used to enable an event for a particular object. *ormally, an event is enabled when a listener is added to an object for a particular event. The enablevents/ method is used by objects that handle events by overriding their event=dispatch methods. What is the difference between the =ile and +andomAccess=ile classes?
The 1ile class encapsulates the files and directories of the local file system. The BandomAccess1ile class provides the methods needed to directly access data contained in any part of a file. What happens when #ou add a double value to a %trin!?
The result is a #tring object. What is #our platform.s default character encodin!?
If you are running 2ava on nglish
Which paca!e is alwa#s imported b# default?
The java.lang pac&age is always imported by default. What interface must an ob
An object must implement the #eriali9able or xternali9able interface before it can be written to a stream as an object. How are this and super used?
this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance. What is the purpose of !arba!e collection?
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 is a compilation unit?
A compilation unit is a 2ava source code file. What interface is e(tended b# AW, event listeners?
All A
3verridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. How can a dead thread be restarted?
A dead thread cannot be restarted. What happens if an e(ception is not cau!ht?
An uncaught exception results in the uncaughtxception/ method of the thread+s Thread>roup being invo&ed, which eventually results in the termination of the program in which it is thrown. What is a la#out mana!er?
A layout manager is an object that is used to organi9e components in a container. Which arithmetic operations can result in the throwin! of an Arithmetic'(ception?
Integer and W can result in the throwing of an Arithmeticxception. What are three wa#s in which a thread can enter the waitin! state?
A thread can enter the waiting state by invo&ing its sleep/ method, by bloc&ing on I3, by unsuccessfully attempting to ac)uire an object+s loc&, or by invo&ing an object+s wait/ method. It can also enter the waiting state by invo&ing its deprecated/ suspend/ method. Can an abstract class be final?
An abstract class may not be declared as final. What is the +esourceundle class?
The Besource(undle class is used to store locale=specific resources that can be loaded by a program to tailor the program+s appearance to the particular locale in which it is being run.
What happens if a tr#-catch-finall# statement does not have a catch clause to handle an e(ception that is thrown within the bod# of the tr# statement?
The exception propagates up to the next higher level try=catch statement if any/ or results in the program+s termination. What is numeric promotion?
*umeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating=point operations may ta&e place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as re)uired. What is the difference between a %crollbar and a %crollPane?
A #crollbar is a Component, but not a Container. A #crollPane is a Container. A #crollPane handles its own events and performs its own scrolling. What is the difference between a public and a non-public class? A public class may be accessed outside of its pac&age. A non=public class may not be accessed outside of its pac&age. ,o what value is a variable of the boolean t#pe automaticall# initiali&ed?
The default value of the boolean type is false. Can tr# statements be nested?
Try statements may be tested. What is the difference between the prefi( and postfi( forms of the OO operator?
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value. What is the purpose of a statement bloc?
A statement bloc& is used to organi9e a se)uence of statements as a single statement group. What is a Java paca!e and how is it used?
A 2ava pac&age is a naming context for classes and interfaces. A pac&age is used to create a separate name space for groups of classes and interfaces. Pac&ages are also used to organi9e related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. What modifiers ma# be used with a top-level class?
A top=level class may be public, abstract, or final. What are the $b
The 3bject class is the highest=level class in the 2ava class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a 2ava program. How does a tr# statement determine which catch clause should be used to handle an e(ception?
Can an unreachable ob
An unreachable object may become reachable again. This can happen when the object+s finali9e/ method is invo&ed and the object performs an operation which causes it to become accessible to reachable objects. When is an ob
An object is subject to garbage collection when it becomes unreachable to the program in which it is used. What method must be implemented b# all threads?
All tas&s must implement the run/ method, whether they are a subclass of Thread or implement the Bunnable interface. What methods are used to !et and set the te(t label displa#ed b# a utton ob
get%abel/ and set%abel/ Which Component subclass is used for drawin! and paintin!?
Canvas What are the two basic wa#s in which classes that can be run as threads ma# be defined?
A thread class may be declared as a subclass of Thread, or it may implement the Bunnable interface. What are the problems faced b# Java pro!rammers who don.t use la#out mana!ers?
FI will be displayed across multiple windowing systems and finding a common si9ing and positioning that will wor& within the constraints imposed by each windowing system. What is the difference between an if statement and a switch statement?
The if statement is used to select among two alternatives. It uses a (oolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. Can there be an abstract class with no abstract methods in it?
yes. Can an Interface be final?
yes. Can an Interface have an inner class?
8es public interface abc static int i57- void dd/- class a6 a6/ int j- #ystem.out.println@in interfia@/- 0- public static void main#tring a6QR/ #ystem.out.println@in interfia@/- 0 0 0 Can we define private and protected modifiers for variables in interfaces?
8es. What is '(ternali&able?
xternali9able is an Interface that extends #eriali9able Interface. And sends data into #treams in Compressed 1ormat. It has two methods, writexternal3bject3uput out/ and readxternal3bjectInput in/
What modifiers are allowed for methods in an Interface?
3nly public and abstract modifiers are allowed for methods in interfaces. What is a local" member and a class variable?
ariables declared within a method are @local@ variables. ariables declared within the class i.e not within any methods are @member@ variables global variables/. ariables declared within the class i.e not within any methods and are defined as @static@ are class variables I made m# class Cloneable but I still !et .Can.t access protected method clone* Wh#?
8eah, some of the 2ava boo&s, in particular @The 2ava Programming %anguage@, imply that all you have to do in order to have your class support clone/ is implement the Cloneable interface. *ot so. Perhaps that was the intent at some point, but that+s not the way it wor&s currently. As it stands, you have to implement your own public clone/ method, even if it doesn+t do anything special and just calls super.clone/. What are the different identifier states of a ,hread?
The different identifiers of a Thread are! B = Bunning or runnable thread # = #uspended thread C< = Thread waiting on a condition variable $< = Thread waiting on a monitor loc& $# = Thread suspended waiting on a monitor loc& What are some alternatives to inheritance?
'elegation is an alternative to inheritance. 'elegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to thin& about each message you forward, because the instance is of a &nown class, rather than a new class, and because it doesn+t force you to accept all the methods of the super class! you can provide only the methods that really ma&e sense. 3n the other hand, it ma&es you write more code, and it is harder to re=use because it is not a subclass/. Wh# isn.t there operator overloadin!?
(ecause C?? has proven by example that operator overloading ma&es code almost impossible to maintain. In fact there very nearly wasn+t even method overloading in 2ava, but it was thought that this was too useful for some very basic methods li&e print/. *ote that some of the classes li&e 'ata3utput#tream have unoverloaded methods li&e writeInt/ and write(yte/. What does it mean that a method or field is NstaticN?
#tatic variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. #tatic methods can be referenced with the name of the class rather than the name of a particular object of the class though that wor&s too/. That+s how library methods li&e #ystem.out.println/ wor&. out is a static field in the java.lang.#ystem class. Wh# do threads bloc on I/$?
Threads bloc& on io that is enters the waiting state/ so that other threads may execute while the io 3peration is performed. What is s#nchroni&ation and wh# is it important?
threads to shared resources.
The null value is not a &eyword. Which characters ma# be used as the second character of an identifier"but not as the first character of an identifier?
The digits 7 through may not be used as the first character of an identifier but they may be used after the first character of an identifier. What is the difference between notif#23 and notif#All23?
notify/ is used to unbloc& one waiting thread- notifyAll/ is used to unbloc& all of them. Fsing notify/ is preferable for efficiency/ when only one bloc&ed thread can benefit from the change for example, when freeing a buffer bac& into a pool/. notifyAll/ is necessary for correctness/ if multiple threads should resume for example, when releasing a @writer@ loc& on a file might permit all @readers@ to resume/. Wh# can.t I sa#
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 wor&s, you+ll get used to it. It+s really a lot safer this way. "owever, there is actually a little tric& 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, ma&e it inherit from java.lang.$ath. That XdoesX bring all the methods into your local name space. (ut you can+t use this tric& in an applet, because you have to inherit from java.awt.Applet. And actually, you can+t use it on java.lang.$ath at all, because $ath is a @final@ class which means it can+t be extended. Wh# are there no !lobal variables in Java?
>lobal variables are considered bad form for a variety of reasons! Y Adding state variables brea&s 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/. Y #tate variables lessen the cohesion of a program! you need to &now more to understand how something wor&s. A major point of 3bject=3riented programming is to brea& up global state into more easily understood collections of local state. Y
What does it mean that a method or class is abstract?
An abstract class cannot be instantiated. 3nly its subclasses can be instantiated. 8ou indicate that a class is abstract with the abstract &eyword li&e 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. 1or example, public abstract float price/ Abstract methods may only be included in abstract classes. "owever, an abstract class is not re)uired to have any abstract methods, though most of them do. ach subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract. What is the main difference between Java platform and other platforms?
The 2ava platform differs from most other platforms in that it+s a software=only platform that runs on top of other hardware=based platforms. The 2ava platform has three elements! 2ava programming language The 2ava irtual $achine 2ava $/ The 2ava Application Programming Interface 2ava API/ What is the Java Eirtual )achine?
The 2ava irtual $achine is a software that can be ported onto various hardware=based platforms. What is the Java API?
The 2ava API is a large collection of ready=made software components that pr ovide many useful capabilities, such as graphical user interface >FI/ widgets. What is the paca!e?
The pac&age is a 2ava namespace or part of 2ava libraries. The 2ava API is grouped into libraries of related classes and interfaces- these libraries are &nown as pac&ages. What is native code?
The native code is code that after you compile it, the compiled code runs on a specific hardware platform. '(plain the user defined '(ceptions?
Fser defined xceptions are the separate xception classes defined by the user for specific purposed. An user defined can created by simply sub=classing it to the xception class. This allows custom exceptions to be generated using throw/ and caught in the same way as normal exceptions. xample! class myCustomxception extends xception The class simply has to exist to be an exception 0 Is Java code slower than native code?
*ot really. As a platform=independent environment, the 2ava platform can be a bit slower than native code. "owever, smart compilers, well=tuned interpreters, and just=in=time bytecode compilers can bring performance close to that of native code without threatening portability.
Can main23 method be overloaded?
8es. the main/ method is a special method for a program entry. 8ou can overload main/ method in any ways. (ut if you change the signature of the main method, the entry point for the program will be gone. What is the seriali&ation?
The seriali9ation is a &ind of mechanism that ma&es a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage. '(plain the new =eatures of J4C 7*9 Core API?
The 2'(C E.7 API includes the complete 2'(C API, which includes both core and 3ptional Pac&age API, and provides inductrial=strength database computing capabilities. *ew 1eatures in 2'(C E.7 Core API! #crollable result sets= using new methods in the Besult#et interface allows programmatically move the to particular row or to a position relative to its current position 2'(C E.7 Core API provides the (atch Fpdates functionality to the java applications. 2ava applications can now use the Besult#et.updateNNN methods. *ew data types = interfaces mapping the #[%O data types Custom mapping of user=defined types FT's/ $iscellaneous features, including performance hints, the use of character streams, full precision for java.math.(ig'ecimal values, additional security, and support for time 9ones in date, time, and timestamp values. How #ou can force the !arba!e collection?
>arbage collection automatic process and can+t be forced. '(plain !arba!e collection?
>arbage collection is one of the most important feature of 2ava. >arbage collection is also called automatic memory management as 2$ automatically removes the unused variablesobjects value is null/ from the memory. Fser program cann+t directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. very class inherits finali9e/ method from java.lang.3bject, the finali9e/ method is called by garbage collector when it determines no more references to the object exists. In 2ava, it is good idea to explicitly assign null into a variable when no more in use. I 2ava on calling #ystem.gc/ and Buntime.gc/, 2$ tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. 4escribe the principles of $$P%*
There are three main principals of oops which are called Polymorphism, Inheritance and ncapsulation. '(plain the 'ncapsulation principle*
ncapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This &eeps the data safe from outside interface and misuse. 3ne way to thin& about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. '(plain the Inheritance principle*
Inheritance is the process by which one object ac)uires the properties of another object. '(plain the Pol#morphism principle*
The meaning of Polymorphism is something li&e one name many forms. Polymorphism enables
one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as @one interface, multiple methods@. '(plain the different forms of Pol#morphism*
1rom a practical programming viewpoint, polymorphism exists in three distinct forms in 2ava! $ethod overloading $ethod overriding through inheritance $ethod overriding through the 2ava interface What are Access %pecifiers available in Java?
ccess specifiers are &eywords that determines the type of access to the member of a class. These are! Public Protected Private 'efaults 4escribe the wrapper classes in Java*
Answer! C ;se the '(ternali&able interface when #ou need complete control over #our ean.s seriali&ation 2for e(ample" when writin! and readin! a specific file format3*
*o. arlier order is maintained. ,he superclass constructor runs before the subclass constructor* ,he subclass.s version of the overridable method will be invoed before the subclass.s constructor has been invoed* If the subclass.s overridable method depends on the proper initiali&ation of the subclass 2throu!h the subclass constructor3" the method will most liel# fail* Is that true?
8es. It is true Wh# are the interfaces more fle(ible than abstract classes?
==An interface=defined type can be implemented by any class in a class hierarchy and can be extended by another interface. In contrast, an abstract=class=defined type can be implemented only by classes that subclass the abstract class. ==An interface=defined type can be used well in polymorphism. The so=called interface type vs. implementation types. ==Abstract classes evolve more easily than interfaces. If you add a new concrete method to an abstract class, the hierarchy system is still wor&ing. If you add a method to an interface, the classes that rely on the interface will brea& when recompiled. ==>enerally, use interfaces for flexibility- use abstract classes for ease of evolution li&e expanding class functionality/. What are new lan!ua!e features in J7%' 8*9?
>enerally! 6. generics E. static imports O. annotations . typesafe enums K. enhanced for loop G. autoboxingunboxing H. varargs . covariant return types What is covariant return t#pe?
A covariant return type lets you override a superclass method with a return type that subtypes the superclass method+s return type. #o we can use covariant return types to minimi9e upcasting and downcasting. class Parent Parent foo / #ystem.out.println @Parent foo/ called@/return this0 0 class Child extends Parent Child foo / #ystem.out.println @Child foo/ called@/return this0 0
class Covariant public static void main#tringQR args/ Child c 5 new Child/Child cE 5 c.foo/- cE is Child Parent cO 5 c.foo/- cO points to Child 0 0 What is the result of the followin! statement?
int i 5 6, float f 5 E.7fi ?5 f- o&, the cast done automatically by the compiler i 5 i ? f- error The compound assignment operators automatically include cast operations in their behaviors. What is e(ternali&ation? Where is it useful?
Fse the xternali9able interface when you need complete control over your (ean+s seriali9ation for example, when writing and reading a specific file format/. What will be the output on e(ecutin! the followin! code* public class )#Class public static void main 2%trin! ar!sR 3 int abcR : new int 8R %#stem*out*println2abc3 D D A 'rror arra# not initiali&ed 8 C null 4 Print some
Answer ! ' It will print some jun& characters to the output. "ere it will not give any compile time or runtime error because we have declared and initiali9ed the array properly. vent if we are not assigning a value to the array, it will always initiali9ed to its defaults. What will be the output on e(ecutin! the followin! code* public class )#Class public static void main 2%trin! ar!sR 3 int abcR : new int 8R %#stem*out*println2abc9R3 D D A 'rror arra# not initiali&ed 8 C9 4 Print some
Answer ! C.
What is a marer interface ?
An interface that contains no methods. .g.! #eriali9able, Cloneable, #ingleThread$odel etc. It is used to just mar& java classes that support certain capability. What are ta! interfaces?
Tag interface is an alternate name for mar&er interface. What are the restrictions placed on static method ?
2$ stands for 2ava irtual $achine. It is the run time for java programs. All are java programs are running inside this 2$ only. It converts java byte code to 3# specific commands. In addition to governing the execution of an application+s byte codes, the virtual machine handles related tas&s such as managing the system+s memory, providing security against malicious code, and managing multiple threads of program execution. What is JI,?
2IT stands for 2ust In Time compiler. It compiles java byte code to native code. What are Class0oaders?
A class loader is an object that is responsible for loading classes. The class Class%oader is an abstract class. >iven the name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a @class file@ of that name from a file system. very Class object contains a reference to the Class%oader that defined it. Class objects for array classes are not created by class loaders, but are created automatically as re)uired by the 2ava runtime. The class loader for an array class, as returned by Class.getClass%oader/ is the same as the class loader for its element type- if the element type is a primitive type, then the array class has no class loader. Applications implement subclasses of Class%oader in order to extend the manner in which the 2ava virtual machine dynamically loads classes. What is %ervice 0ocator pattern?
The #ervice %ocator pattern locates 2E 2ava E Platform, nterprise dition/ services for clients and thus abstracts the complexity of networ& operation and 2E service loo&up as 2( nterprise 2ava(ean/ Interview [uestions = "ome and 2$# 2ava $essage #ervice/ component factories. The #ervice %ocator hides the loo&up process+s implementation details and complexity from clients. To improve application performance, #ervice %ocator caches service objects to eliminate unnecessary 2*'I 2ava *aming and 'irectory Interface/ activity that occurs in a loo&up operation. What is %ession =acade pattern?
#ession facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component i.e.! #ession 2(/, and it contains all the iteractions between low level components i.e.! ntity 2(/. It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. Thin& of a ban& situation, where you have someone that would li&e to transfer money from one account to another. In this type of scenario, the client has to chec& that the user is authori9ed, get the status of the two accounts, chec& that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored.
As you can see, multiple server=side objects need to be accessed and possibly modified. $ultiple fine=grained invocations of ntity or even #ession/ (eans add the overhead of networ& calls, even multiple transaction. In other words, the ris& is to have a solution that has a high networ& overhead, high coupling, poor reusability and mantainability. The best solution is then to wrap all the calls inside a #ession (ean, so the clients will have a single point to access that is the session bean/ that will ta&e care of handling all the rest. What is 4ata Access $b
The 'ata Access 3bject or 'A3/ pattern! separates a data resource+s client interface from its data access mechanisms adapts a specific data resource+s access API to a generic client interface The 'A3 pattern allows data access mechanisms to change independently of the code that uses the data. The 'A3 implements the access mechanism re)uired to wor& with the data source. The data source could be a persistent store li&e an B'($#, an external service li&e a (E( exchange, a repository li&e an %'AP database, or a business service accessed via C3B(A Internet Inter=3B( Protocol II3P/ or low=level soc&ets. The business component that relies on the 'A3 uses the simpler interface exposed by the 'A3 for its clients. The 'A3 completely hides the data source implementation details from its clients. (ecause the interface exposed by the 'A3 to clients does not change when the underlying data source implementation changes, this pattern allows the 'A3 to adapt to different storage schemes without affecting its clients or business components. ssentially, the 'A3 acts as an adapter between the component and the data source. Can we mae an 'J sin!leton?
This is a debatable )uestion, and for every answer we propose there can be contradictions. I propose E solutions of the same. Bemember that 2(+s are distributed components and can be deployed on different 2$+s in a 'istributed environment i/ 1ollow the steps as given below $a&e sure that your service%ocator is deployed on only one 2$. In the service%ocator create a "ashTable"ash$ap8ou are the right judge to choose between these two/
An interface that contains no methods. .g.! #eriali9able, Cloneable, #ingleThread$odel etc. It is used to just mar& java classes that support certain capability. What are ta! interfaces?
Tag interface is an alternate name for mar&er interface.
What are the restrictions placed on static method ?
2$ stands for 2ava irtual $achine. It is the run time for java programs. All are java programs are running inside this 2$ only. It converts java byte code to 3# specific commands. In addition to governing the execution of an application+s byte codes, the virtual machine handles related tas&s such as managing the system+s memory, providing security against malicious code, and managing multiple threads of program execution. What is JI,?
2IT stands for 2ust In Time compiler. It compiles java byte code to native code. What are Class0oaders?
A class loader is an object that is responsible for loading classes. The class Class%oader is an abstract class. >iven the name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a @class file@ of that name from a file system. very Class object contains a reference to the Class%oader that defined it. Class objects for array classes are not created by class loaders, but are created automatically as re)uired by the 2ava runtime. The class loader for an array class, as returned by Class.getClass%oader/ is the same as the class loader for its element type- if the element type is a primitive type, then the array class has no class loader. Applications implement subclasses of Class%oader in order to extend the manner in which the 2ava virtual machine dynamically loads classes. What is %ervice 0ocator pattern?
The #ervice %ocator pattern locates 2E 2ava E Platform, nterprise dition/ services for clients and thus abstracts the complexity of networ& operation and 2E service loo&up as 2( nterprise 2ava(ean/ Interview [uestions = "ome and 2$# 2ava $essage #ervice/ component factories. The #ervice %ocator hides the loo&up process+s implementation details and complexity from clients. To improve application performance, #ervice %ocator caches service objects to eliminate unnecessary 2*'I 2ava *aming and 'irectory Interface/ activity that occurs in a loo&up operation. What is %ession =acade pattern?
#ession facade is one design pattern that is often used while developing enterprise applications. It is implemented as a higher level component i.e.! #ession 2(/, and it contains all the iteractions between low level components i.e.! ntity 2(/. It then provides a single interface for the functionality of an application or part of it, and it decouples lower level components simplifying the design. Thin& of a ban& situation, where you have someone that would li&e to transfer money from one account to another. In this type of scenario, the client has to chec& that the user is authori9ed, get the status of the two accounts, chec& that there are enough money on the first one, and then call the transfer. The entire transfer has to be done in a single transaction otherwise is something goes south, the situation has to be restored. As you can see, multiple server=side objects need to be accessed and possibly modified. $ultiple fine=grained invocations of ntity or even #ession/ (eans add the overhead of networ& calls, even multiple transaction. In other words, the ris& is to have a solution that has a high networ& overhead, high coupling, poor reusability and mantainability. The best solution is then to wrap all the calls inside a #ession (ean, so the clients will have a single point to access that is the session bean/ that will ta&e care of handling all the rest.
What is 4ata Access $b
The 'ata Access 3bject or 'A3/ pattern! separates a data resource+s client interface from its data access mechanisms adapts a specific data resource+s access API to a generic client interface The 'A3 pattern allows data access mechanisms to change independently of the code that uses the data. The 'A3 implements the access mechanism re)uired to wor& with the data source. The data source could be a persistent store li&e an B'($#, an external service li&e a (E( exchange, a repository li&e an %'AP database, or a business service accessed via C3B(A Internet Inter=3B( Protocol II3P/ or low=level soc&ets. The business component that relies on the 'A3 uses the simpler interface exposed by the 'A3 for its clients. The 'A3 completely hides the data source implementation details from its clients. (ecause the interface exposed by the 'A3 to clients does not change when the underlying data source implementation changes, this pattern allows the 'A3 to adapt to different storage schemes without affecting its clients or business components. ssentially, the 'A3 acts as an adapter between the component and the data source. Can we mae an 'J sin!leton?
This is a debatable )uestion, and for every answer we propose there can be contradictions. I propose E solutions of the same. Bemember that 2(+s are distributed components and can be deployed on different 2$+s in a 'istributed environment i/ 1ollow the steps as given below $a&e sure that your service%ocator is deployed on only one 2$. In the service%ocator create a "ashTable"ash$ap8ou are the right judge to choose between these two/
A/ If the class is #eriali9able class #ingleton implements #eriali9able private static #ingleton instanceprivate #ingleton/ 0 public static synchroni9ed #ingleton getInstance/ if instance 55 null/ instance 5 new #ingleton/return instance-
0 XX If the singleton implements #eriali9able, then this X method must be supplied. X protected 3bject readBesolve/ return instance0 XX This method avoids the object fro being cloned X public 3bject clone/ throws Clone*ot#upportedxception return instance0 0 (/ If the class is *3T #eriali9able class #ingleton private static #ingleton instanceprivate #ingleton/ 0 public static synchroni9ed #ingleton getInstance/ if instance 55 null/ instance 5 new #ingleton/return instance0 XX This method avoids the object from being cloned XX public 3bject clone/ throws Clone*ot#upportedxception return instance0 0 How is static %#nchroni&ation different form non-static s#nchroni&ation?
Ced after some time, this object of Class is not >Ced untill all the objects associated with it are
>Ced. This means that when ever you call a @static synchroni9ed@ bloc&, 2$ loc&s access to this Class object and not any of your objects. 8our client can till access the non=static members of your objects. What are class members and Instance members?
Any global membersariables, methods etc./ which are static are called as Class level members and those which are non=static are called as Instance level members. ame few arba!e collection al!orithms?
"ere they go! $ar& and #weep Beference counting Tracing collectors Copying collectors "eap compaction $ar&=compact collectors Can we force arba!e collection?
java follows a philosophy of automatic garbage collection, you can suggest or encourage the 2$ to perform garbage collection but you can not force it. 3nce a variable is no longer referenced by anything it is available for garbage collection. 8ou can suggest garbage collection with #ystem.gc/, but this does not guarantee when it will happen. %ocal variables in methods go out of scope when the method exits. At this point the methods are eligible for garbage collection. ach time the method comes into scope the local variables are re=created. 4oes Java pass b# Ealue or reference?
Its uses Beference while manipulating objects but pass by value when sending method arguments. Those who feel why I added this simple )uestion in this section while claiming to be maintaining only strong and interesting )uestions, go ahead and answer following )uestions. a/
TestCall(yBef
A thread is never faster than a process. If you run a threadsay there+s a process which has spawned only one thread/ in one 2$ and a process in another and that both of them re)uire same resources then both of them would ta&e same time to execute. (ut, when a programApplication is thread basedremember here there will be multiple threads running for a single process/ then definetly a thread based appliationprogram is faster than a process based application. This is because, when ever a process re)uires or waits for a resource CPF ta&es it out of the critical section and allocates the mutex to another process.
(efore deallocating the ealier one, it stores the contexttill what state did it execute that process/ in registers. *ow if this deallocated process has to come bac& and execute as it has got the resource for which it was waiting, then it can+t go into critical section directly. CPF as&s that process to follow scheduling algorithm. #o this process has to wait again for its turn.
An object is considered garbage when it can no longer be reached from any pointer in the running program. The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objects left over are then considered garbage. What are !enerations in arba!e Collection terminolo!#? What is its relevance?
>arbage Collectors ma&e assumptions about how our application runs. $ost common assumption is that an object is most li&ely to die shortly after it was created! called infant mortality. This assumes that an object that has been around for a while, will li&ely stay around for a while. >C organi9es objects into generations young, tenured, and perm/. This tells that if an object lives for more than certain period of time it is moved from one generation to another generations say from young =; tenured =; permanent/. "ence >C will be run more fre)uently at the young generations and rarely at permanent generations. This reduces the overhead on >C and gives faster response time. What is a ,hrou!hput Collector?
The throughput collector is a generational collector similar to the default collector but with multiple threads used to do the minor collection. The major collections are essentially the same as with the default collector. (y default on a host with * CPFs, the throughput collector uses * garbage collector threads in the collection. The number of garbage collector threads can be controlled with a command line option. When to ;se the ,hrou!hput Collector?
Fse the throughput collector when you want to improve the performance of your application with larger numbers of processors. In the default collector garbage collection is done by one thread, and therefore garbage collection adds to the serial execution time of the application. The throughput collector uses multiple threads to execute a minor collection and so reduces the serial execution time of the application. A typical situation is one in which the application has a large number of threads allocating objects. In such an application it is often the case that a large young generation is needed What is A!!ressive Heap?
The =NN!?Aggressive"eap option inspects the machine resources si9e of memory and number of processors/ and attempts to set various parameters to be optimal for long=running, memory allocation=intensive jobs. It was originally intended for machines with large amounts of memory and a large number of CPFs, but in the 2E# platform, version 6..6 and later it has shown itself to be useful even on four processor machines. C/ is used along with adaptive si9ing =NN!?FseAdaptive#i9ePolicy/. The physical memory on the machines must be at least EKG$( before Aggressive "eap can be used. What is a Concurrent 0ow Pause Collector?
The concurrent low pause collector is a generational collector similar to the default collector. The
tenured generation is collected concurrently with this collector. This collector attempts to reduce the pause times needed to collect the tenured generation. It uses a separate garbage collector thread to do parts of the major collection concurrently with the applications threads. The concurrent collector is enabled with the command line option =NN!?FseConc$arweep>C. 1or each major collection the concurrent collector will pause all the application threads for a brief period at the beginning of the collection and toward the middle of the collection. The second pause tends to be the longer of the two pauses and multiple threads are used to do the collection wor& during that pause. The remainder of the collection is done with a garbage collector thread that runs concurrently with the application. The minor collections are done in a manner similar to the default collector, and multiple threads can optionally be used to do the minor collection. When to ;se the Concurrent 0ow Pause Collector?
Fse the concurrent low pause collector if your application would benefit from shorter garbage collector pauses and can afford to share processor resources with the garbage collector when the application is running. Typically applications which have a relatively large set of long=lived data a large tenured generation/, and run on machines with two or more processors tend to benefit from the use of this collector. "owever, this collector should be considered for any application with a low pause time re)uirement. 3ptimal results have been observed for interactive applications with tenured generations of a modest si9e on a single processor. What is Incremental 0ow Pause Collector?
The incremental low pause collector is a generational collector similar to the default collector. The minor collections are done with the same young generation collector as the default collector. 'o not use either =NN!?FseParallel>C or =NN!?FsePar*ew>C with this collector. The major collections are done incrementally on the tenured generation. This collector also &nown as the train collector/ collects portions of the tenured generation at each minor collection. The goal of the incremental collector is to avoid very long major collection pauses by doing portions of the major collection wor& at each minor collection. The incremental collector will sometimes find that a non= incremental major collection as is done in the default collector/ is re)uired in order to avoid running out of memory. When to ;se the Incremental 0ow Pause Collector?
Fse the incremental low pause collector when your application can afford to trade longer and more fre)uent young generation garbage collection pauses for shorter tenured generation pauses. A typical situation is one in which a larger tenured generation is re)uired lots of long= lived objects/, a smaller young generation will suffice most objects are short=lived and don+t survive the young generation collection/, and only a single processor is available. How do #ou enable the concurrent !arba!e collector on %un.s JE)?
=Nconcgc options allows us to use concurrent garbage collector 6.E.E47H?/we can also use =NN! ?FseConc$arweep>C which is available beginning with 2E# 6..6. What is a platform?
A platform is the hardware or software environment in which a program runs. $ost platforms can be described as a combination of the operating system and hardware, li&e
Transient variable can+t be seriali9e. 1or example if a variable is declared as transient in a #eriali9able class and the class is written to an 3bject#tream, the value of the variable can+t be written to the stream instead when the class is retrieved from the 3bject#tream the value of the variable becomes null.
How to mae a class or a bean seriali&able?
(y implementing either the java.io.#eriali9able interface, or the java.io.xternali9able interface. As long as one class in a class+s inheritance hierarchy implements #eriali9able or xternali9able, that class is seriali9able. What restrictions are placed on method overloadin!?
Two methods may not have the same name and argument list but different return types. ame Container classes*
The %ist interface provides support for ordered collections of objects. What is the difference between a %crollbar and a %crollPane?
A #crollbar is a Component, but not a Container. A #crollPane is a Container. A #crollPane handles its own events and performs its own scrolling. What is tunnellin!?
Tunnelling is a route to somewhere. 1or example, B$I tunnelling is a way to ma&e B$I application get through firewall. In C# world, tunnelling means a way to transfer data. What is meant b# NAbstract InterfaceN?
1irst, an interface is abstract. That means you cannot have any implementation in an interface. All the methods declared in an interface are abstract methods or signatures of the methods. Can Java code be compiled to machine dependent e(ecutable file?
8es. There are many tools out there. If you did so, the generated exe file would be run in the specific platform, not cross=platform. 4o not use the %trin! contatenation operator in len!th# loops or other places where performance could suffer* Is that true?
8es. What method is used to specif# a container.s la#out?
The set%ayout/ method is used to specify a container+s layout. Which containers use a =low0a#out as their default la#out?
The Panel and Applet classes use the 1low%ayout as their default layout. What state does a thread enter when it terminates its processin!?
The Collections API is a set of classes and interfaces that support operations on collections of objects. What is the 0ist interface?
The %ist interface provides support for ordered collections of objects. Is si&eof a e#word?
The si9eof operator is not a &eyword in 2ava.
Which class is the superclass for ever# class*
3bject. Which Container method is used to cause a container to be laid out and redispla#ed?
validate/ What.s the difference between a 1ueue and a stac?
#tac&s wor&s by last=in=first=out rule %I13/, while )ueues use the 1I13 rule What comes to mind when #ou hear about a #oun! !eneration in Java?
>arbage collection. Uou can create an abstract class that contains onl# abstract methods* $n the other hand" #ou can create an interface that declares the same methods* %o can #ou use abstract classes instead of interfaces?
#ometimes. (ut your class may be a descendent of another class and in this case the interface is your only option. What comes to mind when someone mentions a shallow cop# in Java?
3bject cloning. If #ou.re overridin! the method e1uals23 of an ob
hashCode/ Uou are plannin! to do an inde(ed search in a list of ob
Array%ist How would #ou mae a cop# of an entire Java ob
"ave this class implement Cloneable interface and call its method clone/. How can #ou minimi&e the need of !arba!e collection and mae the memor# use more effective?
Fse object pooling and wea& object references. ,here are two classes@ A and * ,he class need to inform a class A when some important event has happened* What Java techni1ue would #ou use to implement it?
If these classes are threads I+d consider notify/ or notifyAll/. 1or regular classes you can use the 3bserver interface. What access level do #ou need to specif# in the class declaration to ensure that onl# classes from the same director# can access it?
8ou do not need to specify any access level, and 2ava will use a default pac&age access level. What is the difference between an Interface and an Abstract class? An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members private, protected, etc./, but has some abstract methods.
What is the purpose of !arba!e collection in Java" and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A 2ava object is subject to garbage collection when it becomes unreachable to the program in which it is used. 4escribe s#nchroni&ation in respect to multithreadin!*
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 b# reference and passb# value?
Pass (y Beference means the passing the address itself rather than passing the value. Passby alue means passing a copy of the value to be passed. What is Hash)ap and )ap?
$ap is Interface and "ashmap is class that implements that. 4ifference between Hash)ap and Hash,able?
The "ash$ap class is roughly e)uivalent to "ashtable, except that it is unsynchroni9ed and permits nulls. "ash$ap allows null values as &ey and value whereas "ashtable doesnt allow/. "ash$ap does not guarantee that the order of the map will remain constant over time. "ash$ap is unsynchroni9ed and "ashtable is synchroni9ed. 4ifference between Eector and Arra#0ist?
ector is synchroni9ed whereas arraylist is not. 4ifference between %win! and AW,?
A
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invo&ed 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 invo&ed using the dot operator. What is an Iterator?
#ome of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to wal& through a collection of objects, operating on each object in turn. Bemember 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. %tate the si!nificance of public" private" protected" default modifiers both sin!l# and in combination and state the effect of paca!e relationships on declared items 1ualified b# these modifiers*
public ! Public class is visible in other pac&ages, 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 pac&age 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 pac&age from the class that owns the protected feature. default !
#tatic 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. #tatic 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 super class can be shadowed by another static method in a subclass, as long as the original method was not declared final. "owever, you can+t override a static method with a no static method. In other words, you can+t change a static method into an instance method in a subclass. What is final?
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. 8ou can+t change value of a final variable is a constant/. What if the main method is declared as private?
The program compiles properly but at runtime it will give @$ain method not public.@ message. What if the static modifier is removed from the si!nature of the main method?
Program compiles. (ut at runtime throws an error @*o#uch$ethodrror@. What if I write static public void instead of public static void?
Program compiles and runs properly. What if I do not provide the %trin! arra# as the ar!ument to the method?
Program compiles but throws a runtime error @*o#uch$ethodrror@. What is the first ar!ument of the %trin! arra# in main method?
The #tring array is empty. It does not have any element. This is unli&e CC?? where the first element by default is the program name. If I do not provide an# ar!uments on the command line" then the %trin! arra# of )ain method will be empt# or null?
It is empty. (ut not null. How can one prove that the arra# is not null but empt# usin! one line of code?
Print args.length. It will print 7. That means it is empty. (ut if it would have been null then it would have thrown a *ullPointerxception on attempting to print args.length.
Can an application have multiple classes havin! main method?
8es it is possible.
*o the program fails to compile. The compiler says that the main method is already defined in the class. 4o I need to import
*o. It is by default loaded internally by the 2$. Can I import same paca!e/class twice? Will the JE) load the paca!e twice at runtime?
3ne can import the same pac&age or same class multiple times. *either compiler nor 2$ complains abt it. And the 2$ will internally load the class only once no matter how many times you import the same class. What are Checed and ;nCheced '(ception?
A chec&ed exception is some subclass of xception or xception itself/, excluding class Buntimexception and its subclasses. $a&ing an exception chec&ed forces client programmers to deal with the possibility that the exception will be thrown. eg, I3xception thrown by java.io.1ileInput#tream+s read/ methodY Fnchec&ed exceptions are Buntimexception and any of its subclasses. Class rror and its subclasses also are unchec&ed.
*ested top=level classes, $ember classes, %ocal classes, Anonymous classes *ested top=level classes= If you declare a class within a class and specify the static modifier, the compiler treats the class just li&e any other top=level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a pac&age. eg, outer.inner. Top=level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top=level variety. $ember classes = $ember inner classes are just li&e other member methods and member variables and access to the member class is restricted, just li&e methods and variables. This means a public member class acts similarly to a nested top=level class. The primary difference between member classes and nested top=level classes is that member classes have access to the specific instance of the enclosing class. %ocal classes = %ocal classes are li&e local variables, specific to a bloc& of code. Their visibility is only within the bloc& of their declaration. In order for the class to be useful beyond the declaration
bloc&, it would need to implement a more publicly available interface.(ecause 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. Are the imports checed for validit# at compile time? e*!* will the code containin! an import such as
8es the imports are chec&ed for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol ! class A(C' location! pac&age io import java.io.A(C'4oes importin! a paca!e imports the subpaca!es as well? e*!* 4oes importin! com*)#,est* also import com*)#,est*;nit,ests*?
*o you will have to import the subpac&ages explicitly. Importing com.$yTest.X will import classes in the pac&age $yTest only. It will not import any class in any of it+s subpac&age. What is the difference between declarin! a variable and definin! a variable?
In declaration we just mention the type of the variable and it+s name.
*ull unless we define it explicitly. Can a top level class be private or protected?
*o. A top level class can not be private or protected. It can have either @public@ or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the @modifier private is not allowed here@. This means that a top level class can not be private. #ame is the case with protected. What t#pe of parameter passin! does Java support?
In 2ava the arguments are always passed by value . Primitive data t#pes are passed b# reference or pass b# value?
Primitive data types are passed by value. $b
2ava only supports pass by value.
#eriali9ation is a mechanism by which you can save the state of an object by converting it to a byte stream. How do I seriali&e an ob
The class whose instances are to be seriali9ed should implement an interface #eriali9able. Then you pass the instance to the 3bject3utput#tream which is connected to a fileoutputstream. This will save the object to a file.
Which methods of %eriali&able interface should I implement?
The seriali9able interface is an empty interface, it does not contain any methods. #o we do not implement any methods. How can I customi&e the seriali&ation process? i*e* how can one have a control over the seriali&ation process?
8es it is possible to have control over seriali9ation process. The class should implement xternali9able interface. This interface contains two methods namely readxternal and writexternal. 8ou should implement these methods and write the logic for customi9ing the seriali9ation process. What is the common usa!e of seriali&ation?
xternali9able is an interface which contains two methods readxternal and writexternal. These methods give you a control over the seriali9ation mechanism. Thus if your class implements this interface, you can customi9e the seriali9ation process by implementing these methods. When #ou seriali&e an ob
The seriali9ation mechanism generates an object graph for seriali9ation. Thus it determines whether the included object references are seriali9able or not. This is a recursive process. Thus when an object is seriali9ed, all the included objects are also seriali9ed alongwith the original obect. What one should tae care of while seriali&in! the ob
3ne should ma&e sure that all the included objects are also seriali9able. If any of the objects is not seriali9able then it throws a *ot#eriali9ablexception. What happens to the static fields of a class durin! seriali&ation?
There are three exceptions in which seriali9ation doesnot necessarily read and write to the stream. These are 6. #eriali9ation ignores static fields, because they are not part of ay particular state state. E. (ase class fields are only hendled if the base class itself is seriali9able. O. Transient fields. 4oes Java provide an# construct to find out the si&e of an ob
*o there is not si9eof operator in 2ava. #o there is not direct way to determine the si9e of an object directly in 2ava. What are wrapper classes?
2ava provides speciali9ed classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, 'ouble etc. ive a simplest wa# to find out the time a method taes for e(ecution without usin! an# profilin! tool?
Bead the system time just before the method is invo&ed and immediately after method returns. Ta&e the time difference, which will give you the time ta&en by a method for execution. To put it in code... long start 5 #ystem.currentTime$illis /-
method /long end 5 #ystem.currentTime$illis /#ystem.out.println @Time ta&en for execution is @ ? end = start//Bemember that if the time ta&en for execution is too small, it might show that it is ta&ing 9ero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amount of processing. Wh# do we need wrapper classes?
It is sometimes easier to deal with primitives as objects. $oreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. (ecause of these reasons 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 are checed e(ceptions?
Chec&ed exception are those which the 2ava compiler forces you to catch. e.g. I3xception are chec&ed xceptions. What are runtime e(ceptions?
Buntime 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 chec&ed by the compiler at compile time. What is the difference between error and an e(ception? An error is an irrecoverable condition occurring at runtime. #uch as 3ut3f$emory error. These 2$ errors and you can not repair them at runtime.
8our class should extend class xception, or some more specific type thereof. If I want an ob
The class should extend from xception class. 3r you can extend your class from some more precise exception type also. If m# class alread# e(tends from some other class what should I do if I want an instance of m# class to be thrown as an e(ception ob
3ne can not do anything in this scenario. (ecause 2ava does not allow multiple inheritance and does not provide any exception interface as well. How does an e(ception permeate throu!h the code?
An unhandled exception moves up the method stac& in search of a matching
catch bloc&. This process continues until a catch bloc& handling the appropriate type of exception is found. If it does not find such a bloc& then finally the program terminates. What are the different wa#s to handle e(ceptions?
There are two ways to handle exceptions, 6. (y wrapping the desired code in a try bloc& followed by a catch bloc& to catch the exceptions. and E. %ist the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions. What is the basic difference between the 7 approaches to e(ception handlin!* 6* tr# catch bloc and 7* specif#in! the candidate e(ceptions in the throws clause? When should #ou use which approach?
In the first approach as a programmer of the method, you yourself 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.
It is not necessary that each try bloc& must be followed by a catch bloc&. It should be followed by either a catch bloc& 3B a finally bloc&. And whatever exceptions are li&ely to be thrown should be declared in the throws clause of the method. If I write return at the end of the tr# bloc" will the finall# bloc still e(ecute?
8es even if you write return as the last statement in the try bloc& and no exception occurs, the finally bloc& will execute. The finally bloc& will execute and then the control return. If I write %#stem*e(it 293 at the end of the tr# bloc" will the finall# bloc still e(ecute?
*o in this case the finally bloc& will not execute because when you say #ystem.exit 7/- the control immediately goes out of the program, and thus finally never executes. How are $bserver and $bservable used?
3bjects that subclass the 3bservable class maintain a list of observers.
It uses those low order bytes of the result that can fit into the si9e of the type allowed by the operation. 4oes !arba!e collection !uarantee that a pro!ram will not run out of memor#?
>arbage collection does not guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection . What is the difference between preemptive schedulin! and time slicin!?
Fnder preemptive scheduling, the highest priority tas& executes until it enters the waiting or dead states or a higher priority tas& comes into existence. Fnder time slicing, a tas& executes for a predefined slice of time and then reenters the pool of ready tas&s. The scheduler then determines which tas& should execute next, based on priority and other factors. When a thread is created and started" what is its initial state?
A thread is in the ready state after it has been created and started. What is the purpose of finali&ation?
The purpose of finali9ation is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. What is the 0ocale class?
The %ocale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. What is the difference between a while statement and a do statement?
A while statement chec&s at the beginning of a loop to see whether the next loop iteration should occur. A do statement chec&s 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? A static variable is associated with the class as a whole rather than with specific instances of a class. *on=static variables ta&e on uni)ue values with each object instance. How are this23 and super23 used with constructors?
This/ is used to invo&e a constructor of the same class. super/ is used to invo&e a superclass constructor. What are s#nchroni&ed methods and s#nchroni&ed statements?
#ynchroni9ed methods are methods that are used to control access to an object. A thread only executes a synchroni9ed method after it has ac)uired the loc& for the method+s object or class. #ynchroni9ed statements are similar to synchroni9ed methods. A synchroni9ed statement can only be executed after a thread has ac)uired the loc& for the object or class referenced in the synchroni9ed statement. What is daemon thread and which method is used to create the daemon thread?
'aemon thread is a low priority thread which runs intermittently in the bac& ground doing the garbage collection operation for the java runtime system. set'aemon method is used to create a daemon thread. Can applets communicate with each other?
At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information bac& and forth through a static variable. An applet can also get references to all other applets on the same page using the getApplets/
method of java.applet.AppletContext. 3nce you get the reference to an applet, you can communicate with it by using its public members. It is conceivable to have applets in different virtual machines that tal& to a server somewhere on the Internet and store any data that needs to be seriali9ed there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non=trivial. What are the steps in the J4C connection?
An unreachable object may become reachable again. This can happen when the object+s finali9e/ method is invo&ed and the object performs an operation which causes it to become accessible to reachable objects. What method must be implemented b# all threads?
All tas&s must implement the run/ method, whether they are a subclass of Thread or implement the Bunnable interface. What are s#nchroni&ed methods and s#nchroni&ed statements?
#ynchroni9ed methods are methods that are used to control access to an object. A thread only executes a synchroni9ed method after it has ac)uired the loc& for the method+s object or class. #ynchroni9ed statements are similar to synchroni9ed methods. A synchroni9ed statement can only be executed after a thread has ac)uired the loc& for the object or class referenced in the synchroni9ed statement. What is '(ternali&able?
xternali9able is an Interface that extends #eriali9able Interface. And sends data into #treams in Compressed 1ormat. It has two methods, writexternal3bject3uput out/ and readxternal3bjectInput in/ What modifiers are allowed for methods in an Interface?
3nly public and abstract modifiers are allowed for methods in interfaces. What are some alternatives to inheritance?
'elegation is an alternative to inheritance. 'elegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to thin& about each message you forward, because the instance is of a &nown class, rather than a new class, and because it doesn+t force you to accept all the
methods of the super class! you can provide only the methods that really ma&e sense. 3n the other hand, it ma&es you write more code, and it is harder to re=use because it is not a subclass/. What does it mean that a method or field is NstaticN?
#tatic variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. #tatic methods can be referenced with the name of the class rather than the name of a particular object of the class though that wor&s too/. That+s how library methods li&e #ystem.out.println/ wor& out is a static field in the java.lang.#ystem class. What is the difference between preemptive schedulin! and time slicin!?
Fnder preemptive scheduling, the highest priority tas& executes until it enters the waiting or dead states or a higher priority tas& comes into existence. Fnder time slicing, a tas& executes for a predefined slice of time and then reenters the pool of ready tas&s. The scheduler then determines which tas& should execute next, based on priority and other factors. What is the catch or declare rule for method declarations?
If a chec&ed exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. Is 'mpt# *
8es, an empty .java file is a perfectly valid source file. Can a *
8es, a .java file contain more than one java classes, provided at the most one of them is a public class. Is %trin! a primitive data t#pe in Java?
*o #tring is not a primitive data type in 2ava, even though it is one of the most extensively used object. #trings in 2ava are instances of #tring class defined in java.lang pac&age. Is main a e#word in Java?
*o, main is not a &eyword in 2ava. Is ne(t a e#word in Java?
*o, next is not a &eyword. Is delete a e#word in Java?
*o, delete is not a &eyword in 2ava. 2ava does not ma&e use of explicit destructors the way C?? does. Is e(it a e#word in Java?
*o. To exit a program explicitly you use exit method in #ystem object. What happens if #ou don.t initiali&e an instance variable of an# of the primitive t#pes in Java?
2ava by default initiali9es it to the default value for that primitive type. Thus an int will be initiali9ed to 7, a (oolean will be initiali9ed to false. What will be the initial value of an ob