Anda di halaman 1dari 25

Core Java Interview Questions

1. Why threads block or enters to waiting state on I/O? Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed.

2. What is List interface? List is an ordered collection of objects. 3. What is the difference between yield() and slee ()? When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state. !. What are Wra er Classes ? They are wrappers to primitive data types. They allow us to access primitives as objects. ". Can we call finali#e() $ethod ? Yes. obody will stop us to call any method ! if it is accessible in our class. But a "arba"e collector cannot call an object#s finali$e method if that object is reachable. %&. What is the difference between ti$e slicin' and ree$ tive schedulin' ? %n preemptive schedulin"! hi"hest priority task continues e&ecution till it enters a not runnin" state or a hi"her priority task comes into e&istence. %n ime slicin"! the task continues its e&ecution for a predefined period of time and reenters the pool of ready tasks. %%. What is the initial state of a thread when it is created and started? The thread is in ready state. %2. Can we declare an anony$ous class as both e(tendin' a class and i$ le$entin' an interface? o. 'n anonymous class can e&tend a class or implement an interface! but it cannot be declared to do both %3. What are the differences between boolean )) o erator and ) o erator? When an e&pression containin" the ( operator is evaluated! both operands are evaluated. 'nd the ( operator is applied to the operand. When an e&pression containin" (( operator is evaluated! the first operand is evaluated. %f the first operand returns a value of true then only the second operand is evaluated otherwise the second part will not "et e&ecuted. (( is also called short cut and. %*.What is the use of the finally bloc+? )inally is the block of code that e&ecutes always. The code in finally block will e&ecute even if an e&ception is occurred. finally will not e&ecute when the user calls *ystem.e&it(). %,. What is an abstract $ethod ? 'n abstract method is a method that don#t have a body. %t is declared with modifier abstract.
An abstract method is a method whose implementation is deferred to a subclass.

%-. What is the difference between .yste$.err and .yste$.out? We can redirect *ystem.out to another file but we cannot redirect *ystem.err stream %/. What are the differences between an abstract class and an interface? 'n abstract class can have concrete method! which is not allowed in an interface. 'bstract class can have private or protected methods and variables and only public methods and variables are allowed in interface. We can implement more than one interface ! but we can e&tend only one abstract class. %nterfaces provides loose couplin" where as abstract class provides ti"ht couplin". %!. What is the difference between synchroni#ed bloc+ and synchroni#ed $ethod? *ynchroni$ed blocks place locks for the specified block where as synchroni$ed methods place locks for the entire method. %". 0ow can you force 'arba'e collection in 1ava? You cannot force +arba"e ,ollection! but you can re-uest for it by callin" the method *ystem."c(). But it doesn#t mean that +arba"e ,ollection will start immediately. The "arba"e collection is a low priority thread of ./0. 2&. 0ow can you call a constructor fro$ another constructor ? By usin" this() reference. 2%. 0ow can you call the constructor of su er class ? By usin" super() synta&. The 1acka"e Youn" man mails himself in a bo& to his "irlfriend... naked. 2omain ames 3elpful links on buyin" a domain name. 0essa"e Boards 4 56.77 0essa"e board hostin". )ully customi$able! no advertisin". 1arental ,ontrol *oftware 8eep Your 8ids *afe 9nline With 1,Tattletale %nternet 0onitorin". 22. What2s the difference between nor$al $ethods and constructors? ,onstructors must have the same name of the class and can not have a return type. They are called only once! while re"ular methods can be called whenever re-uired. We cannot e&plicitly call a constructor. 23. What is the use of ac+a'es in 1ava ?

1acka"es are a way to or"ani$e files in java when a project consists of more than one module. %t helps in resolvin" name conflicts when different modules have classes with the same names. 2*. What $ust be the order of catch bloc+s when catchin' $ore than one e(ce tion? The sub classes must come first. 9therwise it will "ive a compile time error. 2,. 0ow can we call a $ethod or variable of the su er class fro$ child class ? We can use super.method() or super.variable synta& for this purpose. 2-. If you are overridin' e3uals() $ethod of a class4 what other $ethods you $i'ht need to override ? hash,ode 2/. 0ow can you create your own e(ce tion? 9ur class must e&tend either :&ception or its sub class 2!. What is seriali#ation? *eriali$ation is the process of savin" the state of an object. 2". What is de5seriali#ation? 2e4seriali$ation is the process of restorin" the state of an object. 3&. What is e(ternali#able? %t is an interface that e&tends *eriali$able. %t is havin" two different methods write:&ternal() and read:&ternal. This interface allows us to customi$e the output. 3%. 6oes 'arba'e collection 'uarantee that a ro'ra$ will not run out of $e$ory? +arba"e collection does not "uarantee that a pro"ram will not run out of memory. %t is also possible for pro"rams to create objects that are not subject to "arba"e collection. 'nd there is no "uarantee that +arba"e ,ollection thread will be e&ecuted. 32. What is a native $ethod? native method is a method that is implemented in a lan"ua"e other than .ava. ;;. What are different type of e&ceptions in .ava< There are two types of e&ceptions in java. ,hecked e&ceptions and =nchecked e&ceptions. 'ny e&ception that is is derived from Throwable and :&ception is called checked e&ception e&cept >untime:&ception and its sub classes. The compiler will check whether the e&ception is cau"ht or not at compile time. We need to catch the checked e&ception or declare in the throws clause. 'ny e&ception that is derived from :rror and >untime:&ception is called unchecked e&ception. We don#t need to e&plicitly catch a unchecked e&ception. )ore& ,urrency Tradin" 3elpful links on )ore& currency tradin". Tired 9f 0y*pace< 0eet cool people at Ta"World? 'cne 3elpful links on on several acne treatments. 0ake 0oney 9nline 3elpful links to pro"rams to makin" money from home. 3*. Can we catch an error in our 1ava ro'ra$ ? Yes. We can . We can catch anythin" that is derived from Throwable. *ince :rror is a sub class of Throwable we can catch an error also. 3,. What is thread riority? Thread 1riority is an inte"er value that identifies the relative order in which it should be e&ecuted with respect to others. The thread priority values ran"in" from @4 @A and the default value is B. But if a thread have hi"her priority doesn#t means that it will e&ecute first. The thread schedulin" depends on the 9*. 3-. 0ow $any ti$es $ay an ob1ect2s finali#e() $ethod be invo+ed by the 'arba'e collector? 9nly once. 3/. What is the difference between a continue state$ent and a brea+ state$ent? Break statement results in the immediate termination of the statement to which it applies (switch! for! do! or while). ' continue statement is used to end the current loop iteration and return control to the loop statement. 3!. What $ust a class do to i$ le$ent an interface? %t must identify the interface in its implements clause. 'lso it must provide definition for all the methods in the interface otherwise it must be declared abstract. 3". What is an abstract class? 'n abstract class is an incomplete class. %t is declared with the modifier abstract. We cannot create objects of the abstract class. %t is used to specify a common behavioral protocol for all its child classes. *&. What is the difference between notify and notify7ll $ethod ? notify wakes up a sin"le thread that is waitin" for object#s monitor. %f any threads are waitin" on this object! one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. notify'll Wakes up all threads that are waitin" on this object#s monitor. ' thread waits on an object#s monitor by callin" one of the wait methods. *%. What does wait $ethod do ? %t causes current thread to wait until either another thread invokes notify or notify'll method of the current object! or a specified amount of time has elapsed. *2. What are the different states of a thread? The different thread states are ready! runnin"! waitin" and dead. *3. What is the difference between static and non static inner class? non4static inner class can have an object instances that are associated with instances of the class#s outer class. ' static inner class can not have any object instances. **. What is the difference between .trin' and .trin'8uffer class ? *trin"s are immutable (constant)! their values cannot be chan"ed after they are created. *trin"Buffer supports mutable objects. *,. Which is the base class for all classes?

java.lan".9bject. *-. What is the difference between readers and strea$s? >eaders are character oriented where streams are byte oriented. The readers are havin" full support for =nicode data. */. What is constructor chainin'? When a constructor of a class is e&ecuted it will automatically call the default constructor of the super class (if no e&plicit call to any of the super class constructor) till the root of the hierarchy. *!. What are the different ri$itive data ty es in 1ava? There are C primitive types in java. boolean ! char! byte! short! int lon"! float! double. *". What is static? static means one per class. static variables are created when the class loads. They are associated with the class. %n order to access a static we don#t need objects. We can directly access static methods and variable by callin" classname.variablename. ,&. Why we cannot override static $ethods? *tatic means they are associated with a class. %n static methods! the bindin" mechanism is static bindin". *o it must be available at the compile time. ,%. What is the difference between static and non static variables? ' static variable is associated with the class as a whole rather than with specific instances of a class. There will be only one value for static variable for all instances of that class. on4static variables take on uni-ue values with each object instance. ,2. When does a co$ iler su lies a default constructor for a class? %f there is no other constructor e&ist in a class! the compiler will supply a default constructor. ,3. What are the restrictions laced on overridin' a $ethod ? The overridden method have the e&act si"nature of the super class method! includin" the return type. The access specified cannot be less restrictive than the super class method. We cannot throw any new e&ceptions in overridden method. ,*. What are the restrictions laced on overloadin' a $ethod? 9verloadin" methods must differ in their parameter list! or number of parameters. ,,. What is castin'? ,astin" means convertin" one type to another. There are mainly two types of castin". ,astin" between primitive types and castin" between object references. ,astin" between primitive numeric types is used to convert lar"er data types to smaller data types. ,astin" between object references is used to refer to an object by a compatible class! interface! or array type reference. ,-. What is the difference between 99 and e3uals? The e-uals method can be considered to perform a deep comparison of the value of an object! whereas the DD operator performs a shallow comparison. %f we are not overridin" the e-uals method both will "ive the same result. DD will is used to compare the object references. %t is used to check whether two objects are points to the same reference. ,/. What is a void return ty e ? void indicates that the method will not return anythin". ,!. What will ha en if an e(ce tion is not cau'ht ? 'n uncau"ht e&ception results in the uncau"ht:&ception() method of the thread#s Thread+roup! which results in the termination of the pro"ram. ,". What are the different ways in which a thread can enter into waitin' state? There are three ways for a thread to enter into waitin" state. By invokin" its sleep() method! by blockin" on %E9! by unsuccessfully attemptin" to ac-uire an object#s lock! or by invokin" an object#s wait() method. -&. What is a :esource8undle class? The >esourceBundle class is used to store locale4specific resources that can be loaded by a pro"ram to create the pro"ram#s appearance to the particular locale in which it is bein" run. -%. What is nu$eric ro$otion? umeric promotion is the conversion of a smaller numeric type to a lar"er numeric type. %n numerical promotion! byte! char! and short values are converted to int values. The int! lon" and float values are converted to the desired types if re-uired. -2. What is the difference between the refi( and ostfi( for$s of the ;; o erator? The prefi& form first performs the increment operation and then returns the value of the increment operation. The postfi& form first returns the current value of the e&pression and then performs the increment operation on that value. -3. What are synchroni#ed $ethods and synchroni#ed state$ents? *ynchroni$ed methods are methods that are declared with the keyword synchroni$ed. ' thread e&ecutes a synchroni$ed method only after it has ac-uired the lock for the method#s object or class. *ynchroni$ed statements are similar to synchroni$ed methods. %t is a block of code declared with synchroni$ed keyword. ' synchroni$ed statement can be e&ecuted only after a thread has ac-uired the lock for the object or class referenced in the synchroni$ed statement. -*. 0ow can we create a thread? thread can be created by e&tendin" Thread class or by implementin" >unnable interface. Then we need to override the method public void run(). -,. What is the difference between a switch state$ent and an if state$ent?

%f statement is used to select from two alternatives. %t uses a boolean e&pression to decide which alternative should be e&ecuted. The e&pression in if must be a boolean value. The switch statement is used to select from multiple alternatives. The case values must be promoted to an to int value. --. What is hashCode? The hashcode of a .ava 9bject is simply a number (;F4bit si"ned int) that allows an object to be mana"ed by a hash4based data structure. ' hashcode should be! e-ual for e-ual object (this is mandatory?) ! fast to compute based on all or most of the internal state of an object! use all or most of the space of ;F4bit inte"ers in a fairly uniform way ! and likely to be different even for objects that are very similar. %f you are overridin" hash,ode you need to override e-uals method also. -/. What is an I<= filter? 'n %E9 filter is an object that reads from one stream and writes to another! usually alterin" the data in some way as it is passed from one stream to another. -!. What is the difference between :ando$7ccess>ile and >ile? The )ile class contains information the files and directories of the local file system. The >andom'ccess)ile class contains the methods needed to directly access data contained in any part of a file. -". What is final ? final is a keyword in java. %f final keyword is applied to a variable! then the variable will become a constant. %f it applied to method! sub classes cannot override the method. %f final keyword is applied to a class we cannot e&tend from that class. /&. What is the difference a$on' J?@ . ec4 J?@ I$ le$entation4 J?@ :unti$e? The ./0 spec is the blueprint for the ./0 "enerated and owned by *un. The ./0 implementation is the actual implementation of the spec by a vendor and the ./0 runtime is the actual runnin" instance of a ./0 implementation /%. 0ow is the difference between thread and rocess? process runs in its own address space. o two processes share their address space. Threads will run in the same address space of the process that owns them. /2. What is the difference between ?ector and 7rrayList ? /ector is synchroni$ed! 'rrayList is not. /ector is havin" a constructor to specify the incremental capacity. But 'rrayList don#t have. By default /ector "rows by @AAG but 'rrayList "rows by BAG only. H;. What is the difference between 3ashtable and 3ash0ap < 3ashtable is synchroni$ed . but 3ash0ap is not synchroni$ed. 3ashtable does not allow null values ! but 3ash0ap allows null values. /*. What are the access $odifiers available in Java. 'ccess modifier specify where a method or attribute can be used. 1ublic is accessible from anywhere. 1rotected is accessible from the same class and its subclasses. 1acka"eE2efault are accessible from the same packa"e. 1rivate is only accessible from within the class. /,. Why 1ava is said to be ass5by5value ? When assi"nin" an object to a variable! we are actually assi"nin" the memory address of that object to the variable. *o the value passed is actually the memory location of the object. This results in object aliasin"! meanin" you can have many variables referrin" to the same object on the heap. /-. What do you $ean by i$$utable ? 0ow to create an i$$utable ob1ect? %mmutability means an object cannot be modified after it has been initiali$ed. There will not be any setter methods in an immutable class. 'nd normally these classes will be final. //. What is class loader in 1ava ? class loader is a class that is responsible for loadin" the class. 'll ./0 contains one class loader called primordial class loader. /!. What is a wea+ reference? weak reference is the one that does nor prevent the referenced object from bein" "arba"e collected. The weak reference will not keep the object that it refers to alive. ' weak reference is not counted as a reference in "arba"e collection. This will make the memory use more effective. /". What is ob1ect clonin'? %t is the process of duplicatin" an object so that two identical objects will e&ist in the memory at the same time. !&. What is ob1ect oolin'? ,reatin" a lar"e number of identical short lived objects is called object poolin". This helps to minimi$e the need of "arba"e collection and makes the memory use more effective. !%. What is 'arba'e collection? +arba"e collection is the process of releasin" memory used by unreferenced objects. %t relieves the pro"rammer from the process of manually releasin" the memory used by objects . !2. What is the disadvanta'e of 'arba'e collection? %t adds an overhead that can affect performance. 'dditionally there is no "uarantee that the object will be "arba"e collected. !3. What is a 6ictionary? 2ictionary is a parent class for any class that maps keys to values. %n a dictionary every key is associated with at most one value. !*. What is J7: file ?

.'> stands for .ava 'rchive. This is a file format that enables you to bundle multiple files into a sin"le archive file. ' jar file will contains a manifest.mf file inside 0:T'4% ) folder that describes the version and other features of jar file. !,. Why Java is not fully ob1ective oriented ? 2ue to the use of primitives in java! which are not objects. !-. What is a $ar+er interface ? 'n interface that contains no methods. :"I *eriali$able! ,loneable! *in"leThread0odel etc. %t is used to just mark java classes that support certain capability. !/. What are ta' interfaces? Ta" interface is an alternate name for marker interface. !!. What are the restrictions laced on static $ethod ? We cannot override static methods. We cannot access any object variables inside static method. 'lso the this reference also not available in static methods. !". What is J?@? ./0 stands for .ava /irtual 0achine. %t is the run time for java pro"rams. 'll are java pro"rams are runnin" inside this ./0 only. %t converts java byte code to 9* specific commands. %n addition to "overnin" the e&ecution of an application#s byte codes! the virtual machine handles related tasks such as mana"in" the system#s memory! providin" security a"ainst malicious code! and mana"in" multiple threads of pro"ram e&ecution. "&. What is JIA? .%T stands for .ust %n Time compiler. %t compiles java byte code to native code. 7@. What is java byte code< Byte code is an sort of intermediate code. The byte code is processed by virtual machine. "2. What is $ethod overloadin'? 0ethod overloadin" is the process of creatin" a new method with the same name and different si"nature. "3. What is $ethod overridin'? 0ethod overridin" is the process of "ivin" a new definition for an e&istin" method in its child class. "*. What is finali#e() ? )inali$e is a protected method in java. When the "arba"e collector is e&ecutes ! it will first call finali$e( )! and on the ne&t "arba"e4collection it reclaim the objects memory. *o finali$e( )! "ives you the chance to perform some cleanup operation at the time of "arba"e collection. ",. What is $ulti5threadin'? 0ulti4threadin" is the scenario where more than one threads are runnin". "-. What is deadloc+? 2eadlock is a situation when two threads are waitin" on each other to release a resource. :ach thread waitin" for a resource which is held by the other waitin" thread. "/. What is the difference between Iterator and Bnu$eration? %terator differ from enumeration in two ways %terator allow the caller to remove elements from the underlyin" collection durin" the iteration with well4defined semantics. 'nd ! method names have been improved. "!. What is the Locale class? Locale object represents a specific "eo"raphical! political! or cultural re"ion "". What is internationali#ation? %nternationali$ation is the process of desi"nin" an application so that it can be adapted to various lan"ua"es and re"ions without chan"es. %&&. What is anony$ous class ? 'n anonymous class is a type of inner class that don#t have any name. %&%. What is the difference between C:L and C:LConnection? =>L represents the location of a resource! and a =>L,onnection represents a link for accessin" or communicatin" with the resource at the location. %&2. What are the two i$ ortant ACD .oc+et classes? *erver*ocket and *ocket. *erver*ocket is useful for two4way socket communication. *ocket class help us to read and write throu"h the sockets. "et%nput*tream() and "et9utput*tream() are the two methods available in *ocket class. %&3. .trin's are i$$utable. 8ut .trin' s9E0elloEF .trin' s%9s;EWorldE returns 0elloWorld how? 3ere actually a new object is created with the value of 3elloWorld %&-. What is 1ava collections? .ava collections is a set of classes! that allows operations on a collection of classes. %&/. Can we co$ ile a 1ava ro'ra$ without $ain? Yes! we can. %n order to compile a java pro"ram! we don#t re-uire any main method. But to e&ecute a java pro"ram we must have a main in it (unless it is an applet or servlet). Because main is the startin" point of a java pro"ram. %&!. What is a 1ava co$ ilation unit. ' compilation unit is a java source file. %&". What are the restrictions when overridin' a $ethod ? 9verridden methods must have the same name! ar"ument list! and return type (i.e.! they must have the e&act si"nature of the method we are "oin" to override! includin" return type.) The overridin" method cannot be less visible than the method it overrides( i.e.! a public method cannot be override to private). The overridin" method may not throw any e&ceptions that may not be thrown by the overridden method %%&. What is static initiali#er bloc+? What is its use?

' static initiali$er block is a block of code that declares with the static keyword. %t normally contains the block of code that must e&ecute at the time of class loadin". The static initiali$er block will e&ecute only once at the time of loadin" the class only. %%%. 0ow does a try state$ent deter$ine which catch clause should be used to handle an e(ce tion? When an e&ception is thrown ! the catch block of the try statement are e&amined in the order in which they appear. The first catch block that is capable of handlin" the e&ception is e&ecuted. The remainin" catch blocks are i"nored %%2. 0ow ara$eters are assed to $ethods in 1ava ro'ra$ ? 'll java method parameters in java are passed by value only. 9bviously primitives are passed by value. %n case of objects a copy of the reference is passed and so all the chan"es made in the method will persist. %%3. If a class doesn2t have any constructors4 what will ha en? %f a class doesn#t have a constructor! the ./0 will provide a default constructor for the class. @@6. What will happen if a thread cannot ac-uire a lock on an object< %t enters to the waitin" state until lock becomes available. %%,. 0ow does $ultithreadin' occurrin' on a co$ uter with a sin'le CDC? The task scheduler of 9* allocates an e&ecution time for multiple tasks. By switchin" between different e&ecutin" tasks! it creates the impression that tasks e&ecute se-uentially. But actually there is only one task is e&ecuted at a time. %%-. What will ha en if you are invo+in' a thread2s interru t $ethod while the thread is waitin' or slee in'? When the task enters to the runnin" state! it will throw an %nterrupted:&ception. %%/. What are the different ways in which a thread can enter into waitin' state? There are three ways for a thread to enter into waitin" state. By invokin" its sleep() method! by blockin" on %E9! by unsuccessfully attemptin" to ac-uire an object#s lock! or by invokin" an object#s wait() method. %%!. What are the the different ways for creatin' a thread? ' thread can be created by subclassin" Thread! or by implementin" the >unnable interface. %%". What is the difference between creatin' a thread by e(tendin' Ahread class and by i$ le$entin' :unnable interface? Which one should refer? When creatin" a thread by e&tendin" the Thread class! it is not mandatory to override the run method (%f we are not overridin" the run method ! it is useless)! because Thread class have already "iven a default implementation for run method. But if we are implementin" >unnable ! it is mandatory to override the run method. The preferred way to create a thread is by implementin" >unnable interface! because it "ive loose couplin". %2&. What is cou lin'? ' ,ouplin" is the dependency between different components of a system %3-. Why Java is not %&&G ure ob1ect oriented lan'ua'e? Because java uses primitives. %3/. Why 7rrayList is faster than ?ector? Because /ector is synchroni$ed. *ynchroni$ation reduces the performance. %3!. What is the security $echnais$ used in 1ava? .ava uses sand bo& security model. %3". What is sandbo(? ' sandbo& is a security mechanism for safely runnin" pro"rams. The sandbo& typically provides a ti"htly4controlled set of resources for "uest pro"rams to run in! such as scratch space on disk and memory. %*&. What is hanto$ $e$ory? 1hantom memory is the memory that does not e&ist in reality. %*%. What is reflection? >eflection is the process of findin" out the different features of a class dynamically. @6F. What are the differences between .%T and 3ot*pot< The 3otspot /0 is a collection of techni-ues! the most important of which is called adaptive optimi$ation. The ori"inal ./0s interpreted byte codes one at a time. *econd4"eneration ./0s added a .%T compiler! which compiles each method to native code upon first e&ecution! then e&ecutes the native code. Thereafter! whenever the method is called! the native code is e&ecuted. The adaptive optimi$ation techni-ue used by 3otspot is a hybrid approach! one that combines byte code interpretation and run4time compilation to native code. 3otspot! unlike a re"ular .%T compilin" /0! doesn#t do Jpremature optimi$ationJ %*3. What are the advanta'es and disadvanta'es of reference countin' in 'arba'e collection? 'n advanta"e of this scheme is that it can run in small chunks of time closely linked with the e&ecution of the pro"ram. These characteristic makes it particularly suitable for real4time environments where the pro"ram can#t be interrupted for very lon" time. ' disadvanta"e of reference countin" is that it does not detect cycles. ' cycle is two or more objects that refer to one another. 'nother disadvanta"e is the overhead of incrementin" and decrementin" the reference count each time. Because of these disadvanta"es! reference countin" currently is out of favor. %**. 0ow would you i$ le$ent a thread ool? The Thread1ool class is a "eneric implementation of a thread pool! which takes the followin" input *i$e of the pool to be constructed and name of the class which implements >unnable (which has a visible default constructor) and constructs a thread pool with active threads that are waitin" for activation. once the threads have finished processin" they come back and wait once a"ain in the pool. %*,. What is the difference between throw and throws clause? ' throw is used to throw an e&ception manually! where as throws is used in the case of checked e&ceptions! to tell the compiler that we haven#t handled the e&ception! so that the e&ception will be handled by the callin" function.

%*/. What is a classloader? ' class loader is an object that is responsible for loadin" classes. %*!. What is the difference between Co$ arable and Co$ arator ? ' The ,omparable is for natural orderin" and ,omparator is for custom orderin". But we can override the compareTo method of comparable interface to "ive a custom orderin". %*". What is the difference between List4 .et and @a ? ' ' *et is a collection that has no duplicate elements. ' List is a collection that has an order associated with its elements. ' map is a way of storin" keyEvalue pairs. The way of storin" a 0ap is similar to two4column table. %,&. What is the difference between B(ce tion and Brror? :rror is unrecoverable. %,%. What is $eant by = en .ource? %n "eneral! open source refers to any pro"ram whose source code is made available for use or modification as users or other developers see fit. 9pen source software is usually developed as a public collaboration and made freely available. %,2. 0ow do you send data fro$ an a let to .ervlet ? What are the ste s involved in it? You can use the java.net.=>L,onnection and java.net.=>L classes to open a standard 3TT1 connection to the web server. The server then passes this information to the servlet in the normal way. Basically! the applet pretends to be a web browser! and the servlet doesn#t know the difference. 's far as the servlet is concerned! the applet is just another 3TT1 client. The 1acka"e Youn" man mails himself in a bo& to his "irlfriend... naked. 2ru" >ehab 3elpful links on dru" addictions! treatment and rehab. )ore& 3elpful links on )ore& currency tradin". Tired 9f 0y*pace< 0eet cool people at Ta"World? %,3. What is oly$or his$? %t is the ability of an object to behave differently on different situations for the same messa"e. %,*. What is a class4 $e$ber and local variable? /ariables declared within a method are local variables. /ariables declared within the class are member variables. /ariables declared within the class with static modifier are class variables %,,. 0ow do I convert a nu$eric ID address li+e --.2".3-.%3& into a hostna$e li+e www.1avacertificate.net *trin" hostname D %net'ddress."etBy ame(JKK.F7.;K.@;AJ)."et3ost ame()L %,-. What is the difference between a constructor and a $ethod? ' constructor is a member function of a class that is used to create objects of that class. %t has the same name as the class itself! has no return type! and is invoked usin" the new operator. We cannot invoke a constructor directly. ' method is an ordinary member function of a class. %t has its own name! a return type (which may be void)! and is invoked usin" the dot operator. %,/. What are the different inner classes ty es? There are mainly four types available. They are 0ember classes! ested top4level classes! Local classes! 'nonymous classes %,!. What is Hested to 5level classes? ' class declared within a class with static modifier is called nested top level class. 'ny class outside the declarin" class can access the nested top level class with the declarin" class dot nested top level class. Top4level inner classes have access to static variables only . %,". What is @e$ber classes? ' class declared inside a class without static modifier is called member class. 0ember classes are just like any other member methods or member variables. %-&. What is Local inner classes? Local inner classes are class declared inside a block of code. They are visible only within the block of their declaration. %-%. Can a to level class be rivate or rotected? o. ' top level class can not be private or protected. %t can have either JpublicJ or no modifier. %-2. 0ow will you invo+e any e(ternal rocess in Java? ' By usin" >untime."et>untime().e&ec(M.) %-3. What is a ac+a'e? ' To "roup set of classes into a sin"le unit is known as packa"in". 1acka"es provides wide namespace visibility. %-*. What is the use of assert +eyword ' 'ssert keyword validates certain e&pressions. %t replaces the if block effectively and throws an 'ssertion:rror on failure. The assert keyword should be used only for critical ar"uments (means without that the method does nothin"). %-,. What is co$ osition? ' 3oldin" the reference of the other class within some other class is known as composition. %--. What is a''re'ation? %t is a special type of composition. %f you e&pose all the methods of a composite class and route the method call to the composite method throu"h its reference! then it is called a""re"ation %-/. What are the $ethods in =b1ect? clone! e-uals! wait! finali$e! "et,lass! hash,ode! notify! notify'll! to*trin" %-!. What is the relationshi between synchroni#ed and volatile +eyword?

The ./0 is "uaranteed to treat reads and writes of data of ;F bits or less as atomic. )or lon" or double variable! pro"rammers should take care in multi4threadin" environment. :ither put these variables in a synchroni$ed method or block! or declare them volatile. %-". What factors are used to decide usin' synchroni#ed or volatile? You can make a variable synchroni$ed or volatile under the followin" casesI @) if you are not updatin" many variables often in a multithread environment! consider usin" volatile. F) %f you are updatin" many variables! consider usin" synchroni$ed! because usin" volatile mi"ht be slower. %/&. What are the drawbac+s of inheritance? *ince inheritance inherits everythin" from the super class and interface! it may make the subclass too clusterin" and sometimes error4prone when dynamic overridin" or dynamic overloadin" in some situation. %n addition! the inheritance may make peers hardly understand your code if they don#t know how your super4class acts. %/%. What is the difference between static synchroni#ed and synchroni#ed $ethods? Both are synchroni$ed methods. 9ne is instance method! the other is class method. 0ethod with static modifier is a class method. That means the method belon"s to class itself and can be accessed directly with class name and is also called *in"leton desi"n. The method without static modifier is an instance method. That means the instance method belon"s to its object. :very instance of the class "ets its own copy of its instance method. %/2. What is the ur ose of the :unti$e class? The purpose of the >untime class is to provide access to the .ava runtime system. %/3. What is the ur ose of the .yste$ class? The purpose of the *ystem class is to provide access to system resources. %/*. 6oes the code in finally bloc+ 'et e(ecuted if there is an e(ce tion and a return state$ent in a catch bloc+? %f an e&ception occurs and there is a return statement in catch block! the finally block is still e&ecuted. The finally block will not be e&ecuted when the *ystem.e&it(@) statement is e&ecuted earlier or the system shut down earlier or the memory is used up earlier before the thread "oes to finally block. %/,. Considerin' note ad<IB or any other thin' as rocess4 What will ha en if you start note ad or IB 3 ti$es? Where ; processes are started or ; threads are started < ; processes will start. %/-. What are the restrictions laced on the values of each case of a switch state$ent? ' 't compile time! each case values of switch statement must evaluate to a an int value. %//. If aaaa is an array then why aaaa.len'th why not aaaa.len'th()? Because len"th is a property not a method. %/!. What is dyna$ic ty in'? ' 2ynamic typin" means type errors are detected at run time by checkin" the actual data types of the values a"ainst the re-uired data types %/". What is static ty i'? ' *tatic typin" means type errors are detected at compile time by checkin" the inferred data type is a subtype of the re-uired type %!&. What is 0ash@a and @a ? ' 0ap is %nterface and 3ash0ap is class that implements that. %!%. What is an =b1ect and how do you allocate $e$ory to it? 9bject is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspectin" and manipulatin" that data. When an object is created usin" new operator! memory is allocated to it. %!2. What is CHIC=6B? =nicode is used for internal representation of characters and strin"s and it uses @K bits to represent each other. %!3. What is ada ter class? 'n adapter class provides a default implementation of all methods in an event listener interface. 'dapter classes are useful when you want to process only some of the events that are handled by a particular event listener interface. You can define a new class by e&tendin" one of the adapter classes and implementin" only those events relevant to us. /o%1 *ervice %nfo and helpful links on /o%1 service and systems. The 1acka"e Youn" man mails himself in a bo& to his "irlfriend... naked. Web 3ostin" 3elpful links on on web hostin"! includin" reviews and more. 9nline Basketball 0ana"er Take controll of your free team and take it to the top? %!*. What is a strea$ and what are the ty es of .trea$s and classes of the .trea$s? ' stream is a flow of data from one direction to another. . There are two types of *treams Byte *treamsI 1rovide a convenient means for handlin" input and output of bytes. 'nd ,haracter *treamsI 1rovide a convenient means for handlin" input ( output of characters. %!,. What is the difference between ACD<ID and C6D? T,1E%1 is a two4way communication between the client and the server and it is a reliable and there is a confirmation re"ardin" reachin" the messa"e to the destination. =21 is a one4way communication only between the client and the server and it is not a reliable and there is no confirmation re"ardin" reachin" the messa"e to the destination. %!-. What is Inter5Ahread co$$unication?. :&chan"e of information between two threads.

%!/. What is a olicy?. %t#s an abstract class for representin" the system security policy for a .ava application environment (specifyin" which permissions are available for code from various sources). .ava security properties file resides in N.'/'4 390:OElibEsecurityEjava.security directory. %!!. What is a thread 'rou ? ' thread "roup is a data structure that controls the state of collection of thread as a whole mana"ed by the particular runtime environment. %!". Why is CA>6ata>or$atB(ce tion thrown by 6ata=ut ut.trea$.writeCA>() when seriali#in' a .trin'? 2ata9utput*tream.write=T)() does not support writin" out strin"s lar"er than K68. The first two bytes of a =T) strin" in the stream are the len"th of the strin". %f a java.lan".*trin" is lar"er than K68! it needs to be stored in the stream by an alternative method rather than dependin" on the default method of storin" a *trin" in the stream! write=T). %"&. Why is =ut=f@e$oryBrror thrown after writin' a lar'e nu$ber of ob1ects into an =b1ect=ut ut.trea$? The 9bject9utput*tream maintains a table mappin" objects written into the stream to a handle. The first time an object is written to a stream! its contents are written into the streamL subse-uent writes of the object result in a handle to the object bein" written into the stream. This table maintains references to objects that mi"ht otherwise be unreachable by an application! thus! resultin" in an une&pected situation of runnin" out of memory. ' call to the 9bject9utput*tream.reset() method resets the objectEhandle table to its initial state! allowin" all previously written objects to be eli"ible for "arba"e collection. %"%. 0ow can I 'et the serial?ersionCI6 of a class? By runnin" the serialver tool with the name of the class as the command line ar"umet! as shown in the e&ample that followsI serialver java.lan".*trin" %"2. What is serial?ersionCI6 ? ' The serial/ersion=%2 is a universal version identifier for a *eriali$able class. 2eseriali$ation uses this identifier number to ensure that a loaded class corresponds to a seriali$ed object. %"3. What is abstraction? 'n abstraction is an idea! concept! or word which defines the phenomena which make up the concrete events or thin"s which the abstraction refers to! the referents. %"*. What is enca sulation? ' :ncapsulation describes the ability of an object to hide its data and methods from the rest of the world %",. What is inheritance? %nheritance is the ability to create new classes based on e&istin" classes. %t is useful to reuse e&istin" code. %",. 0ow could Java classes direct ro'ra$ $essa'es to the syste$ console4 but error $essa'es4 say to a file? '. The class *ystem has a variable out that represents the standard output! and the variable err that represents the standard error device. By default! they both point at the system console. This how the standard output could be re4 directedI *tream st D new *tream(new )ile9utput*tream(Joutput.t&tJ))L *ystem.set:rr(st)L *ystem.set9ut(st)L %"-. What2s the difference between an interface and an abstract class? '. 'n abstract class may contain code in method bodies! which is not allowed in an interface. With abstract classes! you have to inherit your class from it and .ava does not allow multiple inheritance. 9n the other hand! you can implement multiple interfaces in your class. %"/. Why would you use a synchroni#ed bloc+ vs. synchroni#ed $ethod? '. *ynchroni$ed blocks place locks for shorter periods than synchroni$ed methods. *. B( lain the usa'e of the +eyword transient? '. This keyword indicates that the value of this member variable does not have to be seriali$ed with the object. When the class will be de4seriali$ed! this variable will be initiali$ed with a default value of its data type (i.e. $ero for inte"ers). %"!. 0ow can you force 'arba'e collection? '. You can#t force +,! but could re-uest it by callin" *ystem."c(). ./0 does not "uarantee that +, will be started immediately. %"". 0ow do you +now if an e( licit ob1ect castin' is needed? '. %f you assi"n a superclass object to a variable of a subclass#s data type! you need to do e&plicit castin". )or e&ampleI 9bject aL ,ustomer bL b D (,ustomer) aL When you assi"n a subclass to a variable havin" a supeclass type! the castin" is performed automatically. 2&&. What2s the difference between the $ethods slee () and wait() '. The code sleep(@AAA)L puts thread aside for e&actly one second. The code wait(@AAA)! causes a wait of up to one second. ' thread could stop waitin" earlier if it receives the notify() or notify'll() call. The method wait() is defined in the class 9bject and the method sleep() is defined in the class Thread. 2&&%. Can you write a Java class that could be used both as an a let as well as an a lication? Yes. 'dd a main() method to the applet. 2&&2. What2s the difference between constructors and other $ethods?

'. ,onstructors must have the same name as the class and can not return a value. They are only called once while re"ular methods could be called many times. 2&3. Can you call one constructor fro$ another if a class has $ulti le constructors '. Yes. =se this() synta&. 2&*. B( lain the usa'e of Java ac+a'es. '. This is a way to or"ani$e files when a project consists of multiple modules. %t also helps resolve namin" conflicts when different packa"es have classes with the same names. 1acka"es access level also allows you to protect data from bein" used by the non4authori$ed classes. 2&,. If a class is located in a ac+a'e4 what do you need to chan'e in the =. environ$ent to be able to use it? '. You need to add a directory or a jar file that contains the packa"e directories to the ,L'**1'T3 environment variable. Let#s say a class :mployee belon"s to a packa"e com.&y$.hrL and is located in the file cIPdevPcomP&y$PhrP:mployee.java. %n this case! you#d need to add cIPdev to the variable ,L'**1'T3. %f this class contains the method main()! you could test it from a command prompt window as followsI cIPOjava com.&y$.hr.:mployee 2&-. What2s the difference between J2.6I %., and J2.6I ,.&? '.There#s no difference! *un 0icrosystems just re4branded this version. 2&-. What would you use to co$ are two .trin' variables 5 the o erator 99 or the $ethod e3uals()? '. %#d use the method e-uals() to compare the values of the *trin"s and the DD to check if two variables point at the same instance of a *trin" object. 2&/. 6oes it $atter in what order catch state$ents for >ileHot>oundB(ce tion and I=B(ce ti on are written? '. Yes! it does. The )ile o)ound:&ception is inherited from the %9:&ception. :&ception#s subclasses have to be cau"ht first. 2&/. Can an inner class declared inside of a $ethod access local variables of this $ethod? %t#s possible if these variables are final. 2&!. What can 'o wron' if you re lace )) with ) in the followin' codeJ *trin" aDnullL if (a?Dnull (( a.len"th()O@A) Q...R ' sin"le ampersand here would lead to a ull1ointer:&ception. 2%&. When should the $ethod invo+eLater()be used? '. This method is used to ensure that *win" components are updated throu"h the event4dispatchin" thread. 2%%. 0ow can a subclass call a $ethod or a constructor defined in a su erclass? =se the followin" synta&I super.my0ethod()L To call a constructor of the superclass! just write super()L in the first line of the subclass#s constructor. 2%2. What2s the difference between a 3ueue and a stac+? '. *tacks works by last4in4first4out rule (L%)9)! while -ueues use the )%)9 rule 2%3. Kou can create an abstract class that contains only abstract $ethods. =n the other hand4 you can create an interface that declares the sa$e $ethods. .o can you use abstract classes instead of interfaces? '. *ometimes. But your class may be a descendent of another class and in this case the interface is your only option. 2%*. What co$es to $ind when you hear about a youn' 'eneration in Java? '. +arba"e collection. 2%,. What co$es to $ind when so$eone $entions a shallow co y in Java? '. 9bject clonin". 2%-. If you2re overridin' the $ethod e3uals() of an ob1ect4 which other $ethod you $i'ht also consider? '. hash,ode() 2%/. Kou are lannin' to do an inde(ed search in a list of ob1ects. Which of the two Java collections should you useJ 7rrayList or Lin+edList? '. 'rrayList 2%!. 0ow would you $a+e a co y of an entire Java ob1ect with its state? 3ave this class implement ,loneable interface and call its method clone(). 2%". 0ow can you $ini$i#e the need of 'arba'e collection and $a+e the $e$ory use $ore effective? '. =se object poolin" and weak object references. 22&. Ahere are two classesJ 7 and 8. Ahe class 8 need to infor$ a class 7 when so$e i$ ortant event has ha ened. What Java techni3ue would you use to i$ le$ent it? '. %f these classes are threads %#d consider notify() or notify'll(). )or re"ular classes you can use the 9bserver interface. 22%. What access level do you need to s ecify in the class declaration to ensure that only classes fro$ the sa$e directory can access it? '. You do not need to specify any access level! and .ava will use a default packa"e access level.

10

222. What is the diffrence between an Abstract class and Interface?


Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code. A class can implement any number of interfaces, but subclass at most one abstract class. An abstract class can have nonabstract methods. All methods of an interface are abstract. An abstract class can have instance variables. An interface cannot. An abstract class can define constructor. An interface cannot. An abstract class can have any visibility public, protected, private or none !package". An interface#s visibility must be public or none !package". An abstract class inherits from Ob$ect and includes methods such as clone!" and e%uals!". 223. What is a user defined exception? &ser'defined exceptions may be implemented by defining a class to respond to the exception and embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception !to another method where it is handled". The developer can define a new exception by deriving it from the (xception class as follows public class )y(xception extends (xception * /+ class definition of constructors !but ,OT the exception handling code" goes here +/ public )y(xception!" * super!". public )y(xception! /tring error)essage " * super! error)essage ".

The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax. throw new )y(xception!0I threw my own exception.0" To handle the exception within the method where it is thrown, a catch statement that handles )y(xception, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax public my)ethod,ame!" throws )y(xception 2. What are state ents in !A"A ? /tatements are e%uivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon Assignment expressions Any use of 11 or '' )ethod calls Ob$ect creation expressions These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements. #. What is !$I ? 2,I is an acronym of 2ava ,ative Interface. &sing 2,I we can call functions which are written in other languages from 2ava. 3ollowing are its advantages and disadvantages Advantages 4ou want to use your existing library which was previously written in other language. 4ou want to call 5indows A6I function. 3or the sake of execution speed. 4ou want to call A6I function of some server product which is in c or c11 from $ava client. Disadvantages: 4ou cant say write once run anywhere. 7ifficult to debug runtime error in native code. 6otential security risk. 4ou cant call it from Applet. %. What is seriali&ation ? 8uite simply, ob$ect seriali9ation provides a program the ability to read or write a whole ob$ect to and from a raw byte stream. It allows 2ava ob$ects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file'system, or more generally, to a transmission medium or storage facility. A

11

serali9able ob$ect must implement the /erili9able interface. 5e use Ob$ectOutput/tream to write this ob$ect to a stream and Ob$ectInput/tream to read it from the stream. '. Why there are so e null interface in (a)a ? What does it ean ? *i)e e so e null interfaces in !A"A? ,ull interfaces act as markers..they $ust tell the compiler that the ob$ects of this class need to be treated differently..some marker interfaces are /eriali9able, :emote, ;loneable What are checked and unchecked exceptions? ;hecked exceptions are the ones which you expect beforehand to be raised when an exceptional condition occurs and so write your code in a try'catch block to handle that sufficiently. 3or example Insuffucient<alance(xception which might be raised when money is being withdrawn from a bank account and the account has insufficient balance. ;hecked exceptions are sub classes of (xception. &nchecked exceptions are the ones which cannot be handled in the code. These are rather unexpected exceptions like ,ull6ointer(xception, OutOf)emory(rror, 7ivide<y=ero(xception, typically, programming errors. &nchecked exceptions are subclasses of :unTime(xceptions. +. Is synchronised a odifier?indentifier??what is it?? It#s a modifier. /ynchroni9ed methods are methods that are used to control access to an ob$ect. A thread only executes a synchroni9ed method after it has ac%uired the lock for the method#s ob$ect or class. /ynchroni9ed statements are similar to synchroni9ed methods. A synchroni9ed statement can only be executed after a thread has ac%uired the lock for the ob$ect or class referenced in the synchroni9ed statement. ,. What is singleton class?where is it used? /ingleton is a design pattern meant to provide one and only one instance of an ob$ect. Other ob$ects can get a reference to this instance through a static method !class constructor is kept private". 5hy do we need one> /ometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for 2ava, in garbage collection. )oreover, restricting the number of instances may be necessary or desirable for technological or business reasons''for example, we may only want a single instance of a pool of database connections. -. What is a co pilation unit? The smallest unit of source code that can be compiled, i.e. a .$ava file. 1.. Is string a wrapper class? /tring is a class, but not a wrapper class. 5rapper classes like !Integer" exist for each primitive type. They can be used to convert a primitive data value into an ob$ect, and vice'versa. 11. Why (a)a does not ha)e ultiple inheritance?

The 2ava design team strove to make 2ava /imple, ob$ect oriented, and familiar :obust and secure Architecture neutral and portable ?igh performance Interpreted, threaded, and dynamic

The reasons for omitting multiple inheritance from the 2ava language mostly stem from the 0simple, ob$ect oriented, and familiar0 goal. As a simple language, 2ava#s creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to ;11 as possible !familiar" without carrying over ;11#s unnecessary complexity !simple". In the designers# opinion, multiple inheritance causes more problems and confusion than it solves. /o they cut multiple inheritance from the language !$ust as they cut operator overloading". The designers# extensive ;11 experience taught them that multiple inheritance $ust wasn#t worth the headache. 12. What is a resource bundle? In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key. 1/. What is transient )ariable? Transient variable can#t be seriali9e. 3or example if a variable is declared as transient in a /eriali9able class and the class is written to an Ob$ect/tream, the value of the variable can#t be written to the stream instead when the class is retrieved from the Ob$ect/tream the value of the variable becomes null. 1#. What is 0ollection A1I? The ;ollection A6I is a set of classes and interfaces that support operation on collections of ob$ects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. (xample of classes HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. (xample of interfaces Collection, Set, List and Map.

12

1'. Is Iterator a 0lass or Interface? What is its use? Iterator is an interface which is used to step through the elements of a ;ollection. 1+. What is si ilarities/difference between an Abstract class and Interface? 7ifferences 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 ;lass may implement several interfaces. <ut in case of abstract class, a 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 classes are fast. /imilarities ,either Abstract classes or Interface can be instantiated. 1,. Which containers use a border 2ayout as their default layout? The window, 3rame and 7ialog classes use a border layout as their default layout. 1-. Why do threads block on I/O? Threads block on i/o !that is enters the waiting state" so that other threads may execute while the i/o Operation is performed. 21. What is synchroni&ation and why is it i portant? 5ith respect to multithreading, synchroni9ation is the capability to control the access of multiple threads to shared resources. 5ithout synchroni9ation, it is possible for one thread to modify a shared ob$ect while another thread is in the process of using or updating that ob$ect#s value. This often leads to significant errors. 22. 0an a lock be ac3uired on a class? 4es, a lock can be ac%uired on a class. This lock is ac%uired on the class#s ;lass ob$ect.. 2/. What4s new with the stop567 suspend56 and resu e56 ethods in !89 1.2? The stop!", suspend!" and resume!" methods have been deprecated in 27@ A.B. 2#. Is null a keyword? The null value is not a keyword. 2%. What is the preferred si&e of a co ponent? The preferred si9e of a component is the minimum component si9e that will allow the component to display normally. 2'. What ethod is used to specify a container4s layout? The setCayout!" method is used to specify a container#s layout. 2+. Which containers use a :low2ayout as their default layout? The 6anel and Applet classes use the 3lowCayout as their default layout. 2,. What state does a thread enter when it ter inates its processing? 5hen a thread terminates its processing, it enters the dead state. 2-. What is the 0ollections A1I? The ;ollections A6I is a set of classes and interfaces that support operations on collections of ob$ects. /.. Which characters ay be used as the second character of an identifier7 but not as the first character of an identifier? The digits D through E may not be used as the first character of an identifier but they may be used after the first character of an identifier. /1. What is the 2ist interface? The Cist interface provides support for ordered collections of ob$ects. /2. ;ow does !a)a handle integer o)erflows 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 "ector class? The Fector class provides the capability to implement a growable array of ob$ects /#. What odifiers ay be used with an inner class that is a e ber 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 ;ollection. /'. What is the difference between the << and <<< operators? The GG operator carries the sign bit when shifting right. The GGG 9ero'fills bits that have been shifted out. /+. Which ethod of the 0o ponent class is used to set the position and si&e of a co ponent? set<ounds!" /,. ;ow any bits are used to represent =nicode7 A>0II7 =?:@1'7 and =?:@, characters? &nicode re%uires AH bits and A/;II re%uire I bits. Although the A/;II character set uses only I bits, it is usually represented as J bits. &T3'J represents characters using J, AH, and AJ bit patterns. &T3'AH uses AH'bit and larger bit patterns. /-. What is the difference between yielding and sleeping? 5hen a task invokes its yield!" method, it returns to the ready state. 5hen a task invokes its sleep!" method, it returns to the waiting state.

13

#.. Which (a)a.util classes and interfaces support e)ent handling? The (ventOb$ect class and the (ventCistener interface support event processing. #1. Is si&eof a keyword? The si9eof operator is not a keyword. #2. What are wrapped classes? 5rapped classes are classes that allow primitive types to be accessed as ob$ects. #/. 8oes garbage collection guarantee that a progra will not run out of e ory? Karbage 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 ob$ects that are not sub$ect to garbage collection ##. What restrictions are placed on the location of a package state ent within a source code file? A package statement must appear as the first line in a source code file !excluding blank lines and comments". #%. 0an an ob(ect4s finali&e56 ethod be in)oked while it is reachable? An ob$ect#s finali9e!" method cannot be invoked by the garbage collector while the ob$ect is still reachable. ?owever, an ob$ect#s finali9e!" method may be invoked by other ob$ects. #+. What is the difference between pree pti)e scheduling and ti e slicing? &nder preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. &nder time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other actors. #-. What )alue does read2ine56 return when it has reached the end of a file? The readCine!" method returns null when it has reached the end of a file. %.. What is the i ediate superclass of the 8ialog class? Ans 5indow %1. What is clipping? Ans ;lipping is the process of confining paint operations to a limited area or shape. %2. What is a nati)e ethod? A native method is a method that is implemented in a language other than 2ava. %/. 0an a for state ent loop indefinitely? 4es, a for statement can loop indefinitely. 3or example, consider the following for!--" %#. What are order of precedence and associati)ity7 and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left'to'right or right'to'left %%. When a thread blocks on I/O7 what state does it enter? A thread enters the waiting state when it blocks on I/O. %'. ?o what )alue is a )ariable of the >tring type auto atically initiali&ed? The default value of an /tring type is null. %+. What is the catch or declare rule for ethod declarations? If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. %,. What is the difference between a AenuIte and a 0heckboxAenuIte ? The ;heckbox)enuItem class extends the )enuItem class to support a menu item that may be checked or unchecked. %-. What is a task4s priority and how is it used in scheduling? A task#s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. '.. What class is the top of the AW? e)ent hierarchy? The $ava.awt.A5T(vent class is the highest'level class in the A5T event'class hierarchy. '1. When a thread is created and started7 what is its initial state? A thread is in the ready state after it has been created and started. '2. 0an an anony ous class be declared as i ple enting an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. '/. What is the range of the short type? The range of the short type is '!BLAM" to BLAM ' A. '#. What is the range of the char type? The range of the char type is D to BLAH ' A. '%. In which package are ost of the AW? e)ents that support the e)ent@delegation odel defined? )ost of the A5T'related events of the event'delegation model are defined in the $ava.awt.event package. The A5T(vent class is defined in the $ava.awt package. ''. What is the i ediate superclass of Aenu? )enuItem '+. What is the purpose of finali&ation? The purpose of finali9ation is to give an unreachable ob$ect the opportunity to perform any cleanup processing before the ob$ect is garbage collected. ',. Which class is the i ediate superclass of the Aenu0o ponent class. Ob$ect '-. What in)okes a thread4s run56 ethod? After a thread is started, via its start!" method or that of the Thread class, the 2F) invokes the thread#s run!" method when the thread is initially executed. +.. What is the difference between the Boolean C operator and the CC operator? If an expression involving the <oolean N operator is evaluated, both operands are evaluated. Then the N operator is applied to the operand. 5hen an expression involving the NN operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The NN operator

14

is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. +2. What is the *regorian0alendar class? The Kregorian;alendar provides support for traditional 5estern calendars. +#. What is the purpose of the Dunti e class? The purpose of the :untime class is to provide access to the 2ava runtime system. +%. ;ow any ti es ay an ob(ect4s finali&e56 ethod be in)oked by the garbage collector? An ob$ect#s finali9e!" method may only be invoked once by the garbage collector. +'. What is the purpose of the finally clause of a try@catch@finally state ent? 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 argu ent type of a progra 4s ain56 ethod? A program#s main!" method takes an argument of the /tringOP type. +,. Which !a)a operator is right associati)e? The Q operator is right associative. +-. What is the 2ocale class? The Cocale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. ,.. 0an a double )alue be cast to a byte? 4es, a double value can be cast to a byte. ,1. What is the difference between a break state ent and a continue state ent? A break statement results in the termination of the statement to which it applies !switch,for, do, or while". A continue statement is used to end the current loop iteration and return control to the loop statement. ,2. What ust a class do to i ple ent an interface? It must provide all of the methods in the interface and identify the interface in its implements clause. ,/. What ethod is in)oked to cause an ob(ect to begin executing as a separate thread? The start!" method of the Thread class is invoked to cause an ob$ect to begin executing as a separate thread. ,#. $a e two subclasses of the ?ext0o ponent class. Text3ield and TextArea ,%. What is the ad)antage of the e)ent@delegation odel o)er the earlier e)ent inheritance odel? The event'delegation model has two advantages over the event'inheritance model. 3irst, it enables event handling to be handled by ob$ects 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. ,+. ;ow are co as used in the intiali&ation and iteration parts of a for state ent? ;ommas are used to separate multiple statements within the initiali9ation and iteration parts of a for statement. ,,. What is the purpose of the wait567 notify567 and notifyAll56 ethods? The wait!",notify!", and notifyAll!" methods are used to provide an efficient way for threads to wait for a shared resource. 5hen a thread executes an ob$ect#s wait!" method, it enters the waiting state. It only enters the ready state after another thread invokes the ob$ect#s notify!" or notifyAll!" methods.. -.. ;ow are !a)a source code files na ed? A 2ava source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take 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 take on a name that is different than its classes and interfaces. /ource code files use the .$ava extension. -1. What is the relationship between the 0an)as class and the *raphics class? A ;anvas ob$ect provides access to a Kraphics ob$ect via its paint!" method. -2. What are the high@le)el thread states? The high'level thread states are ready, running, waiting, and dead. -/. What )alue does read56 return when it has reached the end of a file? The read!" method returns 'A when it has reached the end of a file. -#. 0an a Byte ob(ect be cast to a double )alue? ,o, an ob$ect 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 ob$ect instances that are associated with instances of the class#s outer class. A static inner class does not have any ob$ect instances. -'. What is the difference between the >tring and >tringBuffer classes? /tring ob$ects are constants. /tring<uffer ob$ects are not. -+. If a )ariable is declared as pri)ate7 where ay the )ariable be accessed? A private variable may only be accessed within the class in which it is declared. -,. What is an ob(ect4s lock and which ob(ect4s ha)e locks? An ob$ect#s lock is a mechanism that is used by multiple threads to obtain synchroni9ed access to the ob$ect. A thread may execute a synchroni9ed method of an ob$ect only after it has ac%uired the ob$ect#s lock. All ob$ects and classes have locks. A class#s lock is ac%uired on the class#s ;lass ob$ect. --. What is the 8ictionary class? The 7ictionary class provides the capability to store key'value pairs. 1... ;ow are the ele ents of a Border2ayout organi&ed? The elements of a <orderCayout are organi9ed at the borders !,orth, /outh, (ast, and 5est" and the center of a

15

container. 1.1. What is the E operator? It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. 1.2. When can an ob(ect reference be cast to an interface reference? An ob$ect reference be cast to an interface reference when the ob$ect implements the referenced interface. 1./. What is the difference between a Window and a :ra e? The 3rame class extends 5indow to define a main application window that can have a menu bar. 1.#. Which class is extended by all other classes? The Ob$ect class is extended by all other classes. 1.%. 0an an ob(ect be garbage collected while it is still reachable? A reachable ob$ect cannot be garbage collected. Only unreachable ob$ects may be garbage collected.. 1.'. Is the ternary operator written x F y ? & or x ? y F & ? It is written x > y 9. 1.+. What is the difference between the :ont and :ontAetrics classes? The 3ont)etrics class is used to define implementation'specific properties, such as ascent and descent, of a 3ont ob$ect. 1.,. ;ow is rounding perfor ed under integer di)ision? The fractional part of the result is truncated. This is known as rounding toward 9ero. 1.-. What happens when a thread cannot ac3uire a lock on an ob(ect? If a thread attempts to execute a synchroni9ed method or synchroni9ed statement and is unable to ac%uire an ob$ect#s lock, it enters the waiting state until the lock becomes available. 11.. What is the difference between the Deader/Writer class hierarchy and the Input>trea /Output>trea class hierarchy? The :eader/5riter class hierarchy is character'oriented, and the Input/tream/Output/tream class hierarchy is byte'oriented. 111. What classes of exceptions ay be caught by 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. 112. If a class is declared without any access odifiers7 where ay the class be accessed? A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. 11/. What is the >i ple?i eGone class? The /impleTime=one class provides support for a Kregorian calendar. 11#. What is the Aap interface? The )ap interface replaces the 27@ A.A 7ictionary class and is used associate keys with values. 11%. 8oes a class inherit the constructors of its superclass? A class does not inherit constructors from any of its superclasses. 11'. :or which state ents does it ake sense to use a label? The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. 11+. What is the purpose of the >yste class? The purpose of the /ystem class is to provide access to system resources. 11,. Which ?ext0o ponent ethod is used to set a ?ext0o ponent to the read@only state? set(ditable!" 11,. ;ow are the ele ents of a 0ard2ayout organi&ed? The elements of a ;ardCayout are stacked, one on top of the other, like a deck of cards. 11-. Is CCH a )alid !a)a operator? ,o, it is not. 12.. $a e the eight pri iti)e !a)a types. The eight primitive types are byte, char, short, int, long, float, double, and boolean. 121. Which class should you use to obtain design infor ation about an ob(ect? The ;lass class is used to obtain information about an ob$ect#s design. 121. What is the relationship between clipping and repainting? 5hen a window is repainted by the A5T painting thread, it sets the clipping regions to the area of the window that re%uires repainting. 122. Is IabcI a pri iti)e )alue? The /tring literal 0abc0 is not a primitive value. It is a /tring ob$ect. 12/. What is the relationship between an e)ent@listener interface and an e)ent@adapter class? An event'listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event'listener interface. 12#. What restrictions are placed on the )alues of each case of a switch state ent? 7uring compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. 12%. What odifiers ay be used with an interface declaration? An interface may be declared as public or abstract. 12'. Is a class a subclass of itself? A class is a subclass of itself. 12+. What is the highest@le)el e)ent class of the e)ent@delegation odel?

16

The $ava.util.(ventOb$ect class is the highest'level class in the event'delegation class hierarchy. 12,. What e)ent results fro the clicking of a button? The Action(vent event is generated as the result of the clicking of a button. 12-. ;ow can a *=I co ponent handle its own e)ents? A component can handle its own events by implementing the re%uired event'listener interface and adding itself as its own event listener. 1/.. What is the difference between a while state ent and a do state ent? A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once. 1/1. ;ow are the ele ents of a *ridBag2ayout organi&ed? The elements of a Krid<agCayout 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. 1/2. What ad)antage do !a)a4s layout anagers pro)ide o)er traditional windowing syste s? 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 accomodate platform' specific differences among windowing systems. 1//. What is the 0ollection interface? The ;ollection interface provides support for the implementation of a mathematical bag ' an unordered collection of ob$ects that may contain duplicates. 1/#. What odifiers can be used with a local inner class? A local inner class may be final or abstract. 1/%. What is the difference between static and non@static )ariables? A static variable is associated with the class as a whole rather than with specific instances of a class. ,on'static variables take on uni%ue values with each ob$ect instance. 1/'. What is the difference between the paint56 and repaint56 ethods? The paint!" method supports painting via a Kraphics ob$ect. The repaint!" method is used to cause paint!" to be invoked by the A5T painting thread. 1/+. What is the purpose of the :ile class? The 3ile class is used to create ob$ects that provide access to the files and directories of a local file system. 1/,. 0an an exception be rethrown? 4es, an exception can be rethrown. 1/-. Which Aath ethod is used to calculate the absolute )alue of a nu The abs!" method is used to calculate absolute values. ber?

1#.. ;ow does ultithreading take place on a co puter with a single 01=? The operating system#s task scheduler allocates execution time to multiple tasks. <y %uickly switching between executing tasks, it creates the impression that tasks execute se%uentially. 1#1. When does the co piler supply a default constructor for a class? The compiler supplies a default constructor for a class if no other constructors are provided. 1#2. When is the finally clause of a try@catch@finally state ent executed? 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. 1#/. Which class is the i ediate superclass of the 0ontainer class? Ans ;omponent

1##. If a ethod is declared as protected7 where ay the ethod be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared. 1#%. ;ow can the 0heckbox class be used to create a radio button? <y associating ;heckbox ob$ects with a ;heckboxKroup. 1#'. Which non@=nicode letter characters ay be used as the first character of an identifier? The non'&nicode letter characters R and S may appear as the first character of an identifier 1#+. What restrictions are placed on ethod o)erloading? Two methods may not have the same name and argument list but different return types. 1#,. What happens when you in)oke a thread4s interrupt ethod while it is sleeping or waiting? 5hen a task#s interrupt!" method is executed, the task enters the ready state. The next time the task enters the running state, an Interrupted(xception is thrown.

17

1#-. What is casting? There are two types of casting, casting between primitive numeric types and casting between ob$ect references. ;asting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. ;asting between ob$ect references is used to refer to an ob$ect by a compatible class, interface, or array type reference. 1%.. What is the return type of a progra 4s ain56 A program#s main!" method has a void return type. 1%1. $a e four 0ontainer classes. /croll6ane Ans ethod? 5indow, 3rame, 7ialog, 3ile7ialog, 6anel, Applet, or

1%2. What is the difference between a 0hoice and a 2ist? A ;hoice is displayed in a compact form that re%uires you to pull it down to see the list of available choices. Only one item may be selected from a ;hoice. A Cist may be displayed in such a way that several Cist items are visible. A Cist supports the selection of one or more Cist items. 1%/. What class of exceptions are generated by the !a)a run@ti e syste The 2ava runtime system generates :untime(xception and (rror exceptions. 1%#. What class allows you to read ob(ects directly fro a strea ? The Ob$ectInput/tream class supports the reading of ob$ects from input streams. 1%%. What is the difference between a field )ariable and a local )ariable? 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. 1%'. =nder what conditions is an ob(ect4s finali&e56 ethod in)oked by the garbage collector? The garbage collector invokes an ob$ect#s finali9e!" method when it detects that the ob$ect has become unreachable. 1%+. ;ow are this56 and super56 used with constructors? this!" is used to invoke a constructor of the same class. super!" is used to invoke a superclass constructor. 1%,. What is the relationship between a ethod4s throws clause and the exceptions that can be thrown during the ethod4s execution? A method#s throws clause must declare any checked exceptions that are not caught within the body of the method. 1%-. What is the difference between the !89 1..2 e)ent odel and the e)ent@delegation odel introduced with !89 1.1? The 27@ A.DB 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 ob$ects are designated as event handlers for K&I components. These ob$ects 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. ATH. ?ow is it possible for two /tring ob$ects with identical values not to be e%ual under the QQ operator> The QQ operator compares two ob$ects to determine if they are the same ob$ect in memory. It is possible for two /tring ob$ects to have the same value, but located indifferent areas of memory. 1'.. Why are the ethods of the Aath class static? /o they can be invoked as if they are a mathematical code library. 1'1. What 0heckbox ethod allows you to tell if a 0heckbox is checked? Ans get/tate!" ?

1'2. What state is a thread in when it is executing? state.

An executing thread is in the running

1'/. What are the legal operands of the instanceof operator? The left operand is an ob$ect reference or null value and the right operand is a class, interface, or array type. 1'#. ;ow are the ele ents of a *rid2ayout organi&ed? The elements of a Krid<ad layout are of e%ual si9e and are laid out using the s%uares of a grid. 1'%. What an I/O filter? An I/O filter is an ob$ect 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.

18

1''. If an ob(ect is garbage collected7 can it beco e reachable again? Once an ob$ect is garbage collected, it ceases to exist. It can no longer become reachable again. 1'+. 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. 1',. What classes of exceptions ay be thrown by a throw state ent? A throw statement may throw any expression that may be assigned to the Throwable type. 1',. What are J and 1I? ( is the base of the natural logarithm and 6I is mathematical value pi. 1+.. Are true and false keywords? Ans The values true and false are not keywords.

1+1. What is a )oid return type? A void return type indicates that a method does not return a value. 1+2. What is the purpose of the enableJ)ents56 ethod? The enable(vents!" method is used to enable an event for a particular ob$ect. ,ormally, an event is enabled when a listener is added to an ob$ect for a particular event. The enable(vents!" method is used by ob$ects that handle events by overriding their eventdispatch methods. 1+/. What is the difference between the :ile and Dando Access:ile classes? The 3ile class encapsulates the files and directories of the local file system. The :andomAccess3ile class provides the methods needed to directly access data contained in any part of a file. 1+#. What happens when you add a double )alue to a >tring? The result is a /tring ob$ect. 1+%. What is your platfor 4s default character encoding? If you are running 2ava on (nglish 5indows platforms, it is probably ;pABMB. If you are running 2ava on (nglish /olaris platforms, it is most likely JJMESA.. 1+'. Which package is always i ported by default? The $ava.lang package is always imported by default. 1++. What interface ust an ob(ect i ple ent before it can be written to a strea as an ob(ect? An ob$ect must implement the /eriali9able or (xternali9able interface before it can be written to a stream as an ob$ect. 1+,. ;ow are this and super used? this is used to refer to the current ob$ect instance. super is used to refer to the variables and methods of the superclass of the current ob$ect instance. 1+-. What is the purpose of garbage collection? The purpose of garbage collection is to identify and discard ob$ects that are no longer needed by a program so that their resources may be reclaimed and reused. 1,.. What is a co pilation unit? A compilation unit is a 2ava source code file. 1,1. What interface is extended by AW? e)ent listeners? All A5T event listeners extend the $ava.util.(ventCistener interface. 1,2. What restrictions are placed on ethod o)erriding? Overridden 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. 1,/. ;ow can a dead thread be restarted? A dead thread cannot be restarted. 1,#. What happens if an exception is not caught? An uncaught exception results in the uncaught(xception!" method of the thread#s ThreadKroup being invoked, which eventually results in the termination of the program in which it is thrown. 1,%. What is a layout anager? A layout manager is an ob$ect that is used to organi9e components in a container.

19

1,'. Which arith etic operations can result in the throwing of an Arith Integer / and U can result in the throwing of an Arithmetic(xception.

eticJxception?

1,+. What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep!" method, by blocking on I/O, by unsuccessfully attempting to ac%uire an ob$ect#s lock, or by invoking an ob$ect#s wait!" method. It can also enter the waiting state by invoking its !deprecated" suspend!" method. 1,,. 0an an abstract class be final? An abstract class may not be declared as final.

1,-. What is the DesourceBundle class? The :esource<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. 1-.. What happens if a try@catch@finally state ent does not ha)e a catch clause to handle an exception that is thrown within the body of the try state ent? The exception propagates up to the next higher level try'catch statement !if any" or results in the program#s termination. 1-1. What is nu eric pro otion? ,umeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating'point operations may take 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. 1-2. What is the difference between a >crollbar and a >croll1ane? A /crollbar is a ;omponent, but not a ;ontainer. A /croll6ane is a ;ontainer. A /croll6ane handles its own events and performs its own scrolling. 1-/. What is the difference between a public and a non@public class? A public class may be accessed outside of its package. A non'public class may not be accessed outside of its package. 1-#. ?o what )alue is a )ariable of the boolean type auto The default value of the boolean type is false. 1-%. 0an try state ents be nested? atically initiali&ed?

Try statements may be tested.

1-'. What is the difference between the prefix and postfix for s of the KK 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. 1-+. What is the purpose of a state ent block? A statement block is used to organi9e a se%uence of statements as a single statement group. 1-,. What is a !a)a package and how is it used? A 2ava package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. 6ackages are also used to organi9e related classes and interfaces into a single A6I unit and to control accessibility to these classes and interfaces. AJH. 5hat modifiers may be used with a top'level class> A top'level class may be public, abstract, or final. 1--. What are the Ob(ect and 0lass classes used for? The Ob$ect class is the highest'level class in the 2ava class hierarchy. The ;lass class is used to represent the classes and interfaces that are loaded by a 2ava program.. 2... ;ow does a try state ent deter ine which catch clause should be used to handle an exception? 5hen an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored. 2.1. 0an an unreachable ob(ect beco e reachable again? An unreachable ob$ect may become reachable again. This can happen when the ob$ect#s finali9e!" method is invoked and the ob$ect performs an operation which causes it to become accessible to reachable ob$ects. 2.2. When is an ob(ect sub(ect to garbage collection? An ob$ect is sub$ect to garbage collection when it becomes unreachable to the program in which it is used. 2./. What ethod ust be i ple ented by all threads? All tasks must implement the run!" method, whether they are a subclass of Thread or implement the :unnable

20

interface. 2.#. What ethods are used to get and set the text label displayed by a Button ob(ect? Ans getCabel!" and setCabel!" 2.%. Which 0o ponent subclass is used for drawing and painting? Ans ;anvas

2.'. What are synchroni&ed ethods and synchroni&ed state ents? /ynchroni9ed methods are methods that are used to control access to an ob$ect. A thread only executes a synchroni9ed method after it has ac%uired the lock for the method#s ob$ect or class. /ynchroni9ed statements are similar to synchroni9ed methods. A synchroni9ed statement can only be executed after a thread has ac%uired the lock for the ob$ect or class referenced in the synchroni9ed statement. 2.+. What are the two basic ways in which classes that can be run as threads ay be defined? A thread class may be declared as a subclass of Thread, or it may implement the :unnable interface. 2.,. What are the proble s faced by !a)a progra ers who don4t use layout anagers? 5ithout layout managers, 2ava programmers are faced with determining how their K&I will be displayed across multiple windowing systems and finding a common si9ing and positioning that will work within the constraints imposed by each windowing system. 2.-. What is the difference between an if state ent and a switch state ent? The if statement is used to select among two alternatives. It uses a boolean 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. 21.. What happens when you add a double )alue to a >tring? The result is a /tring ob$ect. 211. What is the 2ist interface? The Cist interface provides support for ordered collections of ob$ects. 212. What do you know about the garbage collector? Karbage collector is a runtime component of 2ava which sits on top of the heap memory area from which 2ava ob$ects are created and periodically scans it for ob$ects which are eligible to be reclaimed when there are no references to these ob$ects in the program. There is simply no way to force garbage collection, but you can suggest your intention of getting the ob$ect garbage collecetd to 2ava Firtual )achine by calling /ystem.gc!" 21/. *arbage collection thread belongs to which priority.. in?nor The 2ava garbage collection is implemented as a low priority thread al? ax?

21#. Jxplain garbage collection? Karbage collection is one of the most important feature of 2ava. Karbage collection is also called automatic memory management as 2F) automatically removes the unused variables/ob$ects !value is null" from the memory. &ser program cann#t directly free the ob$ect from memory, instead it is the $ob of the garbage collector to automatically free the ob$ects that are no longer referenced by a program. (very class inherits finali9e!" method from $ava.lang.Ob$ect, the finali9e!" method is called by garbage collector when it determines no more references to the ob$ect 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 :untime.gc!", 2F) tries to recycle the unused ob$ects, but there is no guarantee when all the ob$ects will garbage collected. 21'. ;ow you can force the garbage collection? Karbage collection automatic process and can#t be forced. 21+. If an ob(ect is garbage collected7 can it beco e reachable again? Once an ob$ect is garbage collected, it ceases to exist. It can no longer become reachable again. 21,. 8oes garbage collection guarantee that a progra will not run out of e ory? Karbage 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 ob$ects that are not sub$ect to garbage collection 21-. 0an an ob(ectLMNs finali&e56 ethod be in)oked while it is reachable? An ob$ectVWXs finali9e!" method cannot be invoked by the garbage collector while the ob$ect is still reachable. ?owever, an ob$ectVWXs finali9e!" method may be invoked by other ob$ects. 22.. What is the purpose of garbage collection? The purpose of garbage collection is to identify and discard ob$ects that are no longer needed by a program so that their resources may be reclaimed and reused. 221. 8escribe what happens when an ob(ect is created in !a)a?

21

/everal things happen in a particular order to ensure the ob$ect is constructed properly )emory is allocated from heap to hold all instance variables and implementation'specific data of the ob$ect and its superclasses. Implemenation'specific data includes pointers to class and method data. The instance variables of the ob$ects are initiali9ed to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for $ava.lang.Ob$ect is called, as $ava.lang.Ob$ect is the base class for all ob$ects in $ava. <efore the body of the constructor is executed, all instance variable initiali9ers and initiali9ation blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

%LClass ?ariables (.tatic ?ariable) When a number of objects are created from the same class blueprint! they each have their own distinct copies of instance variables. %n the case of the Bicycle class! the instance variables are cadence! "ear! and speed. :ach Bicycle object has its own values for these variables! stored in different memory locations. *ometimes! you want to have variables that are common to all objects. This is accomplished with the static modifier. )ields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class! rather than with any object. :very instance of the class shares a class variable! which is in one fi&ed location in memory. 'ny object can chan"e the value of a class variable! but class variables can also be manipulated without creatin" an instance of the class. )or e&ample! suppose you want to create a number of Bicycle objects and assi"n each a serial number! be"innin" with @ for the first object. This %2 number is uni-ue to each object and is therefore an instance variable. 't the same time! you need a field to keep track of how many Bicycle objects have been created so that you know what %2 to assi"n to the ne&t one. *uch a field is not related to any individual object! but to the class as a whole. )or this you need a class variable! number9fBicycles! as followsI public class Bicycle{ private int cadence; private int gear; private int speed; // add an instance variable for the object ID private int id; // add a class variable for the number of Bicycle objects instantiated private static int nu ber!"Bicycles # $; ...... % ,lass variables are referenced by the class name itself! as in

Bicycle.nu ber!"Bicycles yBike.nu ber!"Bicycles

This makes it clear that they are class variables. oteI You can also refer to static fields with an object reference like but this is discoura"ed because it does not make it clear that they are class variables. You can use the Bicycle constructor to set the id instance variable and increment the number9fBicycles class variableI public class Bicycle{ private int cadence; private int gear; private int speed; private int id; private static int nu ber!"Bicycles # $; public Bicycle&int startCadence' int startSpeed' int start(ear){ gear # start(ear; cadence # startCadence; speed # startSpeed; // increment number of Bicycles and assign ID number id = ++numberOfBicycles; % // new method to return the ID instance variable public int get*+&) { return id; % ..... % 2L Class @ethods

22

The .ava pro"rammin" lan"ua"e supports static methods as well as static variables. *tatic methods! which have the static modifier in their declarations! should be invoked with the class name! without the need for creatin" an instance of the class! as in Class,a e. ethod,a e&args) oteI You can also refer to static methods with an object reference like instance,a e. ethod,a e&args) but this is discoura"ed because it does not make it clear that they are class methods. ' common use for static methods is to access static fields. )or e&ample! we could add a static method to the Bicycle class to access the number9fBicycles static fieldI public static int get,u ber!"Bicycles&) { return nu ber!"Bicycles; % ot all combinations of instance and class variables and methods are allowedI

%nstance methods can access instance variables and instance methods directly. %nstance methods can access class variables and class methods directly. ,lass methods can access class variables and class methods directly.

,lass methods cannot access instance variables or instance methods directlythey must use an object reference. 'lso! class methods cannot use the this keyword as there is no instance for this to refer to. @ethod =verridin' 0ethod overridin" occurs when a class declares a method that has the same type si"nature as a method declared by one of its superclasses. >ecall that a type si"nature is a combination of a method name and the se-uence of its parameter types. When a method in a subclass overrides a method in a superclass! the method in the superclass is hidden relative to the subclass object. 0ethod overridin" is a very important capability because it forms the basis for run5ti$e oly$or his$. >ecall that polymorphism means one interface! multiple implementations. The si"nature of the method defines the interface! and each overridden version provides a uni-ue implementation. 's e&plained! a superclass reference can be used to refer to a subclass object. Ahe dyna$ic $ethod dis atch $echanis$ in .ava selects the appropriate version of an overridden method to e&ecute based on the class of the e&ecutin" object! not the type of a variable that references that object. Thus! the actual version of an overridden method that is e&ecuted is determined at run4time! not compile time. The .ava compiler issues an error messa"e if a method overrides another method but has a different return type.

23

Aodifier public protected 0lasses ,lass is publicly accessible (the class can be used by any other class) ,lasses can be declared with security so they can be accessed outside their packa"e by usin" the public statement in the class declaration. %f no e&plicit statement is made at declaration time! the class may be accessed only from within its own packa"e. A compile error is generated if any other security modifier is used in the declaration, such as private or protected, which are reserved for methods. Aethod 0ethod is publicly accessible

:unction "ariables /ariables are publicly accessible *ame as methods 0onstructor 'ny class can use this constructor. *ubclasses of this class and classes in the same packa"e can use this constructor.

,lass members are accessible only to methods in that class and subclasses of that class. This means that protected class members have visibility limited to subclasses

+e"ault&no odi"ier)

9nly classes in the same packa"e can have access to a classs variables and methods

*ame as methods

%f no access specifier is provided! the constructor has the default access (sometimes called packa"e private). 9nly classes within the same packa"e as this class can use this constructor. 9nly this class can use this constructor. 0akin" a constructor private! in essence! makes the class final the class can#t be subclassed! e&cept from within. %f all constructors within a class are private! the class mi"ht contain public class methods (called factory methods) that create and initiali$e an instance of this class. 9ther classes can use the factory methods to create an instance of this class.

private

9nly inner classes can be rivate

,lass members are only accessible by the class they are defined in. This means that no other class has access to private class members! even subclasses

*ame as methods

static

-inal

abstract

synchroni.ed

The static keyword can be used for inner classes! but can not LThe static modifier specifies that a variable or method is the same for all objects of a be used to re"ular classes. The static modifier is only applicable to particular class. Typically! new variables are allocated for each instance of a class. When a variable is declared as bein" static! it is only allocated once re"ardless of how many objects so4called member classes are instantiated. The result is that all instantiated objects share the same instance of the static variable. *imilarly! a static method is one whose implementation is e&actly the same for all objects of a particular class. This means that static methods only have access to static variables 2eclares this is a %Lclass variable rather than an instance variable. You also use static to declare 2Lclass methods. The class cannot be subclassed ' variable has a constant value or that a method cannot be overridden in a subclass. ' class member is the final version allowed for the class %ndicates that the value of this member cannot chan"e. ' compile4time constant is defined by usin" static and final to"ether ,lass cannot be instantiatedL 'n abstract method has no implementation and must 'n abstract class can only be subclassed. be a member of an abstract class 'n abstract class can contain abstract methods. & %n practice! abstract classes usually provide a complete or partial implementation of at least one method The synchroni$ed modifier is used to specify that a The class can not be synchroni.ed. method is thread safe /e can create synchroni.ed block & The native modifier is used to identify methods that have native implementations. The native modifier informs the .ava compiler that a methods implementation is in an e&ternal , file S S & 0arks member variables that should not be seriali$ed. This component is used in object seriali$ation 1revents the compiler from performin" certain optimi$ations on a member.

&

&

&

native

&

transient volatile

& &

& &

24

static +eyword Controllin' 7ccess to @e$bers of a Class %n order to understand the use of the static keyword in class declaration! we need to understand the class declaration itself. You can declare two kinds of
7ccess Levels . ecifier Class Dac+a'e .ubclass World classesI top4level classes and inner classes. Ao 5level classes You declare a top4level class at the top level as a member of a packa"e. :ach top4level class corresponds to its own java file sportin" the same name as the class name. ' top4level class is by definition already top4level! so there is no point in declarin" it staticL it is an error to do so. The compiler will detect and report this error. Inner classes You define an inner class within a top4level class. 2ependin" on how it is defined! an inner class can be one of the followin" four typesI %. 7nony$ous. 'nonymous classes are declared and instantiated within the same statement. They do not have names! and they can be instantiated only once. The followin" is an e&ample of an anonymous classI

private no specifier protected public

4 4 4 4

, 4 4 4

, , 4 4

, , , 4

okButton.addActionListener& ne0 ActionListener&){ public void action1er"or ed&Action2vent e){ dispose&); % %);
Because an anonymous class doesn#t have a normal class declaration where it#s possible to use static! it cannot be declared static. 2. Local. Local classes are the same as local variables! in the sense that they#re created and used inside a block. 9nce you declare a class within a block! it can be instantiated as many times as you wish within that block. Like local variables! local classes aren#t allowed to be declared public! protected! private! or static. 3. @e$ber. 0ember classes are defined within the body of a class. You can use member classes anywhere within the body of the containin" class. You declare member classes when you want to use variables and methods of the containin" class without e&plicit dele"ation. The member class is the only class that you can declare static. When you declare a member class! you can instantiate that member class only within the conte&t of an object of the outer class in which this member class is declared. %f you want to remove this restriction! you declare the member class a static class. When you declare a member class with a static modifier! it becomes a nested top4level class and can be used as a normal top4level class as e&plained above. 6. Hested to 5level. ' nested top4level class is a member classes with a static modifier. ' nested top4level class is just like any other top4level class e&cept that it is declared within another class or interface. ested top4level classes are typically used as a convenient way to "roup related classes without creatin" a new packa"e. %f your main class has a few smaller helper classes that can be used outside the class and make sense only with your main class! it#s a "ood idea to make them nested top4level classes.

25

Anda mungkin juga menyukai