Anda di halaman 1dari 19

1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence?

Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux, olaris,etc). 3. What is a JVM? J!" is Java !irtual "achine which is a run time environment for the compiled java class files. 4. Are JVM s platform independent? J!"#s are not platform independent. J!"#s are platform specific run time implementation provided $y the vendor. !. What is the difference bet"een a J#$ and a JVM? J%& is Java %evelopment &it which is for development purpose and it includes execution environment also. 'ut J!" is purely a run time environment and hence you will not $e a$le to compile your source files using a J!". %. What is a pointer and does Java support pointers? Pointer is a reference handle to a memory location. (mproper handling of pointers leads to memory lea)s and relia$ility issues hence Java doesn#t support the usage of pointers. &. What is the base class of all classes?

java.lang.Object
'. #oes Java support multiple inheritance? Java doesn#t support multiple inheritance. (. )s Java a pure ob*ect oriented lan+ua+e? Java uses primitive data types and hence is not a pure o$ject oriented language. 1,. Are arrays primitive data types? (n Java, *rrays are o$jects. 11. What is difference bet"een -ath and .lasspath? Path and +lasspath are operating system level environment variales. Path is used define where the system can find the executa$les(.exe) files and classpath is used to specify the location .class files. 12. What are local variables? Local varaia$les are those which are declared within a $loc) of code li)e methods. Local varia$les should $e initialised $efore accessing them. 13. What are instance variables? (nstance varia$les are those which are defined at the class level. (nstance varia$les need not $e initiali,ed $efore using them as they are automatically initiali,ed to their default values. 14. /o" to define a constant variable in Java? -he varia$le should $e declared as static and final. o only one copy of the varia$le exists for all instances of the class and the value can#t $e changed also. static final int PI = 2.14; is an example for constant. 1!. 0hould a main12 method be compulsorily declared in all *ava classes? .o not re/uired. main() method should $e defined only if the source class is a java application. 1%. What is the return type of the main12 method?

Main() method doesn#t return anything hence declared void.


1&. Why is the main12 method declared static?

main() method is called $y the J!" even $efore the instantiation of the class hence it is declared as static.
1'. What is the ar+uement of main12 method?

main() method accepts an array of tring o$ject as arguement.


1(. .an a main12 method be overloaded? 0es. 0ou can have any num$er of main() methods with different method signature and implementation in the class. 2,. .an a main12 method be declared final? 0es. *ny inheriting class will not $e a$le to have it#s own default main() method. 21. #oes the order of public and static declaration matter in main12 method? .o. (t doesn#t matter $ut void should always come $efore main(). 22. .an a source file contain more than one class declaration? 0es a single source file can contain any num$er of +lass declarations $ut only one of the class can $e declared aspublic. 23. What is a pac3a+e? Pac)age is a collection of related classes and interfaces. pac)age declaration should $e first statement in a java class. 24. Which pac3a+e is imported by default?

java.lang pac age is imported $y default even without a pac)age declaration.


2!. .an a class declared as private be accessed outside it s pac3a+e? .ot possi$le. 2%. .an a class be declared as protected? * class can#t $e declared as p!otected. only methods can $e declared as p!otected. 2&. What is the access scope of a protected method? * p!otected method can $e accessed $y the classes within the same pac)age or $y the su$classes of the class in any pac)age. 2'. What is the purpose of declarin+ a variable as final? * final varia$le#s value can#t $e changed. final varia$les should $e initiali,ed $efore using them. 2(. What is the impact of declarin+ a method as final? * method declared as final can#t $e overridden. * su$1class can#t have the same method signature with a different implementation. 3,. ) don t "ant my class to be inherited by any other class. What should i do? 0ou should declared your class as final. 'ut you can#t define your class as final, if it is an abst!act class. * class declared as final can#t $e extended $y any other class. 31. .an you +ive fe" e4amples of final classes defined in Java A-)?

java.lang."t!ing# java.lang.Mat$ are final classes.


32. /o" is final different from finally and finali5e12?

final is a modifier which can $e applied to a class or a method or a varia$le. final class can#t $e inherited, finalmethod can#t $e overridden and final varia$le can#t $e changed.
finally is an exception handling code section which gets executed whether an exception is raised or not $y the try $loc) code segment.

finali%e() is a method of 2$ject class which will $e executed $y the J!" just $efore gar$age collecting
o$ject to give a final chance for resource releasing activity. 33. .an a class be declared as static? .o a class cannot $e defined as static. 2nly a method, a varia$le or a $loc) of code can $e declared as static. 34. When "ill you define a method as static? When a method needs to $e accessed even $efore the creation of the o$ject of the class then we should declare the method as static. 3!. What are the restriction imposed on a static method or a static bloc3 of code? * static method should not refer to instance varia$les without creating an instance and cannot use 3this3 operator to refer the instance. 3%. ) "ant to print 6/ello6 even before main12 is e4ecuted. /o" "ill you acheive that? Print the statement inside a static $loc) of code. tatic $loc)s get executed when the class gets loaded into the memory and even $efore the creation of an o$ject. 4ence it will $e executed $efore the main() method. *nd it will $e executed only once. 3&. What is the importance of static variable? static varia$les are class level varia$les where all o$jects of the class refer to the same varia$le. (f one o$ject changes the value then the change gets reflected in all the o$jects. 3'. .an "e declare a static variable inside a method? tatic varai$les are class level varia$les and they can#t $e declared inside a method. (f declared, the class will not compile. 3(. What is an Abstract .lass and "hat is it s purpose? * +lass which doesn#t provide complete implementation is defined as an a$stract class. *$stract classes enforce a$straction. 4,. .an a abstract class be declared final? .ot possi$le. *n a$stract class without $eing inherited is of no use and hence will result in compile time error. 41. What is use of a abstract variable? !aria$les can#t $e declared as a$stract. only classes and methods can $e declared as abst!act. 42. .an you create an ob*ect of an abstract class? .ot possi$le. *$stract classes can#t $e instantiated. 43. .an a abstract class be defined "ithout any abstract methods? 0es it#s possi$le. -his is $asically to avoid instance creation of the class. 44. .lass . implements )nterface ) containin+ method m1 and m2 declarations. .lass . has provided implementation for method m2. .an i create an ob*ect of .lass .? .o not possi$le. &lass & should provide implementation for all the methods in the Inte!face I. ince &lass &didn#t provide implementation for m1 method, it has to $e declared as abst!act. *$stract classes can#t $e instantiated.

4!. .an a method inside a )nterface be declared as final? .o not possi$le. %oing so will result in compilation error. public and abst!act are the only applica$le modifiers for method declaration in an inte!face. 4%. .an an )nterface implement another )nterface? (ntefaces doesn#t provide implementation hence a interface cannot implement another interface. 4&. .an an )nterface e4tend another )nterface? 0es an (nterface can inherit another (nterface, for that matter an (nterface can extend more than one (nterface. 4'. .an a .lass e4tend more than one .lass? .ot possi$le. * +lass can extend only one class $ut can implement any num$er of (nterfaces. 4(. Why is an )nterface be able to e4tend more than one )nterface but a .lass can t e4tend more than one .lass? 'asically Java doesn#t allow multiple inheritance, so a +lass is restricted to extend only one +lass. 'ut an (nterface is a pure a$straction model and doesn#t have inheritance hierarchy li)e classes(do remem$er that the $ase class of all classes is 2$ject). o an (nterface is allowed to extend more than one (nterface. !,. .an an )nterface be final? .ot possi$le. %oing so so will result in compilation error. !1. .an a class be defined inside an )nterface? 0es it#s possi$le. !2. .an an )nterface be defined inside a class? 0es it#s possi$le. !3. What is a Mar3er )nterface? *n (nterface which doesn#t have any declaration inside $ut still enforces a mechanism. !4. Which ob*ect oriented .oncept is achieved by usin+ overloadin+ and overridin+? Polymorphism. !!. Why does Java not support operator overloadin+? 2perator overloading ma)es the code very difficult to read and maintain. -o maintain code simplicity, Java doesn#t support operator overloading. !%. .an "e define private and protected modifiers for variables in interfaces? .o. !&. What is 74ternali5able? 5xternali,a$le is an (nterface that extends eriali,a$le (nterface. *nd sends data into +ompressed 6ormat. (t has two methods, '!ite()te!nal(ObjectOuput out) and !ead()te!nal(ObjectInput in) !'. What modifiers are allo"ed for methods in an )nterface? 2nly public and abst!act modifiers are allowed for methods in interfaces. !(. What is a local8 member and a class variable? !aria$les declared within a method are 3local3 varia$les. !aria$les declared within the class i.e not within any methods are 3mem$er3 varia$les (glo$al varia$les). !aria$les declared within the class i.e not within any methods and are defined as 3static3 are class varia$les. %,. What is an abstract method? treams in

*n a$stract method is a method whose implementation is deferred to a su$class. %1. What value does read12 return "hen it has reached the end of a file? -he !ead() method returns *1 when it has reached the end of a file. %2. .an a 9yte ob*ect be cast to a double value? .o, an o$ject cannot $e cast to a primitive value. %3. What is the difference bet"een a static and a non:static inner class? * non1static inner class may have o$ject instances that are associated with instances of the class#s outer class. * static inner class does not have any o$ject instances. %4. What is an ob*ect s loc3 and "hich ob*ect s have loc3s? *n o$ject#s loc) is a mechanism that is used $y multiple threads to o$tain synchroni,ed access to the o$ject. * thread may execute a synchroni,ed method of an o$ject only after it has ac/uired the o$ject#s loc). *ll o$jects and classes have loc)s. * class#s loc) is ac/uired on the class#s +lass o$ject. %!. What is the ; operator? (t is referred to as the modulo or remainder operator. (t returns the remainder of dividing the first operand $y the second operand. %%. When can an ob*ect reference be cast to an interface reference? *n o$ject reference $e cast to an interface reference when the o$ject implements the referenced interface. %&. Which class is e4tended by all other classes? -he 2$ject class is extended $y all other classes. %'. Which non:<nicode letter characters may be used as the first character of an identifier? -he non17nicode letter characters + and , may appear as the first character of an identifier %(. What restrictions are placed on method overloadin+? -wo methods may not have the same name and argument list $ut different return types. &,. What is castin+? -here are two types of casting, casting $etween primitive numeric types and casting $etween o$ject references. +asting $etween numeric types is used to convert larger values, such as dou$le values, to smaller values, such as $yte values. +asting $etween o$ject references is used to refer to an o$ject $y a compati$le class, interface, or array type reference. &1. What is the return type of a pro+ram s main12 method? void. &2. )f a variable is declared as private8 "here may the variable be accessed? * private varia$le may only $e accessed within the class in which it is declared. &3. What do you understand by private8 protected and public? -hese are accessi$ility modifiers. P!ivate is the most restrictive, while public is the least restrictive. -here is no real difference $etween p!otected and the default type (also )nown as pac)age protected) within the context of the same pac)age, however the protected )eyword allows visi$ility to a derived class in a different pac)age. &4. What is #o"ncastin+ ? %owncasting is the casting from a general to a more specific type, i.e. casting down the hierarchy &!. What modifiers may be used "ith an inner class that is a member of an outer class?

* (non1local) inner class may $e declared as pu$lic, protected, private, static, final, or a$stract. &%. /o" many bits are used to represent <nicode8 A0.))8 <=>:1%8 and <=>:' characters? 7nicode re/uires 89 $its and * +(( re/uire : $its *lthough the * +(( character set uses only : $its, it is usually represented as ; $its. 7-61; represents characters using ;, 89, and 8; $it patterns. 7-6189 uses 891$it and larger $it patterns. &&. What restrictions are placed on the location of a pac3a+e statement "ithin a source code file? * pac)age statement must appear as the first line in a source code file (excluding $lan) lines and comments). &'. What is a native method? * native method is a method that is implemented in a language other than Java. &(. What are order of precedence and associativity8 and ho" are they used? 2rder of precedence determines the order in which operators are evaluated in expressions. *ssociatity determines whether an expression is evaluated left1to1right or right1to1left. ',. .an an anonymous class be declared as implementin+ an interface and e4tendin+ a class? *n anonymous class may implement an interface or extend a superclass, $ut may not $e declared to do $oth. '1. What is the ran+e of the char type? -he range of the c$a! type is < to =89 1 8 (i.e. < to 9>>?>.) '2. What is the ran+e of the short type? -he range of the s$o!t type is 1(=8>) to =8> 1 8. (i.e. 1?=,:9; to ?=,:9:) '3. Why isn t there operator overloadin+? 'ecause +@@ has proven $y example that operator overloading ma)es code almost impossi$le to maintain. '4. What does it mean that a method or field is 6static6? tatic varia$les and methods are instantiated only once per class. (n other words they are class varia$les, not instance varia$les. (f you change the value of a static varia$le in a particular o$ject, the value of that varia$le changes for all instances of that class. tatic methods can $e referenced with the name of the class rather than the name of a particular o$ject of the class (though that wor)s too). -hat#s how li$rary methods li)e "-stem.out.p!intln() wor). out is a static field in the java.lang."-stem class. '!. )s null a 3ey"ord? -he null value is not a )eyword. '%. Which characters may be used as the second character of an identifier8 but not as the first character of an identifier? -he digits < through A may not $e used as the first character of an identifier $ut they may $e used after the first character of an identifier. '&. )s the ternary operator "ritten 4 ? y ? 5 or 4 ? y ? 5 ? (t is written ) . - / %. ''. /o" is roundin+ performed under inte+er division? -he fractional part of the result is truncated. -his is )nown as rounding toward ,ero. '(. )f a class is declared "ithout any access modifiers8 "here may the class be accessed?

* class that is declared without any access modifiers is said to have pac)age access. -his means that the class can only $e accessed $y other classes and interfaces that are defined within the same pac)age. (,. #oes a class inherit the constructors of its superclass? * class does not inherit constructors from any of its superclasses. (1. @ame the ei+ht primitive Java types. -he eight primitive types are $yte, char, short, int, long, float, dou$le, and $oolean. (2. What restrictions are placed on the values of each case of a s"itch statement? %uring compilation, the values of each case of a s'itc$ statement must evaluate to a value that can $e promoted to an int value. (3. What is the difference bet"een a "hile statement and a do "hile statement? * '$ile statement chec)s at the $eginning of a loop to see whether the next loop iteration should occur. * do '$ile statement chec)s at the end of a loop to see whether the next iteration of a loop should occur. -he do '$ilestatement will always execute the $ody of a loop at least once. (4. What modifiers can be used "ith a local inner class? * local inner class may $e final or abst!act. (!. When does the compiler supply a default constructor for a class? -he compiler supplies a default constructor for a class if no other constructors are provided. (%. )f a method is declared as protected8 "here may the method be accessed? * protected method may only $e accessed $y classes or interfaces of the same pac)age or $y su$classes of the class in which it is declared. (&. What are the le+al operands of the instanceof operator? -he left operand is an o$ject reference or null value and the right operand is a class, interface, or array type. ('. Are true and false 3ey"ords? -he values true and false are not )eywords. ((. What happens "hen you add a double value to a 0trin+? -he result is a tring o$ject.

1,,. What is the diffrence bet"een inner class and nested class? When a class is defined within a scope od another class, then it $ecomes inner class. (f the access modifier of the inner class is static, then it $ecomes nested class. 1,1. .an an abstract class be final? *n a$stract class may not $e declared as final. 1,2. What is numeric promotion? .umeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating1point operations may ta)e place. (n numerical promotion, $yte, char, and short values are converted to int values. -he int values are also converted to long values, if necessary. -he long and float values are converted to dou$le values, as re/uired. 1,3. What is the difference bet"een a public and a non:public class? * pu$lic class may $e accessed outside of its pac)age. * non1pu$lic class may not $e accessed outside of its pac)age. 1,4. =o "hat value is a variable of the boolean type automatically initiali5ed? -he default value of the $oolean type is false.

1,!. What is the difference bet"een the prefi4 and postfi4 forms of the AA operator? -he prefix form performs the increment operation and returns the value of the increment operation. -he postfix form returns the current value all of the expression and then performs the increment operation on that value. 1,%. What restrictions are placed on method overridin+? 2verridden methods must have the same name, argument list, and return type. -he overriding method may not limit the access of the method it overrides. -he overriding method may not throw any exceptions that may not $e thrown $y the overridden method. 1,&. What is a Java pac3a+e and ho" is it used? * Java pac)age is a naming context for classes and interfaces. * pac)age is used to create a separate name space for groups of classes and interfaces. Pac)ages are also used to organi,e related classes and interfaces into a single *P( unit and to control accessi$ility to these classes and interfaces. 1,'. What modifiers may be used "ith a top:level class? * top1level class may $e pu$lic, a$stract, or final. 1,(. What is the difference bet"een an if statement and a s"itch statement? -he if statement is used to select among two alternatives. (t uses a $oolean expression to decide which alternative should $e executed. -he switch statement is used to select among multiple alternatives. (t uses an int expression to determine which alternative should $e executed. 11,. What are the practical benefits8 if any8 of importin+ a specific class rather than an entire pac3a+e 1e.+. import *ava.net.B versus import *ava.net.0oc3et2? (t ma)es no difference in the generated class files since only the classes that are actually used are referenced $y the generated class file. -here is another practical $enefit to importing single classes, and this arises when two (or more) pac)ages have classes with the same name. -a)e java.util.0ime! and javax.swing.-imer, for example. (f (impo!t java.util.1 and java).s'ing.1 and then try to use 3-imer3, ( get an error while compiling (the class name is am$iguous $etween $oth pac)ages). Let#s say what you really wanted was the java).s'ing.0ime! class, and the only classes you plan on using in java.util are +ollection and 4ash"ap. (n this case, some people will prefer to impo!t java.util.&ollection and impo!t java.util.2as$Map instead of importing java.util.1. -his will now allow them to use -imer, +ollection, 4ash"ap, and other java).s'ing classes without using fully /ualified class names in. 111. .an a method be overloaded based on different return type but same ar+ument type ? .o, $ecause the methods can $e called without using their return type in which case there is am$i/uity for the compiler. 112. What happens to a static variable that is defined "ithin a method of a class ? +an#t do it. 0ou#ll get a compilation error. 113. /o" many static initiali5ers can you have ? *s many as you want, $ut the static initiali,ers and class varia$le initiali,ers are executed in textual order and may not refer to class varia$les declared in the class whose declarations appear textually after the use, even though these class varia$les are in scope. 114. What is the difference bet"een method overridin+ and overloadin+? 2verriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name $ut different arguments 11!. What is constructor chainin+ and ho" is it achieved in Java ? * child o$ject constructor always first needs to construct its parent (which in turn calls its parent constructor.). (n Java it is done via an implicit call to the no1args constructor as the first statement. 11%. What is the difference bet"een the 9oolean C operator and the CC operator?

(f an expression involving the 'oolean B operator is evaluated, $oth operands are evaluated. -hen the B operator is applied to the operand. When an expression involving the BB operator is evaluated, the first operand is evaluated. (f the first operand returns a value of true then the second operand is evaluated. -he BB operator is then applied to the first and second operands. (f the first operand evaluates to false, the evaluation of the second operand is s)ipped. 11&. Which Java operator is ri+ht associative? -he C operator is right associative. 11'. .an a double value be cast to a byte? 0es, a dou$le value can $e cast to a $yte. 11(. What is the difference bet"een a brea3 statement and a continue statement? * b!ea statement results in the 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. 12,. .an a for statement loop indefinitely? 0es, a for statement can loop indefinitely. 6or example, consider the followingD fo!(;;); 121. =o "hat value is a variable of the 0trin+ type automatically initiali5ed? -he default value of an tring type is null.

122. What is the difference bet"een a field variable and a local variable? * field varia$le is a varia$le that is declared as a mem$er of a class. * local varia$le is a varia$le that is declared local to a method. 123. /o" are this12 and super12 used "ith constructors?

t$is() is used to invo)e a constructor of the same class. supe!() is used to invo)e a superclass
constructor. 124. What does it mean that a class or member is final? * final class cannot $e inherited. * final method cannot $e overridden in a su$class. * final field cannot $e changed after it#s initiali,ed, and it must include an initiali,er statement where it#s declared. 12!. What does it mean that a method or class is abstract? *n a$stract class cannot $e instantiated. *$stract methods may only $e included in a$stract classes. 4owever, an a$stract class is not re/uired to have any a$stract methods, though most of them do. 5ach su$class of an a$stract class must override the a$stract methods of its superclasses or it also should $e declared a$stract. 12%. What is a transient variable? -ransient varia$le is a varia$le that may not $e seriali,ed. 12&. /o" does Java handle inte+er overflo"s and underflo"s? (t uses those low order $ytes of the result that can fit into the si,e of the type allowed $y the operation. 12'. What is the difference bet"een the DD and DDD operators? -he EE operator carries the sign $it when shifting right. -he EEE ,ero1fills $its that have $een shifted out. 12(. )s si5eof a 3ey"ord? -he si,eof operator is not a )eyword.

8. What is the difference $etween a constructor and a methodF

* constructor is a mem$er function of a class that is used to create o$jects of that class. (t has the same name as the class itself, has no return type, and is invo)ed using the new operator. * method is an ordinary mem$er function of a class. (t has its own name, a return type (which may $e void), and is invo)ed using the dot operator. 2. What is the purpose of +arba+e collection in Java8 and "hen is it used? -he purpose of gar$age collection is to identify and discard o$jects that are no longer needed $y a program so that their resources can $e reclaimed and reused. * Java o$ject is su$ject to gar$age collection when it $ecomes unreacha$le to the program in which it is used. 3. #escribe synchroni5ation in respect to multithreadin+. With respect to multithreading, synchroni,ation is the capa$ility to control the access of multiple threads to shared resources. Without synchoni,ation, it is possi$le for one thread to modify a shared varia$le while another thread is in the process of using or updating same shared varia$le. -his usually leads to significant errors. 4. What is an abstract class? *$stract class must $e extendedGsu$classed (to $e useful). (t serves as a template. * class that is a$stract may not $e instantiated (ie. you may not call its constructor), a$stract class may contain static data. *ny class with an a$stract method is automatically a$stract itself, and must $e declared as such. * class may $e declared a$stract even if it has no a$stract methods. -his prevents it from $eing instantiated. !. What is the difference bet"een an )nterface and an Abstract class? *n a$stract class can have instance methods that implement a default $ehavior. *n (nterface can only declare constants and instance methods, $ut cannot implement default $ehavior and all methods are implicitly a$stract. *n interface has all pu$lic mem$ers and no implementation. *n a$stract class is a class which may have the usual flavors of class mem$ers (p!ivate# p!otected, etc.), $ut has some a$stract methods. %. 74plain different "ay of usin+ thread? -he thread could $e implemented $y using runna$le interface or $y inheriting from the 0$!ead class. -he former is more advantageous, #cause when you are going for multiple inheritance, the only interface can help. :. What is an (teratorF ome of the collection classes provide traversal of their contents via a java.util.Ite!ato! interface. -his interface allows you to wal) through a collection of o$jects, operating on each o$ject in turn. Hemem$er when using (terators that they contain a snapshot of the collection at the time the (terator was o$tainedI generally it is not advisa$le to modify the collection itself while traversing an (terator. '. 0tate the si+nificance of public8 private8 protected8 default modifiers both sin+ly and in combination and state the effect of pac3a+e relationships on declared items Eualified by these modifiers.

public/ Pu$lic class is visi$le in other pac)ages, field is visi$le everywhere (class must $e pu$lic too) p!ivate / Private varia$les or methods may $e used only $y an instance of the same class that declares
the varia$le or method, * private feature may only $e accessed $y the class that owns the feature.

p!otected / (s availa$le to all classes in the same pac)age and also availa$le to all su$classes of the
class that owns the protected feature. -his access is provided even to su$classes that reside in a different pac)age from the class that owns the protected feature.

What you get $y default ie, without any access modifier (ie, pu$lic private or protected). (t means that it is visi$le to all within a particular pac)age. (. What is static in *ava? tatic means one per class, not one for each o$ject no matter how many instance of a class might exist. -his means that you can use them without creating an instance of a class. tatic methods are implicitly final, $ecause overriding is done $ased on the type of the o$ject, and static methods are attached to a class, not an o$ject. * static method in a superclass can $e shadowed $y another static method in a su$class, as long as the original method was not declared final. 4owever, you can#t override a static method with a nonstatic method. (n other words, you can#t change a static method into an instance method in a su$class. 1,. What is final class? * final class can#t $e extended ie., final class may not $e su$classed. * final method can#t $e overridden when its class is inherited. 0ou can#t change value of a final varia$le (is a constant). 11. What if the main12 method is declared as private? -he program compiles properly $ut at runtime it will give 3main() method not pu$lic.3 message. 12. What if the static modifier is removed from the si+nature of the main12 method? Program compiles. 'ut at runtime throws an error 3.o uch"ethod5rror3. 8?. What if ( write static pu$lic void instead of pu$lic static voidF Program compiles and runs properly. 14. What if ) do not provide the 0trin+ array as the ar+ument to the method? Program compiles $ut throws a runtime error 3.o uch"ethod5rror3. 1!. What is the first ar+ument of the 0trin+ array in main12 method? -he tring array is empty. (t does not have any element. -his is unli)e +G+@@ where the first element $y default is the program name. 1%. )f ) do not provide any ar+uments on the command line8 then the 0trin+ array of main12 method "ill be empty or null? (t is empty. 'ut not null. 1&. /o" can one prove that the array is not null but empty usin+ one line of code? Print a!gs.lengt$. (t will print <. -hat means it is empty. 'ut if it would have $een null then it would have thrown a3ullPointe!()ception on attempting to print a!gs.lengt$. 1'. What environment variables do ) need to set on my machine in order to be able to run Java pro+rams?

&45""P502 and P502 are the two varia$les.


8A. +an an application have multiple classes having main() methodF 0es it is possi$le. While starting the application we mention the class name to $e run. -he J!" will loo) for the "ain method only in the class whose name you have mentioned. 4ence there is not conflict amongst the multiple classes having main() method. 2,. .an ) have multiple main12 methods in the same class? .o the program fails to compile. -he compiler says that the main() method is already defined in the class. 21. #o ) need to import *ava.lan+ pac3a+e any time? Why ? .o. (t is $y default loaded internally $y the J!".

22. .an ) import same pac3a+eFclass t"ice? Will the JVM load the pac3a+e t"ice at runtime? 2ne can import the same pac)age or same class multiple times. .either compiler nor J!" complains a$out it. *nd the J!" will internally load the class only once no matter how many times you import the same class. 23. What are .hec3ed and <n.hec3ed 74ception? * chec)ed exception is some su$class of 5xception (or 5xception itself), excluding class Huntime5xception and its su$classes. "a)ing an exception chec)ed forces client programmers to deal with the possi$ility that the exception will $e thrown. 5xampleD IO()ception thrown $y java.io.6ileInput"t!eam#s !ead() methodJ 7nchec)ed exceptions are Huntime5xception and any of its su$classes. +lass 5rror and its su$classes also are unchec)ed. With an unchec)ed exception, however, the compiler doesn#t force client programmers either to catch the exception or declare it in a throws clause. (n fact, client programmers may not even )now that the exception could $e thrown. 5xampleD "t!ingInde)OutOf7ounds()ception thrown $y tring#s c$a!5t() methodJ +hec)ed exceptions must $e caught at compile time. Huntime exceptions do not need to $e. 5rrors often cannot $e. 24. What is Gverridin+? When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invo)ed for an o$ject of the class, it is the new definition of the method that is called, and not the method definition from superclass. "ethods may $e overridden to $e more pu$lic, not more private. =>. *re the imports chec)ed for validity at compile timeF 5xampleD will the code containing an import such as java.lang.*'+% compileF 0es the imports are chec)ed for the semantic validity at compile time. -he code containing a$ove line of import will not compile. (t will throw an error saying, can not resolve sym$ol sym$ol D class 57&8 locationD pac age io

impo!t java.io.57&8;
2%. #oes importin+ a pac3a+e imports the subpac3a+es as "ell? 74ample? #oes importin+ com.My=est.B also import com.My=est.<nit=ests.B? .o you will have to import the su$pac)ages explicitly. (mporting com.M-0est.1 will import classes in the pac)ageM-0est only. (t will not import any class in any of it#s su$pac)age. 2&. What is the difference bet"een declarin+ a variable and definin+ a variable? (n declaration we just mention the type of the varia$le and it#s name. We do not initiali,e it. 'ut defining means declaration @ initiali,ation. 5xampleD "t!ing s; is just a declaration while "t!ing s = ne' "t!ing (9abcd9); 2r "t!ing s = 9abcd9;are $oth definitions. 2'. What is the default value of an ob*ect reference declared as an instance variable? -he default value will $e null unless we define it explicitly. 2(. .an a top level class be private or protected? .o. * top level class cannot $e private or protected. (t can have either 3pu$lic3 or no modifier. (f it does not have a modifier it is supposed to have a default access. (f a top level class is declared as private the compiler will complain that the 3modifier private is not allowed here3. -his means that a top level class can not $e private. ame is the case with protected.

3,. What type of parameter passin+ does Java support? (n Java the arguments are always passed $y value. ?8. Primitive data types are passed $y reference or pass $y valueF Primitive data types are passed $y value. 32. Gb*ects are passed by value or by reference? Java only supports pass $y value. With o$jects, the o$ject reference itself is passed $y value and so $oth the original reference and parameter copy $oth refer to the same o$ject. 33. What is seriali5ation? eriali,ation is a mechanism $y which you can save the state of an o$ject $y converting it to a $yte stream. 34. /o" do ) seriali5e an ob*ect to a file? -he class whose instances are to $e seriali,ed should implement an interface eriali,a$le. -hen you pass the instance to the ObjectOutput"t!eam which is connected to a fileoutputst!eam. -his will save the o$ject to a file. 3!. Which methods of 0eriali5able interface should ) implement? -he seriali,a$le interface is an empty interface, it does not contain any methods. any methods. o we do not implement

3%. /o" can ) customi5e the serali5ation process? i.e. ho" can one have a control over the seriali5ation process? 0es it is possi$le to have control over seriali,ation process. -he class should implement 5xternali,a$le interface. -his interface contains two methods namely !ead()te!nal and '!ite()te!nal. 0ou should implement these methods and write the logic for customi,ing the seriali,ation process. ?:. What is the common usage of seriali,ationF Whenever an o$ject is to $e sent over the networ), o$jects need to $e seriali,ed. "oreover if the state of an o$ject is to $e saved, o$jects need to $e serila,ed. 3'. What is 74ternali5able interface? 5xternali,a$le is an interface which contains two methods !ead()te!nal and '!ite()te!nal. -hese methods give you a control over the seriali,ation mechanism. -hus if your class implements this interface, you can customi,e the seriali,ation process $y implementing these methods. 3(. When you seriali5e an ob*ect8 "hat happens to the ob*ect references included in the ob*ect? -he seriali,ation mechanism generates an o$ject graph for seriali,ation. -hus it determines whether the included o$ject references are seriali,a$le or not. -his is a recursive process. -hus when an o$ject is seriali,ed, all the included o$jects are also seriali,ed alongwith the original o$ect. 4,. What one should ta3e care of "hile seriali5in+ the ob*ect? 2ne should ma)e sure that all the included o$jects are also seriali,a$le. (f any of the o$jects is not seriali,a$le then it throws a 3ot"e!iali%able()ception. 41. What happens to the static fields of a class durin+ seriali5ation? -here are three exceptions in which seriali,ation doesnot necessarily read and write to the stream. -hese are 8. eriali,ation ignores static fields, $ecause they are not part of ay particular state state.

=. 'ase class fields are only hendled if the $ase class itself is seriali,a$le. ?. -ransient fields. 42. #oes Java provide any construct to find out the si5e of an ob*ect? .o, there is not si,eof operator in Java. directly in Java. K?. What are wrapper classesF Java provides speciali,ed classes corresponding to each of the primitive data types. -hese are called wrapper classes. -hey are exampleD (nteger, +haracter, %ou$le etc. 44. Why do "e need "rapper classes? (t is sometimes easier to deal with primitives as o$jects. "oreover most of the collection classes store o$jects and not primitive data types. *nd also the wrapper classes provide many utility methods also. 'ecause of these resons we need wrapper classes. *nd since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. *lso we can pass them around as method parameters where a method expects an o$ject. 4!. What are chec3ed e4ceptions? +hec)ed exception are those which the Java compiler forces you to catch. 5xampleD IO()ception are chec)ed exceptions. 4%. What are runtime e4ceptions? Huntime exceptions are those exceptions that are thrown at runtime $ecause of either wrong input data or $ecause of wrong $usiness logic etc. -hese are not chec)ed $y the compiler at compile time. 4&. What is the difference bet"een error and an e4ception? *n error is an irrecovera$le condition occurring at runtime. uch as OutOfMemo!- error. o there is not direct way to determine the si,e of an o$ject

-hese J!" errors and you can not repair them at runtime. While exceptions are conditions that occur $ecause of $ad input etc. 5xampleD 6ile3ot6ound()ception will $e thrown if the specified file does not exist. 2r a3ullPointe!()ception will ta)e place if you try using a null reference. (n most of the cases it is possi$le to recover from an exception (pro$a$ly $y giving user a feed$ac) for entering proper values etc.). 4'. /o" to create custom e4ceptions? 0our class should extend class ()ception, or some more specific type thereof. KA. (f ( want an o$ject of my class to $e thrown as an exception o$ject, what should ( doF -he class should extend from 5xception class. 2r you can extend your class from some more precise exception type also. !,. )f my class already e4tends from some other class "hat should ) do if ) "ant an instance of my class to be thro"n as an e4ception ob*ect? 2ne can not do anytihng in this scenarion. 'ecause Java does not allow multiple inheritance and does not provide any exception interface as well. !1. /o" does an e4ception permeate throu+h the code? *n unhandled exception moves up the method stac) in search of a matching When an exception is thrown from a code which is wrapped in a try $loc) followed $y one or more catch $loc)s, a search is made for matching catch $loc). (f a matching type is found then that $loc) will $e invo)ed. (f a matching type is not found then the exception moves up the method stac) and reaches the caller method.

ame procedure is repeated if the caller method is included in a try catch $loc). -his process continues until a catch $loc) handling the appropriate type of exception is found. (f it does not find such a $loc) then finally the program terminates. !2. What are the different "ays to handle e4ceptions? -here are two ways to handle exceptions, 8. 'y wrapping the desired code in a try $loc) followed $y a catch $loc) to catch the exceptions. and =. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions. !3. )s it necessary that each try bloc3 must be follo"ed by a catch bloc3? (t is not necessary that each t!- $loc) must $e followed $y a catc$ $loc). (t should $e followed $y either a catch $loc) or a finall- $loc). *nd whatever exceptions are li)ely to $e thrown should $e declared in the throws clause of the method. !4. )f ) "rite return at the end of the try bloc38 "ill the finally bloc3 still e4ecute? 0es even if you write return as the last statement in the t!- $loc) and no exception occurs, the finally $loc) will execute. -he finally $loc) will execute and then the control return. >>. (f ( write ystem.exit(<)I at the end of the try $loc), will the finally $loc) still executeF

.o. (n this case the finally $loc) will not execute $ecause when you say "-stem.e)it(:); the control immediately goes out of the program, and thus finally never executes. !%. /o" are Gbserver and Gbservable used? 2$jects that su$class the 2$serva$le class maintain a list of o$servers. When an 2$serva$le o$ject is updated it invo)es the update() method of each of its o$servers to notify the o$servers that it has changed state. -he 2$server interface is implemented $y o$jects that o$serve 2$serva$le o$jects. !&. What is synchroni5ation and "hy is it important? With respect to multithreading, synchroni,ation is the capa$ility to control the access of multiple threads to shared resources. Without synchroni,ation, it is possi$le for one thread to modify a shared o$ject while another thread is in the process of using or updating that o$ject#s value. -his often leads to significant errors. !'. /o" does Java handle inte+er overflo"s and underflo"s? (t uses those low order $ytes of the result that can fit into the si,e of the type allowed $y the operation. !(. #oes +arba+e collection +uarantee that a pro+ram "ill not run out of memory? Lar$age collection does not guarantee that a program will not run out of memory. (t is possi$le for programs to use up memory resources faster than they are gar$age collected. (t is also possi$le for programs to create o$jects that are not su$ject to gar$age collection. %,. What is the difference bet"een preemptive schedulin+ and time slicin+? 7nder preemptive scheduling, the highest priority tas) executes until it enters the waiting or dead states or a higher priority tas) comes into existence. 7nder time slicing, a tas) executes for a predefined slice of time and then reenters the pool of ready tas)s. -he scheduler then determines which tas) should execute next, $ased on priority and other factors. 98. When a thread is created and started, what is its initial stateF * thread is in the ready state after it has $een created and started. %2. What is the purpose of finali5ation?

-he purpose of finali,ation is to give an unreacha$le o$ject the opportunity to perform any cleanup processing $efore the o$ject is gar$age collected. %3. What is the Hocale class? -he Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. %4. What is the difference bet"een a "hile statement and a do statement? * '$ile statement chec)s at the $eginning of a loop to see whether the next loop iteration should occur. * do statement chec)s at the end of a loop to see whether the next iteration of a loop should occur. -he do statement will always execute the $ody of a loop at least once. %!. What is the difference bet"een static and non:static variables? * static varia$le is associated with the class as a whole rather than with specific instances of a class. .on1static varia$les ta)e on uni/ue values with each o$ject instance. %%. /o" are this12 and super12 used "ith constructors?

t$is() is used to invo)e a constructor of the same class. supe!() is used to invo)e a superclass
constructor. 9:. What is daemon thread and which method is used to create the daemon threadF %aemon thread is a low priority thread which runs intermittently in the $ac) ground doing the gar$age collection operation for the java !untime s-stem.set8aemon method is used to create a daemon thread. %'. .an applets communicate "ith each other? *t this point in time applets may communicate with other applets running in the same virtual machine. (f the applets are of the same class, they can communicate via shared static varia$les. (f the applets are of different classes, then each will need a reference to the same class with static varia$les. (n any case the $asic idea is to pass the information $ac) and forth through a static varia$le. *n applet can also get references to all other applets on the same page using the get5pplets() method ofjava.applet.5pplet&onte)t. 2nce you get the reference to an applet, you can communicate with it $y using its pu$lic mem$ers. (t is conceiva$le to have applets in different virtual machines that tal) to a server somewhere on the (nternet and store any data that needs to $e seriali,ed there. -hen, when another applet needs this data, it could connect to this same server. (mplementing this is non1trivial. %(. What are the steps in the J#9. connection? While ma)ing a J%'+ connection we go through the following steps D tep 8 D Hegister the data$ase driver $y using D

&lass.fo!3ame(;9 d!ive! classs fo! t$at specific database;9 );


tep = D .ow create a data$ase connection using D

&onnection con = 8!ive!Manage!.get&onnection(u!l#use!name#pass'o!d);


tep ?D .ow +reate a /uery using D

"tatement stmt = &onnection."tatement(;9select 1 f!om 0574( 35M(;9);


tep K D 5xceute the /uery D

stmt.e)ceute<pdate();
&,. /o" does a try statement determine "hich catch clause should be used to handle an e4ception?

When an exception is thrown within the $ody of a t!- statement, the catc$ clauses of the t!- statement are examined in the order in which they appear. -he first catch clause that is capa$le of handling the exceptionis executed. -he remaining catch clauses are ignored. &1. .an an unreachable ob*ect become reachable a+ain? *n unreacha$le o$ject may $ecome reacha$le again. -his can happen when the o$ject#s finali%e() method is invo)ed and the o$ject performs an operation which causes it to $ecome accessi$le to reacha$le o$jects. &2. What method must be implemented by all threads? *ll tas)s must implement the !un() method, whether they are a su$class of -hread or implement the Hunna$le interface. :?. What are synchroni,ed methods and synchroni,ed statementsF ynchroni,ed methods are methods that are used to control access to an o$ject. * thread only executes a synchroni,ed method after it has ac/uired the loc) for the method#s o$ject or class. ynchroni,ed statements are similar to synchroni,ed methods. * synchroni,ed statement can only $e executed after a thread has ac/uired the loc) for the o$ject or class referenced in the synchroni,ed statement. &4. What is 74ternali5able? 5xternali,a$le is an (nterface that extends eriali,a$le (nterface. *nd sends data into +ompressed 6ormat. (t has two methods, '!ite()te!nal(ObjectOuput out) and !ead()te!nal(ObjectInput in). &!. What modifiers are allo"ed for methods in an )nterface? 2nly public and abst!act modifiers are allowed for methods in interfaces. &%. What are some alternatives to inheritance? %elegation is an alternative to inheritance. %elegation means that you include an instance of another class as an instance varia$le, and forward messages to the instance. (t is often safer than inheritance $ecause it forces you to thin) a$out each message you forward, $ecause the instance is of a )nown class, rather than a new class, and $ecause it doesn#t force you to accept all the methods of the super classD you can provide only the methods that really ma)e sense. 2n the other hand, it ma)es you write more code, and it is harder to re1use ($ecause it is not a su$class). &&. What does it mean that a method or field is 6static6? tatic varia$les and methods are instantiated only once per class. (n other words they are class varia$les, not instance varia$les. (f you change the value of a static varia$le in a particular o$ject, the value of that varia$le changes for all instances of that class. tatic methods can $e referenced with the name of the class rather than the name of a particular o$ject of the class (though that wor)s too). -hat#s how li$rary methods li)e "-stem.out.p!intln() wor) out is a static field in thejava.lang."-stem class. &'. What is the difference bet"een preemptive schedulin+ and time slicin+? 7nder preemptive scheduling, the highest priority tas) executes until it enters the waiting or dead states or a higher priority tas) comes into existence. 7nder time slicing, a tas) executes for a predefined slice of time and then reenters the pool of ready tas)s. -he scheduler then determines which tas) should execute next, $ased on priority and other factors. :A. What is the catch or declare rule for method declarationsF (f a chec)ed exception may $e thrown within the $ody of a method, the method must either catch the exception or declare it in its throws clause. treams in

',. )s 7mpty .*ava file a valid source file? 0es. *n empty .java file is a perfectly valid source file. '1. .an a .*ava file contain more than one *ava classes? 0es. * .java file contain more than one java classes, provided at the most one of them is a pu$lic class. '2. )s 0trin+ a primitive data type in Java? .o. tring is not a primitive data type in Java, even though it is one of the most extensively used o$ject. trings in Java are instances of tring class defined in java.lang pac age. '3. )s main a 3ey"ord in Java? .o. main is not a )eyword in Java. '4. )s ne4t a 3ey"ord in Java? .o. ne)t is not a )eyword. ;>. (s delete a )eyword in JavaF .o. delete is not a )eyword in Java. Java does not ma)e use of explicit destructors the way +@@ does. '%. )s e4it a 3ey"ord in Java? .o. -o exit a program explicitly you use e)it method in ystem o$ject.

'&. What happens if you dont initiali5e an instance variable of any of the primitive types in Java? Java $y default initiali,es it to the default value for that primitive type. -hus an int will $e initiali,ed to :(,ero), a $oolean will $e initiali,ed to false. ''. What "ill be the initial value of an ob*ect reference "hich is defined as an instance variable? -he o$ject references are all initiali,ed to null in Java. 4owever in order to do anything useful with these references, you must set them to a valid o$ject, else you will get 3ullPointe!()ceptions everywhere you try to use such default initiali,ed references. '(. What are the different scopes for Java variables? -he scope of a Java varia$le is determined $y the context in which the varia$le is declared. -hus a java varia$le can have one of the three scopes at any given point in time. 8. (nstance D 1 -hese are typical o$ject level varia$les, they are initiali,ed to default values at the time of creation of o$ject, and remain accessi$le as long as the o$ject accessi$le. =. Local D 1 -hese are the varia$les that are defined within a method. -hey remain access$ile only during the course of method excecution. When the method finishes execution, these varia$les fall out of scope. ?. taticD 1 -hese are the class level varia$les. -hey are initiali,ed when the class is loaded in J!" for the first time and remain there as long as the class remains loaded. -hey are not tied to any particular o$ject instance. (,. What is the default value of the local variables? -he local varia$les are not initiali,ed to any default value, neither primitives nor o$ject references. (f you try to use these varia$les without initiali,ing them explicitly, the java compiler will not compile the code. (t will complain a$t the local varai$le not $eing initili,ed. A8. 4ow many o$jects are created in the following piece of codeF "y+lass c8, c=, c?I c8 C new "y+lass ()I c? C new "y+lass ()I 2nly = o$jects are created, c1 and c=. -he reference c2 is only declared and not initiali,ed. (2. .an a public class My.lass be defined in a source file named Iour.lass.*ava?

.o. -he source file name, if it contains a pu$lic class, must $e the same as the pu$lic class name itself with a .javaextension. (3. .an main12 method be declared final? 0es, the main() method can $e declared final, in addition to $eing public static. (4. What is /ashMap and Map? "ap is an (nterface and 4ashmap is the class that implements "ap. (!. #ifference bet"een /ashMap and /ash=able? -he 4ash"ap class is roughly e/uivalent to 4ashta$le, except that it is unsynchroni,ed and permits nulls. (4ash"ap allows null values as )ey and value whereas 4ashta$le doesnt allow). 4ash"ap does not guarantee that the order of the map will remain constant over time. 4ash"ap is unsynchroni,ed and 4ashta$le is synchroni,ed. (%. #ifference bet"een Vector and ArrayHist? !ector is synchroni,ed whereas arraylist is not. A:. %ifference $etween wing and *wtF wings are light1weight components. 4ence swing wor)s faster

*W- are heavy1weight componenets. than *W-.

('. What "ill be the default values of all the elements of an array defined as an instance variable? (f the array is an array of primitive types, then all the elements of the array will $e initiali,ed to the default value corresponding to that primitive type. 5xampleD *ll the elements of an array of int will $e initiali,ed to :(,ero), while that of $oolean type will $e initiali,ed tofalse. Whereas if the array is an array of references (of any type), all the elements will $e initiali,ed to null.

Anda mungkin juga menyukai