Vous êtes sur la page 1sur 67

3-5- 100 quest 30 break 5.30-7.

30- probleme + irina telefon +collection+oop principlee Top 100 Java Interview "nswers
sparrow gajjar 07:00 java tutorials

uestions wit!

1. #!at is t!e $ifference between an Inner %lass an$ a &ub-%lass' Ans: An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class. (. #!at are t!e various access specifiers for Java classes' Ans: In Java, access specifiers are the keywords used before a class name which defines the access scope. he types of access specifiers for classes are: !. "ublic : #lass,$ethod,%ield is accessible from anywhere. &. "rotected:$ethod,%ield can be accessed from the same class to which they belong or from the sub-classes,and from the class of same package,but not from outside. '. (efault: $ethod,%ield,class can be accessed only from the same package and not from outside of it)s native package. *. "rivate: $ethod,%ield can be accessed from the same class to which they belong. 3. #!at)s t!e purpose of &tatic met!o$s an$ static variables' Ans: +hen there is a re,uirement to share a method or a variable between multiple ob-ects of a class instead of creating separate copies for each ob-ect, we use static keyword to make a method or variable shared for all ob-ects. *. #!at is $ata encapsulation an$ w!at)s its si+nificance' Ans: .ncapsulation is a concept in /b-ect /riented "rogramming for combining properties and methods in a single unit. .ncapsulation helps programmers to follow a modular approach for software development as each ob-ect has its own set of methods and variables and serves its functions independent of other ob-ects. .ncapsulation also serves data hiding purpose. 5. #!at is a sin+leton class' ,ive a practical e-ample of its usa+e. A singleton class in -ava can have only one instance and hence all its methods and variables belong to -ust one instance. Singleton class concept is useful for the situations when there is a need to limit the number of ob-ects for a class.

he best e0ample of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues. .. #!at are /oops in Java' #!at are t!ree t0pes of loops' Ans: 1ooping is used in programming to e0ecute a statement or a block of statement repeatedly. here are three types of loops in Java: !2 %or 1oops %or loops are used in -ava to e0ecute statements repeatedly for a given number of times. %or loops are used when number of times to e0ecute the statements is known to programmer. &2 +hile 1oops +hile loop is used when certain statements need to be e0ecuted repeatedly until a condition is fulfilled. In while loops, condition is checked first before e0ecution of statements. '2 (o +hile 1oops (o +hile 1oop is same as +hile loop with only difference that condition is checked after e0ecution of block of statements. 3ence in case of do while loop, statements are e0ecuted at least once. 71 #!at is an infinite /oop' 2ow infinite loop is $eclare$' Ans: An infinite loop runs without any condition and runs infinitely. An infinite loop can be broken by defining any breaking logic in the body of the statement blocks. Infinite loop is declared as follows: 4-ava5 %or 6772 8 99 Statements to e0ecute 99 Add any loop breaking logic : 49-ava5 3. #!at is t!e $ifference between continue an$ break statement'

Ans: break and continue are two important keywords used in 1oops. +hen a break keyword is used in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken and loop continues with ne0t iteration. In below e0ample, 1oop is broken when counter reaches *. 4-ava5 %or 6counter;<7counter System.out.println6counter27 If 6counter;;*2 8 =reak7: : 49-ava5 In the below e0ample when counter reaches *, loop -umps to ne0t iteration and any statements after the continue keyword are skipped for current iteration. 4-ava5 %or 6counter;<7counter System.out.println6counter27 If 6counter;;*2 8 continue7 : System.outprintln6> his will not get printed when counter is *?27 : 49-ava5 4. #!at is t!e $ifference between $ouble an$ float variables in Java' Ans: In -ava, float takes * bytes in memory while (ouble takes @ bytes in memory. %loat is single precision floating point decimal number while (ouble is double precision decimal number. 10. #!at is 5inal 6e0wor$ in Java' ,ive an e-ample. Ans: In -ava, a constant is declared using the keyword %inal. Aalue can be assigned only once and after assignment, value of a constant can)t be changed.

In below e0ample, a constant with the name constBval is declared and assigned avalue: "rivate %inal int constBval;!<< +hen a method is declared as final,it can C/ resolved at complied time. +hen a class is declares as final,it cannot be subclassed. .0ample String,Integer and other wrapper classes. 11. #!at is ternar0 operator' ,ive an e-ample. Ans: ernary operator , also called conditional operator is used to decide which value to assign to a variable based on a =oolean value evaluation. It)s denoted as D In the below e0ample, if rank is !, status is assigned a value of >(oneE else >"endingE. 4-ava5 public class condition est 8 public static void main6string args452 8 String status7 int rank7 status; 6rank ;; !2 D >(oneE: >"endingE7 : : 49-ava5 1(1 #!at are . $ifferent t0pes of operators in Java'

be overridden by the

subclasses. his method are faster than any other method,because they are

Ans: In -ava, operators can be classified in following si0 types: Arithmetic Operators Fsed for arithmetic calculations. .0ample are +7-78797:7++7; Relational Operators Fsed for relational comparison. ..g. <<7=<7 >7?7?<7>< Bitwise operators Fsed for bit by bit operations. ..g. @7A7B7C Logical Operators Fsed for logical comparisons. ..g. @@7AA7=

Assignment Operators Fsed for assigning values to variables. ..g. <7+<7-<78<79< 13. #!at is $efault switc! case' ,ive e-ample. Ans: In a switch statement, default case is e0ecuted when no other switch condition matches. (efault case is an optional case . It can be declared only once all other switch cases have been coded. In the below e0ample, when score is not ! or &, default case is used. 4-ava5 public class switch.0ample 8 int score;*7 public static void main6String args452 8 switch 6score2 8 case !: System.out.println6>Score is !?27 break7 case &: system.out.println6>Score is &?27 break7 default: System.out.println6>(efault #aseE27 : : : 49-ava5 1*. #!at)s t!e base class in Java from w!ic! all classes are $erive$' Ans: -ava.lang.ob-ect 15. %an mainDE met!o$ in Java can return an0 $ata' Ans: In -ava, main62 method can)t return any data and hence, it)s always declared with a void return type. 1.. #!at are Java Facka+es' #!at)s t!e si+nificance of packa+es' Ans: In Java, package is a collection of classes and interfaces which are bundled together as they are related to each other. Fse of packages helps

developers to modulariGe the code and group the code for proper re-use. /nce code has been packaged in "ackages, it can be imported in other classes and used. 17. %an we $eclare a class as "bstract wit!out !avin+ an0 abstract met!o$' Ans: Hes we can create an abstract class by using abstract keyword before class name even if it doesn)t have any abstract method. 3owever, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error. 13. #!at)s t!e $ifference between an "bstract %lass an$ Interface in Java' Ans: he primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers 6public, private etc2 with or without concrete implementation. Another key difference in the use of abstract classes and interfaces is that a class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn)t re,uire implementation of all the methods of its super class. A class can implement multiple interfaces but it can e0tend only one abstract class. 14. #!at are t!e performance implications of Interfaces over abstract classes' Ans: Interfaces are slower in performance as compared to abstract classes as e0tra indirections are re,uired for interfaces. Another key factor for developers to take into consideration is that any class can e0tend only one abstract class while a class can implement many interfaces. Fse of interfaces also puts an e0tra burden on the developers as any time an interface is implemented in a class7 developer is forced to implement each and every method of interface. (0. Goes Importin+ a packa+e imports its sub-packa+es as well in Java' Ans: In -ava, when a package is imported, its sub-packages aren)t imported and developer needs to import them separately if re,uired. %or e0ample, if a developer imports a package university.I, all classes in the package named university are loaded but no classes from the sub-package

are loaded. o load the classes from its sub-package 6 say department2, developer has to import it e0plicitly as follows: Import university.department.I (1. %an we $eclare t!e main met!o$ of our class as private' Ans: In -ava, main method must be public static in order to run any application correctly. If main method is declared as private, developer won)t get any compilation error however, it will not get e0ecuted and will give a runtime error. ((. 2ow can we pass ar+ument to a function b0 reference instea$ of pass b0 value' Ans: In -ava, we can pass argument to a function only by value and not by reference. (3. 2ow an obHect is serialiIe$ in Hava' Ans: In -ava, to convert an ob-ect into byte stream by serialiGation, an interface with the name SerialiGable is implemented by the class. All ob-ects of a class implementing serialiGable interface get serialiGed and their state is saved in byte stream. (*. #!en we s!oul$ use serialiIation' Ans: SerialiGation is used when data needs to be transmitted over the network. Fsing serialiGation, ob-ect)s state is saved and converted into byte stream . he byte stream is transferred over the network and the ob-ect is recreated at destination. (5. Is it compulsor0 for a Tr0 Jlock to be followe$ b0 a %atc! Jlock in Java for K-ception !an$lin+' Ans: ry block needs to be followed by either #atch block or %inally block or both. Any e0ception thrown from try block needs to be either caught in the catch block or else any specific tasks to be performed before code abortion are put in the %inally block. (.. Is t!ere an0 wa0 to skip 5inall0 block of e-ception even if some e-ception occurs in t!e e-ception block' Ans: If an e0ception is raised in ry block, control passes to catch block if it e0ists otherwise to finally block. %inally block is always e0ecuted when an

e0ception occurs and the only way to avoid e0ecution of any statements in %inally block is by aborting the code forcibly by writing following line of code at the end of try block: 4-ava5 System.e0it6<27 49-ava5 (7. #!en t!e constructor of a class is invoke$' Ans: he constructor of a class is invoked every time an ob-ect is created with new keyword. %or e0ample, in the following class two ob-ects are created using new keyword and hence, constructor is invoked two times. 4-ava5 public class constBe0ample 8 constBe0ample62 8 System.out.println6>Inside constructorE27 : "ublic static void main6String args452 8 constBe0ample c!;new constBe0ample627 constBe0ample c&;new constBe0ample627 : : 49-ava5 (3. %an a class !ave multiple constructors' Ans: Hes, a class can have multiple constructors with different parameters. +hich constructor gets used for ob-ect creation depends on the arguments passed while creating the ob-ects. (4. %an we overri$e static met!o$s of a class' Ans: +e cannot override static methods. Static methods belong to a class and not to individual ob-ects and are resolved at the time of compilation 6not at runtime2..ven if we try to override static method,we will not get an complitaion error,nor the impact of overriding when running the code. 30. In t!e below e-ample7 w!at will be t!e output'

4-ava5 public class superclass 8 public void displayJesult62 8 System.out.println6>"rinting from superclassE27 : : public class subclass e0tends superclass 8 public void displayJesult62 8 System.out.println6>(isplaying from sub#lassE27 super.displayJesult627 : public static void main6String args452 8 subclass ob-;new subclass627 ob-.displayJesult627 : : 49-ava5 "ns: /utput will be: (isplaying from subclass (isplaying from superclass 31. Is &trin+ a $ata t0pe in Hava' Ans: String is not a primitive data type in -ava. +hen a string is created in -ava, it)s actually an ob-ect of Java.1ang.String class that gets created. After creation of this string ob-ect, all built-in methods of String class can be used on the string ob-ect. 3(. In t!e below e-ample7 !ow man0 &trin+ LbHects are create$' 4-ava5 String s!;EI am Java .0pertE7 String s&;EI am # .0pertE7 String s';EI am Java .0pertE7 49-ava5

Ans: In the above e0ample, two ob-ects of Java.1ang.String class are created. s! and s' are references to same ob-ect. 33. #!0 &trin+s in Java are calle$ as Immutable' Ans: In -ava, string ob-ects are called immutable as once value has been assigned to a string, it can)t be changed and if changed, a new ob-ect is created. In below e0ample, reference str refers to a string ob-ect having value >Aalue oneE. 4-ava5 String str;EAalue /neE7 49-ava5 +hen a new value is assigned to it, a new String ob-ect gets created and the reference is moved to the new ob-ect. 4-ava5 str;ECew AalueE7 49-ava5 3*. #!at)s t!e $ifference between an arra0 an$ Mector' Ans: An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types. 35. #!at is multi-t!rea$in+' Ans: $ulti threading is a programming concept to run multiple tasks in a concurrent manner within a single program. hreads share same process stack and running in parallel. It helps in performance improvement of any program. 3.. #!0 Nunnable Interface is use$ in Java' Ans: Junnable interface is used in -ava for implementing multi threaded applications. Java.1ang.Junnable interface is implemented by a class to support multi threading. 37. #!at are t!e two wa0s of implementin+ multi-t!rea$in+ in Java' Ans: $ulti threaded applications can be developed in Java by using any of the following two methodologies:

!. =y using Java.1ang.Junnable Interface. #lasses implement this interface to enable multi threading. here is a Jun62 method in this interface which is implemented. &. =y writing a class that e0tend Java.1ang. hread class. 33. #!en a lot of c!an+es are require$ in $ata7 w!ic! one s!oul$ be a preference to be use$' &trin+ or &trin+Juffer' Ans: Since String=uffers are dynamic in nature and we can change the values of String=uffer ob-ects unlike String which is immutable, it)s always a good choice to use String=uffer when data is being changed too much. If we use String in such a case, for every data change a new String ob-ect will be created which will be an e0tra overhead. 34. #!at)s t!e purpose of usin+ Jreak in eac! case of &witc! &tatement' Ans: =reak is used after each case 6e0cept the last one2 in a switch so that code breaks after the valid case and doesn)t flow in the proceeding cases too. If break isn)t used after each case, all cases after the valid case also get e0ecuted resulting in wrong results. *0. 2ow +arba+e collection is $one in Java' Ans: In -ava, when an ob-ect is not referenced any more, garbage collection takes place and the ob-ect is destroyed automatically. %or automatic garbage collection -ava calls either System.gc62 method or Juntime.gc62 method. *1. 2ow we can e-ecute an0 co$e even before main met!o$' Ans: If we want to e0ecute any statements before even creation of ob-ects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get e0ecuted once at the time of loading the class even before creation of ob-ects in the main method. *(. %an a class be a super class an$ a sub-class at t!e same time' ,ive e-ample. Ans: If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time. In the e0ample below, continent class is sub-class of world class and it)s super class of country class. 4-ava5

public class world 8 KKK. : public class continenet e0tends world 8 KKKK : public class country e0tends continent 8 KKKKKKK. : 49-ava5 *3. 2ow obHects of a class are create$ if no constructor is $efine$ in t!e class' Ans: .ven if no e0plicit constructor is defined in a -ava class, ob-ects get created successfully as a default constructor is implicitly used for ob-ect creation. his constructor has no parameters. **. In multi-t!rea$in+ !ow can we ensure t!at a resource isn)t use$ b0 multiple t!rea$s simultaneousl0' Ans: In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchroniGation. Fsing synchroniGed keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it. *5. %an we call t!e constructor of a class more t!an once for an obHect' Ans: #onstructor is called automatically when we create an ob-ect using new keyword. It)s called only once for an ob-ect at the time of ob-ect creation and hence, we can)t invoke the constructor again for an ob-ect after its creation. *.. T!ere are two classes name$ class" an$ classJ. Jot! classes are in t!e same packa+e. %an a private member of class" can be accesse$ b0 an obHect of classJ' Ans: "rivate members of a class aren)t accessible outside the scope of that class and any other class even in the same package can)t access them. *7. %an we !ave two met!o$s in a class wit! t!e same name'

Ans: +e can define two methods in a class with the same name but with different number9type of parameters. +hich method is to get invoked will depend upon the parameters passed. %or e0ample in the class below we have two print methods with same name but different parameters. (epending upon the parameters, appropriate one will be called: 4-ava5 public class method.0ample 8 public void print62 8 System.out.println6>"rint method without parameters.E27 : public void print6String name2 8 System.out.println6>"rint method with paramterE27 : public static void main6String args452 8 method.0ample ob-!;new method.0ample627 ob-!.print627 ob-!.print6>00E27 : : 49-ava5 *3. 2ow can we make cop0 of a Hava obHect' Ans: +e can use the concept of cloning to create copy of an ob-ect. Fsing clone, we create copies with the actual state of an ob-ect. #lone62 is a method of #loneable interface and hence, #loneable interface needs to be implemented for making ob-ect copies. *4. #!at)s t!e benefit of usin+ in!eritance' Ans: Ley benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. "olymorphism 6.0tensibility 2 is another great benefit which allow new functionality to be introduced without effecting e0isting derived classes. 50. #!at)s t!e $efault access specifier for variables an$ met!o$s of a class'

Ans: (efault access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package,not outside the package. 51. ,ive an e-ample of use of Fointers in Java class. Ans: here are no pointers in Java. So we can)t use concept of pointers in Java. 5(. 2ow can we restrict in!eritance for a class so t!at no class can be in!erite$ from it' Ans: If we want a class not to be e0tended further by any class, we can use the keyword 5inalwith the class name. In the following e0ample, Stone class is %inal and can)t be e0tend 4-ava5 MpreNMemN M9emNpublic %inal #lass Stone 8 99 #lass methods and Aariables : 49-ava5 53. #!at)s t!e access scope of Frotecte$ "ccess specifier' Ans: +hen a method or a variable is declared with "rotected access specifier, it becomes accessible in the same class,any other class of the same package as well as a sub-class. Oo$ifier %lass Y Y Y Y Y Y Y N Facka+e Y Y N N &ubclass Y N N N #orl$

public protected
no modifier

private

Access Levels 5*. #!at)s $ifference between &tack an$ ueue'

Ans: Stack and Oueue both are used as placeholder for a collection of data. he primary difference between a stack and a ,ueue is that stack is based on 1ast in %irst out 61I%/2 principle while a ,ueue is based on %I%/ 6%irst In %irst /ut2 principle. 55. In Hava7 !ow we can $isallow serialiIation of variables' Ans: If we want certain variables of a class not to be serialiGed, we can use the keywordtransient while declaring them. %or e0ample, the variable transBvar below is a transient variable and can)t be serialiGed: 4-ava5 public class transient.0ample 8 private transient transBvar7 99 rest of the code : 49-ava5 5.. 2ow can we use primitive $ata t0pes as obHects' Ans: "rimitive data types like int can be handled as ob-ects by the use of their respective wrapper classes. %or e0ample, Integer is a wrapper class for primitive data type int. +e can apply different methods to a wrapper class, -ust like any other ob-ect. 57. #!ic! t0pes of e-ceptions are cau+!t at compile time' Ans: #hecked e0ceptions can be caught at the time of program compilation. #hecked e0ceptions must be handled by using try catch block in the code in order to successfully compile the code. 53. Gescribe $ifferent states of a t!rea$.

Ans: A thread in Java can be in either of the following states: Read : !hen a thread is created" it#s in Read state$ Running: A thread currentl %eing e&ecuted is in running state$ !aiting: A thread waiting for another thread to free certain resources is in waiting state$ 'ead: A thread which has gone dead after e&ecution is in dead state$

54. %an we use a $efault constructor of a class even if an e-plicit constructor is $efine$' Ans: Java provides a default no argument constructor if no e0plicit constructor is defined in a Java class. =ut if an e0plicit constructor has been defined, default constructor can)t be invoked and developer can use only those constructors which are defined in the class. .0. %an we overri$e a met!o$ b0 usin+ same met!o$ name an$ ar+uments but $ifferent return t0pes' Ans: he basic condition of method overriding is that method name, arguments as well as return type must he e0actly same as is that of the method being overridden. 3ence using a different return type doesn)t override a method. .1.#!at will be t!e output of followin+ piece of co$e' 4-ava5 public class operator.0ample 8 public static void main6String args452 8 int 0;*7 System.out.println60PP27 : : 49-ava5 Ans: In this case postfi0 PP operator is used which first returns the value and then increments. 3ence it)s output will be *. .1. " person sa0s t!at !e compile$ a Hava class successfull0 wit!out even !avin+ a main met!o$ in it' Is it possible' Ans: main method is an entry point of Java class and is re,uired for e0ecution of the program however7 a class gets compiled successfully even if it doesn)t have a main method. It can)t be run though. .(. %an we call a non-static met!o$ from insi$e a static met!o$' Ans: Con-Static methods are owned by ob-ects of a class and have ob-ect level scope and in order to call the non-Static methods from a static block 6like

from a static main method2, an ob-ect of the class needs to be created first. hen using ob-ect reference, these methods can be invoked. .3. #!at are t!e two environment variables t!at must be set in or$er to run an0 Java pro+rams' Ans: Java programs can be e0ecuted in a machine only once following two environment variables have been properly set: ($ )A*+ varia%le ,$ -LA..)A*+ varia%le .*. %an variables be use$ in Java wit!out initialiIation' Ans: In Java, if a variable is used in a code without prior initialiGation by a valid value, program doesn)t compile and gives an error as no default value is assigned to variables in Java. .5. %an a class in Java be in!erite$ from more t!an one class' Ans: In Java, a class can be derived from only one class and not from multiple classes. $ultiple inheritances is not supported by Java. ... %an a constructor !ave $ifferent name t!an a %lass name in Java' Ans: #onstructor in Java must have same name as the class name and if the name is different, it doesn)t act as a constructor and compiler thinks of it as a normal method. .7. #!at will be t!e output of Noun$D3.7E an$ %eilD3.7E' Ans: Jound6'.Q2 returns ' while #eil6'.Q2 returns *. .31 %an we use +oto in Java to +o to a particular line' Ans: In Java, there is not goto keyword and -ava doesn)t support this feature of going to a particular labeled line. .4. %an a $ea$ t!rea$ be starte$ a+ain' Ans: In -ava, a thread which is in dead state can)t be started again. here is no way to restart a dead thread. 70. Is t!e followin+ class $eclaration correct' "ns1 4-ava5 public abstract final class test#lass 8 99 #lass methods and variables

: 49-ava5 Ans: he above class declaration is incorrect as an abstract class can)t be declared as %inal. 71. Is JG6 require$ on eac! mac!ine to run a Java pro+ram' Ans: J(L is development Lit of Java and is re,uired for development only and to run a Java program on a machine, J(L isn)t re,uired. /nly JJ. is re,uired. 7(. #!at)s t!e $ifference between comparison $one b0 equals met!o$ an$ << operator' Ans: In Java, e,uals62 method is used to compare the contents of two string ob-ects and returns true if the two have same value while ;; operator compares the references of two string ob-ects. In the following e0ample, e,uals62 returns true as the two string ob-ects have same values. 3owever ;; operator returns false as both string ob-ects are referencing to different ob-ects: 4-ava5 public class e,uals est 8 public static void main6String args452 8 String srt!;E3ello +orldE7 String str&;E3ello +orldE7 If 6str!.e,uals6str&22 899 this condition is true System.out.println6>str! and str& are e,ual in terms of valuesE27 : If 6str!;;str&2 8 99 his condition is not true System.out.println6>=oth strings are referencing same ob-ectE27 : .lse 8 99 his condition is true System.out.println6>=oth strings are referencing different ob-ectsE27

: :: 49-ava5 73. Is it possible to $efine a met!o$ in Java class but provi$e it)s implementation in t!e co$e of anot!er lan+ua+e like %' Ans: Hes, we can do this by use of native methods. In case of native method based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like # separately. 7*. 2ow $estructors are $efine$ in Java' Ans: In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the -ob automatically by destroying the ob-ects when no longer referenced. 75. %an a variable be local an$ static at t!e same time' Ans: Co a variable can)t be static as well as local at the same time. (efining a local variable as static gives compilation error. 7.. %an we !ave static met!o$s in an Interface' Ans: Static methods can)t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java. 77. In a class implementin+ an interface7 can we c!an+e t!e value of an0 variable $efine$ in t!e interface' Ans: Co, we can)t change the value of any variable of an interface in the implementing class as all variables defined in the interface are by default public, static and %inal and final variables are like constants which can)t be changed later. 73. Is it correct to sa0 t!at $ue to +arba+e collection feature in Java7 a Hava pro+ram never +oes out of memor0' Ans: .ven though automatic garbage collection is provided by Java, it doesn)t ensure that a Java program will not go out of memory as there is a possibility

that creation of Java ob-ects is being done at a faster pace compared to garbage collection resulting in filling of all the available memory resources. So, garbage collection helps in reducing the chances of a program going out of memory but it doesn)t ensure that. 74. %an we !ave an0 ot!er return t0pe t!an voi$ for main met!o$' Ans: Co, Java class main method can have only void return type for the program to get successfully e0ecuted. Conetheless , if you absolutely must return a value to at the completion of main method , you can use System.e0it6int status2 30. I want to re-reac! an$ use an obHect once it !as been +arba+e collecte$. 2ow it)s possible' Ans: /nce an ob-ect has been destroyed by garbage collector, it no longer e0ists on the heap and it can)t be accessed again. here is no way to reference it again. 31. In Java t!rea$ pro+rammin+7 w!ic! met!o$ is a must implementation for all t!rea$s' Ans: Jun62 is a method of Junnable interface that must be implemented by all threads. 3(. I want to control $atabase connections in m0 pro+ram an$ want t!at onl0 one t!rea$ s!oul$ be able to make $atabase connection at a time. 2ow can I implement t!is lo+ic' Ans: his can be implemented by use of the concept of synchroniGation. (atabase related code can be placed in a method which hs s0nc!roniIe$ keyword so that only one thread can access it at a time. 33. 2ow can an e-ception be t!rown manuall0 b0 a pro+rammer' Ans: In order to throw an e0ception in a block of code manually, t!row keyword is used. hen this e0ception is caught and handled in the catch block. 4-ava5 public void top$ethod628 try8 e0c$ethod627

:catch6$anual.0ception e28 : : public void e0c$ethod8 String name;null7 if6name ;; null28 throw 6new $anual.0ception6>.0ception thrown manually >27 : : 49-ava5 3*. I want m0 class to be $evelope$ in suc! a wa0 t!at no ot!er class Deven $erive$ classE can create its obHects. 2ow can I $o so' Ans: If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its ob-ect will be limited to itself only. 35. 2ow obHects are store$ in Java' Ans: In -ava, each ob-ect when created gets a memory space from a heap. +hen an ob-ect is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new ob-ects. 3.. 2ow can we fin$ t!e actual siIe of an obHect on t!e !eap' Ans: In -ava, there is no way to find out the e0act siGe of an ob-ect on the heap. 37. #!ic! of t!e followin+ classes will !ave more memor0 allocate$' %lass "1 T!ree met!o$s7 four variables7 no obHect %lass J1 5ive met!o$s7 t!ree variables7 no obHect Ans: $emory isn)t allocated before creation of ob-ects. Since for both classes, there are no ob-ects created so no memory is allocated on heap for any class. 33. #!at !appens if an e-ception is not !an$le$ in a pro+ram' Ans: If an e0ception is not handled in a program using try catch blocks, program gets aborted and no statement e0ecutes after the statement which caused e0ception throwing.

34. I !ave multiple constructors $efine$ in a class. Is it possible to call a constructor from anot!er constructor)s bo$0' Ans: If a class has multiple constructors, it)s possible to call one constructor from the body of another one using t!isDE. 40. #!at)s meant b0 anon0mous class' Ans: An anonymous class is a class defined without any name in a single line of code using new keyword. %or e0ample, in below code we have defined an anonymous class in one line of code: 4-ava5 public -ava.util..numeration test$ethod62 8 return new -ava.util..numeration62 8 R/verride public boolean has$ore.lements62 8 99 /(/ Auto-generated method stub return false7 : R/verride public /b-ect ne0t.lement62 8 99 /(/ Auto-generated method stub return null7 : : 49-ava5 41. Is t!ere a wa0 to increase t!e siIe of an arra0 after its $eclaration'

Ans: Arrays are static and once we have specified its siGe, we can)t change it. If we want to use such collections where we may re,uire a change of siGe 6 no of items2, we should prefer vector over array. 4(. If an application !as multiple classes in it7 is it oka0 to !ave a main met!o$ in more t!an one class' Ans: If there is main method in more than one classes in a -ava application, it won)t cause any issue as entry point for any application will be a specific class and code will start from the main method of that particular class only. 43. I want to persist $ata of obHects for later use. #!at)s t!e best approac! to $o so' Ans: he best way to persist data for future use is to use the concept of serialiGation. 4*. #!at is a /ocal class in Java' Ans: In Java, if we define a new class inside a particular block, it)s called a local class. Such a class has local scope and isn)t usable outside the block where its defined. 45. &trin+ an$ &trin+Juffer bot! represent &trin+ obHects. %an we compare &trin+ an$ &trin+Juffer in Java' Ans: Although String and String=uffer both represent String ob-ects, we can)t compare them with each other and if we try to compare them, we get an error. 4.. #!ic! "FI is provi$e$ b0 Java for operations on set of obHects' Ans: Java provides a #ollection A"I which provides many useful methods which can be applied on a set of ob-ects. Some of the important classes provided by #ollection A"I include Array1ist, 3ash$ap, reeSet and ree$ap. 47. %an we cast an0 ot!er t0pe to Joolean T0pe wit! t0pe castin+' Ans: Co, we can neither cast any other primitive type to =oolean data type nor can cast =oolean data type to any other primitive data type. 43. %an we use $ifferent return t0pes for met!o$s w!en overri$$en' Ans: he basic re,uirement of method overriding in Java is that the overridden method should have same name, and parameters.=ut a method

can be overridden with a different return type as long as the new return type e0tends the original. %or e0ample , method is returning a reference type. #lass = e0tends A8 A method6int 028 99original method : = method6int 028 99overridden method : : 44. #!at)s t!e base class of all e-ception classes' Ans: In Java, Java./an+.t!rowable is the super class of all e0ception classes and all e0ception classes are derived from this base class. 100. #!at)s t!e or$er of call of constructors in in!eritiance' Ans: In case of inheritance, when a new ob-ect of a derived class is created, first the constructor of the super class is invoked and then the constructor of the derived class is invoked.

*he /uestions %elow are e&amples of what a 0ava programmer can e&pect in a technical interview$

1. What does the static keyword mean, and where can it be used?
static

can %e used in four wa s: varia%les are shared % the entire class" not a specific instance 1unli2e normal mem%er varia%les3 static methods are also shared % the entire class static classes are inner classes that aren#t tied to their enclosing classes static can %e used around a %loc2 of code in a class to specif code that runs when the virtual machine is first started up" %efore instances of the class are created$
static

2. How do you deal with dependency issues?


*his /uestion is purposel am%iguous$ 4t can refer to solving the dependenc injection pro%lem 15uice is a standard tool to help3$ 4t can also refer to project dependencies 6 using e&ternal" third7part li%raries$ *ools li2e 8aven and 5radle help manage them$ You should consider learning more a%out 8aven as a wa to prepare for this /uestion$

3. You want to create a simple class that just has three member variables. ell me how you!d do this.
*his pro%lem seems simple at first" and creating such a simple class is covered in classes li2e )rogramming 0ava for Beginners$ But an e&perienced programmer will recogni9e that it#s necessar to 2now how to correctl override the hash-ode13 and e/uals13 methods 1using" for e&ample" :/ualsBuilder and +ash-odeBuilder" in the Apache -ommons li%rar 3$

". What does synchronized do? ell me how to use it to set a variable just one without any race conditions?
synchronized sa s that a method has to hold the o%ject#s loc2 to e&ecute$ 4f used a %loc2" li2e synchronized (obj) { ... }" it will gra% the loc2 of obj %efore

around

e&ecuting that %loc2$ -lasses li2e )rogramming 0ava for Beginners and 0ava ;undamentals 4 and 44 will provide a refresher$

#. What is type erasure?


* pe erasure is a 0<8 phenomenon that means that the runtime has no 2nowledge of the t pes of generic o%jects" li2e List<Integer> 1the runtime sees all List o%jects as having the same t pe" List<Object>3$ *he topic of t pe erasure is covered in Advanced 0ava )rogramming$

$. When and why are %etters and setters important?


!hile an advanced 0ava class covers the topic" the 2e factor to 2now for interviews is that setters and getters can %e put in interfaces and can hide implementation details" so that ou don#t have to ma2e mem%er varia%les pu%lic 1which ma2es our class dangerousl %rittle3$

&. What are the di''erences between (ap, Hashtable, Hash(ap, ree(ap, )oncurrentHash(ap, *inkedHash(ap?

8ap is an interface for a 2e 7value map +ash8ap is a 8ap that uses a hash ta%le for its implementation +ashta%le is a s nchroni9ed version of +ash8ap

*ree8ap uses a tree to implement a map -oncurrent+ash8ap allows for multiple threads to access it at the same time safel Lin2ed+ash8ap preserves the iteration order that things were inserted in 1others don#t provide a fi&ed iteration order3

A deeper discussion of the differences can %e found in Advanced 0ava )rogramming$

+. What are the di''erences between inter'aces, abstract classes, classes, and instances?

4nterfaces are essentiall a list of methods that implementations must possess" %ut have no code or mem%er varia%les A%stract classes cannot %e instantiated" %ut can contain varia%les" implemented methods" and unimplemented methods -lasses contain varia%les and implemented methods onl " and can %e instantiated 4nstances 1or o%jects3 are specific e&amples of a particular class$

,. -' you needed to provide a ./- 'or your 0ava pro%ram, how would you %o about it?
*here are a lot of options" from we% apps to local applications$ =suall " interviewers mean .wing or other 5=4 tool2its with a /uestion li2e this$ 4t ma %e worth going through a course on 0ava .wing )rogramming %efore an interview$

11. How do you test your code?


You should tal2 a%out our e&perience using li%raries li2e 0=nit" 8oc2ito" and .elenium$ :ven if ou don#t have e&tensive 2nowledge a%out testing" %eing a%le to tal2 a%out the li%raries is a good first step$ *est7'riven7'evelopment 1*''3 is ver popular these da s" and an e&perience here would also %e good to tal2 a%out$ *here are courses on *est 'riven 'evelopment in 0ava which can %ring ou up to speed$

he 2asics
1 !hat is data mining and how can it %e used> "1 'ata mining refers to an procedure for collecting" anal 9ing" and summari9ing the contents of a data%ase$ 4t can %e used to judge the success of a %usiness" mar2eting campaigns" and to forecast future trends$

1 !hat is data%ase normali9ation and wh is it done> "1 *his is the process of organi9ing data in a data%ase efficientl " and it is done to ma2e sure that connections and dependencies %etween data ma2e sense" and to get rid of redundant data$

1 !hat are fact ta%les> "1 *a%les which trac2 the progress of a certain process or activit 7 the primar ta%les of data%ases$

1 !hat are attri%utes> "1 An attri%ute is a column in a ta%le$

1 !hat does .?L stand for" and what is it used for> "1 .?L stands for structured /uer language" used with relational data%ases$ 4t is used to /uer " update" and retrieve the contents of data%ases$

@@-hec2 out this online %eginners tutorial in 8 .?L@@

1 !hat does R'8B. stand for" and what does it do> "1 Relational data%ase management s stems are the %asis of .?L" and the are used to manage the data%ase and intelligentl store data in related rows and columns with identifiers and inde&es$

1 !hat do constraints do> !hat are the t pes of constraints> "1 -onstraints are used to prevent the data%ase from losing internal and e&ternal integrit $ *he t pes are: chec2" not null" uni/ue" primar 2e " and foreign 2e $

1 'escri%e the difference %etween primar 2e s and foreign 2e s$ "1 )rimar 2e s are at least one column in a ta%le that identif specific rows in that same ta%le$ ;oreign 2e s are columns in a ta%le that identif rows in a different ta%le$

@@Learn more a%out .?L servers and data%ase maintenance with this online tutorial@@

3uestions about (y43*


1 !hat are the commands to start and stop 8 .?L> "1 7N:* .*AR* 8 .?L and 7N:* .*O) 8 .?L

1 !hat is the 8 .?L server default port> "1 *he default port is AA0B$

1 !hat is the 8 .?L command to get a list of user accounts> "1 7.:L:-* =ser ;RO8 m s/l$user

1 !hat is the 8 .?L command to concatenate a string of characters> "1 7-ON-A*1string(" string," stringA3

@@8aster 8 .?L and data%ase concepts with this online course@@

1 !hat is the 8 .?L command to delete a column> "1 -AL*:R *ABL: ta%leCname 'RO) columnCname

3uestions about 5racle


1 !hat does each num%er in the version num%er of an Oracle release stand for> "1 ;irst num%er D major data%ase release num%er$ .econd D data%ase maintenance release num%er$ *hird D application server release num%er$ ;ourth D component specific release num%er$ ;ifth D platform specific release num%er$

1 !hat does concurrenc refer to> "1 -oncurrenc refers to when multiple different users can access the same data at the same time$

1 !hat Large o%ject t pes are used in Oracle> "1 *he -lo% and Blo% o%ject t pes are used$

1 !hat is B-)> "1 B-) is the %ul2 cop tool" which allows ou to /uic2l and easil import and e&port large amounts of data to and from ta%les$

@@Learn the fundamentals of the Oracle data%ase s stem with this online course@@

1 !hat is the difference %etween privileges and grants> "1 )rivileges are given to users and give them the right to e&ecute certain commands" li2e the right to connect to a certain data%ase$ 5rants are given to particular o%jects % their owners" and allow them to %e accessed in certain wa s$

Top 20 Java technical interview questions and answers for experienced Java developers

If 0ou are an interviewer 77 it reall

pa s to as2 well rounded /uestions to judge the real e&perience of the candidate as opposed to just rel ing on the num%er of ears$

If 0ou are an interviewee 77 You have no control over what /uestions will
%e as2ed in 0ava jo% interviews" %ut there are a few 0ava interview /uestions that are ver fre/uentl as2ed in jo% interviews" and it reall pa s to prepare for those /uestions$ +ere are a few such /uestions$ *his is %ased on some of m recent interviews$ Brushing up on these answers will %oost our success rate in 0ava jo% interviews$ *he focus is on Hu$+in+ 0our e-perience$ .o" go through our resume and reflect %ac2 on our hands7on e&perience$ 8an of these answers will also serve ou well in selling our technical strengths to open ended /uestions li2e 77 tell me about 0ourself' " w!0 $o 0ou like software $evelopment'" w!en reviewin+ ot!ersP work7 w!at $o 0ou look for'" w!at was 0our most si+nificant accomplis!ment'" etc 1$ -an ou descri%e the high level architecture of the application that ou had wor2ed on recentl > or -an ou give a (00 feet %irdEs e e view of the application ou were involved in as a developer or designer> "1$ *he purpose is to judge our overall e&perience$ +ere are a few lin2s that will prepare for this most sought7after /uestion" especiall for the e&perienced professionals$

A to n7tier enterprise 0ava architecture" the 8<-7, design pattern" the distinction %etween ph sical and logical tiers" and the la ered architecture$*he lo+ical tiers shown in the diagrams for the a%ove lin2 are %asicall la ers" and the la ers are used for organi9ing our code$ * pical la ers include Fresentation" Jusiness and Gata D the same as the traditional A7tier model$ But when tal2 a%out la ers" we#re onl tal2ing a%out lo+ical organi9ation of code$ F!0sical tiers however" are onl a%out where the code gets deplo ed and run as war" ear or jar$ .pecificall " tiers are places where la ers are deplo ed and where la ers run$ 4n other words" tiers are the p!0sical $eplo0ment of la0ers$ high level architectural patterns and the pros and cons of each approach$ 'iscusses a num%er different architectual st les li2e OM%" &L"" QI %omponent" NK&Tful $ata composition" 2TO/ $ata composition" Flu+-in arc!itecture" and :vent 'riven Architecture 1KG"3$ Also" covers a sample enterprise architecture" which is a h %rid of a num%er of architectural st les$ 2nowing the difference %etween a component and a service$ -overs the differences %etween components and services and %J" 1-omponent Based Architecture3 <s" &L" 1.ervice Oriented Architecture3$ Also" %riefl covers sin+le pa+e web $esi+n and &%" 1.ervice -omponent Architecture3 =nderstanding of various t pes of application integration st les$ :nterprise applications need to %e integrated with other s stems" and this post covers different integration st les li2e sharing the same data%ase" feed %ased" R)- st le 1e$g$ we% services3" and e&changing 08. messages$ 5ood wor2ing 2nowledge of popular and sought7after technologies and framewor2s li2e 8aven" .pring" +i%ernate" 0.;" etc$ -overs a num%er of tutorials using sought7after framewor2s and technologies li2e li2e .pring" 8aven" 0.;" 0'B-" and R:.*ful we% service$

($ +ow would ou go a%out deciding %etween &L"F base$ web service and NK&Tful we% service> "($ !e% services are ver popular and widel used to integrate disparate s stems$ 4t is imperative to understand the differences" pros" and cons %etween each approach$ Recentl " 4 have %een as2ed these /uestions ver fre/uentl " here is the answer that discusses the pros and cons of .OA) vs$ R:.*ful we% services in detail$ 3$+ow will ou go a%out ensuring that ou %uild a more ro%ust application> or +ow do ou improve /ualit of our application> "3$ *his /uestion is ver popular with the interviewers %ecause the want to hire candidates who write good /ualit application$ +ere are some useful lin2s to prepare for this /uestion$

0ava interview /uestions and answers on code /ualit $ 5ives a high level over view as to things ou can do and tools ou can use to improve code /ualit $ A common popular jo% interview /uestion answered is 77 #!at is t!e $ifference between fake obHects7 mock obHects7 an$ stubs' =nit testing with moc2 o%jects interview /uestions and answers$ *utorial that e&plains how to write JQnit tests with moc2 o%jects using the Oockito and Fower mock framewor2s$ =nit testing .pring 8<- controllers for we% and R:.*ful services with spring7 test7mvc$ *utorial for writing .pring 8<- unit tests$ .elenium and !e% 'river for unit testing 0ava 5=4$ *utorial for writing functional unit tests for we% applications to test displa logic$ +i%ernate 4nterview ?uestions and Answers: integration testing the 'AO la er$ *utorial for unit testing the 'AO la er using hi%ernate$ 0ava 4nterview ?uestions and Answers 7 performance testing our 0ava application$ A high level overview as to how ou can go a%out monitoring performance$ 8an applications face performance issues and this is a ver popular /uestion with the interviewers$ =sing 08eter for performance testing 0ava application$A 08eter tutorial for conducting performance tets

*$ !hat are some of the %est practices regarding .'L-> +ave ou wor2ed in an agile development environment> 'id ou use test driven development and continuous integration> "*$

Fnow the .'L- and the %est practices $ 5ives a high level overview of &G/%$

5: -an ou write code> +ow would ou go a%out implementing $$$$$> "5: You will %e as2ed to write a small function or a program$ *he interviewer will %e loo2ing for things li2e

+ow well ou anal 9e the re/uirements and the solution> As2 relevant /uestions if the re/uirements are not clear$ *hin2 out loud so that the interviewer 2nows that how ou are approaching the pro%lem$*he approach is more important that arriving at the correct solution$ List all possi%le alternatives$ !rite pseudo code$ !rite unit tests$ !here re/uired" %rainstorm with the interviewer$ ;ind wa s to improve our initial solution$ *al2 through thread safet and %est practices where applica%le$

+ere are some lin2s to popular coding /uestions and answers$

0ava coding interview /uestions and answers:$ -overs a num%er of coding /uestions with answers$ *hese are some of the popular coding interview /uestions li2e reversing a string" calculating the ;i%onacci num%er" recursion vs iteration" e/uals versus GG" etc$

B$ +ow would ou go a%out designing a car par2ing station> ".$ Oap out t!e requirements1

*he car par2 needs to cater for different t pes of car par2s li2e regular" handicapped" and compact$ 4t should 2eep trac2 of empt and filled spaces$ 4t should also cater for valet par2ing$

Oap out t!e classes t!at woul$ be require$. =se a =8L class diagram$ +ere are some points to get started$

A -ar)ar2 class to represent a par2ing station$ A )ar2ing.pace can %e an a%stract class or an interface to represent a par2ing space" and Regular)ar2ing.pace" +andicapped)ar2ing.pace" -ompact)ar2ing.pace" etc are su%t pes of a )ar2ing.pace$ *his means a Regular)ar2ing.pace is

a )ar2ing.pace$

A -ar)ar2 !as a 1i$e$ composition3 finite num%er of )ar2ing.paces$ A -ar)ar2 also 2eeps trac2 of all the par2ing spaces and a separate list of all the vacant par2ing spaces$ A <ehicle class uses a 1i$e$ delegation3 )ar2ing.pace$ *he <ehicle class will hold attri%utes using enum classes li2e <ehicle* pe and )ar2ing* pe$ *he

vehicle t pes could %e -ompact" Regular" and +andicapped$ *he par2ing t pes could %e .elf or <alet$ 'epending on the re/uirements" the self or valet t pes could %e designed as su%t pes of the <ehicle class$

7: -an ou design the classes that represent a restaurant> "7: <er popular$ 5ood understanding of LL $esi+n is vital to jo% interview success$ Learn the &L/IG design principles" 2now wh ou favor composition over in!eritance" and $onPt un$er estimate t!e power of co$in+ to interface$

0ava OO 4nterview ?uestions and Answers$ A step7% 7step tutorial e&plaining how ou would go a%out designing our classes$ *he H-ore 0ava -areer :ssentialsH )'; covers more e&amples on .OL4' design principles with wor2ing code$

+ow would ou go a%out identif ing t!rea$ safet0 issues in an application> +ow would ou go a%out identif ing memor0 leaks issues> +ow would ou go a%out identif ing performance issues>" etc to judge our e&perience$ 4 am et to wor2 on a project that didnEt face pro%lems relating to thread safet " memor lea2s" and performance issues$ +ence" it reall pa s to mar2et our s2ills and e&perience in fi&ing issues relating to these common challenges$ 3$ +ow will ou go a%out fi&ing memor lea2s in 0ava> "3$ Again" a ver common pro%lem" and a thorough answer will go a long wa in securing our ne&t 0ava jo%$

'etecting and fi&ing memor lea2 issues in 0ava$ *ools and techni/ues to detect memor lea2s in 0ava$ 8emor profiling in 0ava$ *utorial on memor profiling a 0ava application$

4: +ow will ou go a%out fi&ing performance issues in 0ava> "4:


'etecting performance issues in 0ava$ A %asic tutorial covering 77 how to detect performance issues$ Also" refer to the 08eter tutorials in this %log as to learn how ou can put load on our application to simulate concurrent users$

10: +ow will ou go a%out detecting and fi&ing thread7safet issues in 0ava> "10: 'e%ugging concurrenc issues and fi&ing an t!rea$ starvation7 $ea$ lock" and

contention re/uires s2ills and e&perience to identif and reproduce these hard to resolve issues$ +ere are some techni/ues to detect concurrenc issues$

8anuall reviewing the code for an o%vious thread7safet issues$ *here are static anal sis tools li2e .onar" *hread-hec2" etc for catching concurrenc %ugs at compile7time % anal 9ing their % te code$ List all possi%le causes and add e&tensive log statements and write test cases to prove or disprove our theories$ *hread dumps are ver useful for diagnosing s nchroni9ation pro%lems such as deadloc2s$ *he tric2 is to ta2e I or B sets of thread dumps at an interval of I seconds %etween each to have a log file that has ,I to A0 seconds worth of runtime action$ ;or thread dumps" use 2ill 7A in =ni& and -*RLJBR:AF in !indows$ *here are tools li2e *hread 'ump Anal 9er 1*'A3" .amurai" etc$ to derive useful information from the thread dumps to find where the pro%lem is$ ;or e&ample" .amurai colors idle threads in gre " %loc2ed threads in red" and running threads in green$ You must pa more attention to those red threads$ *here are tools li2e 0'B 1i$e$ 0ava 'eBugger3 where a KwatchL can %e set up on the suspected varia%le$ !hen ever the application is modif ing that varia%le" a thread dump will %e printed$ *here are d namic anal sis tools li2e jstac2 and 0-onsole" which is a 08M compliant 5=4 tool to get a thread dump on the fl $ *he 0-onsole 5=4 tool does have hand features li2e Kdetect deadloc2L %utton to perform deadloc2 detection operations and a%ilit to inspect the threads and o%jects in error states$ .imilar tools are availa%le for other languages as well$

*he part7( covered /uestions 1-10 0avaN0:: 0o% 4nterview ?uestions and Answers %ased on m e&perience" and this covers /uestions 11-13 for e&perienced 0avaN0:: professionals$ 8ost applications %uilt toda are we% %ased and it is vital that ou have a good handle on the we% paradigms$ 11$ +**) is a stateless protocol" so how do ou maintain state> +ow do ou store user data %etween re/uests> 4s it a good thing to maintain state> "11 $ *his is a commonl as2ed interview /uestion$ *he Khttp protocolL is a stateless request9response base$ protocol$ You can retain the state information %etween different page re/uests as follows: 2TTF &ession$ A session identifies the re/uests that originate from the same %rowser during the period of conversation$ All the servlets can share the same session$ *he 0.:..4ON4' is generated % the server and can %e passed to client through coo2ies" =RL re7writing 1if coo2ies are turned off3 or %uilt7in ..L mechanism$ -are should %e

ta2en to minimi9e si9e of o%jects stored in session and o%jects stored in session should %e seriali9a%le$ 4n a 0ava servlet the session can %e o%tained as follows: > ( , A O I B 7 P Q ( 0
ttp!ession session " re#uest.get!ession(true)$ %%returns a current session or a ne& session %%'o put%get a value in%(ro) the session *a)e na)e " ne& *a)e(+,eter-)$ session.set.ttribute(+/irstna)e-0 na)e)$ %%session.put1alue(2) is deprecated as o( 3.3 session.get.ttribute(+/irstna)e-)$%%get a value. session.get1alue(2) is deprecated %%I( a session is no longer re#uired e.g. user has logged out0 etc then it can be invalidated. session.invalidate()$

> (<input na)e"4-/irstna)e-4 value"4-,eter-4 type"4-hidden-4> ,<input na)e"4-Lastna)e-4 value"4-!)ith-4 type"4-hidden-4> 2i$$en 5iel$s on the pages can maintain state and the are not visi%le on the %rowser$ *he server treats %oth hidden and non7hidden fields the same wa $ QN/ re-writin+ will append the state information as a /uer string to the =RL$ *his should not %e used to maintain private or sensitive information$ > ( ttp5%%6y!erver57878%6y!ervlet9/irstna)e",eter:Lastna)e"!)ith

%ookies: A coo2ie is a piece of te&t that a !e% server can store on a user#s hard dis2$ -oo2ies allow a we%site to store information on a user#s machine and later retrieve it$ *hese pieces of information are stored as name7value pairs$ *he coo2ie data moves in the following manner: $ Are states %ad> if es" wh > "$ .tate isn#t %ad" it#s a necessit $ But favor stateless architecture for the num%er of reasons descri%ed %elow$

You should AL!AY. ma2e our s stems not onl as simple as possible" %ut also as scalable as possible$ 4n a clustered or load %alanced environment with multiple servers" maintainig of states re/uires the user to alwa s return to the same server using stic2 sessions or else the whole s stem %rea2s down$ *he answer to this pro%lem is using stic2 sessions which force the load %alancer to send traffic for a given user to the same server ever time$ *he LB is hardl %alancing load if it can#t decide who gets the traffic$ *here are other more complicated methods for sharing sessions across multiple servers via true clustering" %ut getting this right is more complicated and time consuming$ .tate can also %e pro%lematic from a securit point of view due to sharing the state %etween the client and server$ *here are methods around this pro%lem using encr ption and other techni/ues" %ut again can complicate our solution$

*he single page rich we% pages ma2ing a num%er of R:.*;ul we% services via aja& re/uests is a ver popular architecture$ 8a2ing server side R:.*ful we% services stateless is a central tenant of R:.*$ A trul0 stateless NK&Tful web service is not onl incredi%l fle&i%le and scala%le thing" %ut also ta2es responsi%ilit for handling securit and deciding who can access what in the s stem$ .ince there is ver little Hunder the covers stuffH happening to tr to ma2e this stuff KeasierL" ou are free to implement securit however ma2es sense for our s stem$ 1(: !hat is our understanding of the following terms $$$ forwar$" re$irect 1a2a sendRedirect3" and post-back> "1(: 5orwar$

a forward is performed internall % the servlet$ *he %rowser is completel unaware that it has ta2en place" so its original =RL remains intact$ You can set re/uest attri%utes from the forwarding re/uest 1e$g$ s servlet3 to the resource to which it is forwarded 1e$g$ 0.)3$

Ne$irect

A redirect is a two step process" where the we% application instructs the %rowser to fetch a second =RL" which differs from the original$ A %rowser reload of the second =RL will not repeat the original re/uest" %ut will rather fetch the second =RL$ *his ma2es the second resource lin2 %oo2 mar2a%le$ A redirect can %e marginall slower than a forward as it re/uires two %rowser re/uests as opposed to one with the forward$ An attri%utes placed in the original re/uest scope are not availa%le to the second re/uest" since it is a new re/uest$

Fost-back

*he +**) ver% )O.* is used to send data %ac2 to the server with 0.ON data in the %od " with M8L" or with form fields$ A post%ac2 is when ou send data via )O.* http ver% %ac2 to the server$ 4n other words" ou are )O.*ing data %ac2 to the server$ *he term H%ac2H reall means that ou retrieved the page initiall with a 5:* ver% to show the user the RformS element that has RinputS fields for them to interact with" and at the end ouEre sending data %ac2$ .o" A )ostBac2 is a )O.* re/uest for a page that is not the first re/uest$

8ore %asic we% development /uestions are discussed with diagrams$ .pring framewor2 is ver popular and can %e used as an 4o- container" 8<-, we% application framewor2" 0'B- and 08. template" and so on$ .o ou need to %e prepared with %asic .pring jo% interview /uestions$ 13:!hat are the different wa s can ou wire up our dependencies using .pring> "13: A different wa s$ You can com%ine all A wa s$

=sing an M8L %ased application conte&t file as demonstrated here in .*:) A$ =sing annotations RNesource" R%omponent" and R&ervice as descri%ed here" including the R"utowire$ annotaion$ =sing the 0ava config using the annotations R%onfi+uration and RJean$ *his is demonstrated via wiring up Apache -amel routing using 0ava %ased .pring configuration as shown in step , to see how it is done$ *his also shows TAutowired" T.ervice" and TResource annotations in action$

. -an ou descri%e the following %ean concepts ($ ,$ A$ O$ .pring managed %eans life c cles$ Bootsrapping the initial .pring %ean$ !hat is a %ean factor > +ow would ou create an application conte&t from a we% application>

". *he answers are clearl e&plained in this .pring training tutorial$ . -an ou list some real life scenarios where ou will use .pring AO)> ". 1. You can use the Oet!o$ "LF interceptors for dead loc2 retr and logging$ Occasionall " ou get deadloc2s in data%ases and ou data%ase management s stems resolves deadloc2s % a%orting a transaction$ *hese transactions can %e retried with the help of .pring AO) method interceptors$ *his is clearl e&plained in .tep A under +ow do ou wire up transaction manager> ($ Another area is service retr service in general where an failed remote service calls can %e retried at a certain interval sa ever (0 seconds for A times$ 3. for auditing purposes$ 3. .pring itself uses aspects for things li2e transaction management" securit " and caching$ .ta tuned for more 0ava 4nterview ?uestions and Answers for e&perienced developers$

Java /an+ua+e
($ !hat is a platform>

uestions

A platform is the hardware or software environment in which a program runs$ 8ost platforms can %e descri%ed as a com%ination of the operating s stem and hardware" li2e !indows ,000NM)" Linu&" .olaris" and 8acO.$ ,$ !hat is the main difference %etween 0ava platform and other platforms> *he 0ava platform differs from most other platforms in that itEs a software7onl platform that runs on top of other hardware7%ased platforms$ *he 0ava platform has two components: ($ *he 0ava <irtual 8achine 10ava <83 ,$ *he 0ava Application )rogramming 4nterface 10ava A)43

A$ !hat is the 0ava <irtual 8achine>

*he 0ava <irtual 8achine is a software that can %e ported onto various hardware7%ased platforms$ O$ !hat is the 0ava A)4> *he 0ava A)4 is a large collection of read 7made software components that provide man useful capa%ilities" such as graphical user interface 15=43 widgets$ I$ !hat is the pac2age> *he pac2age is a 0ava namespace or part of 0ava li%raries$ *he 0ava A)4 is grouped into li%raries of related classes and interfacesU these li%raries are 2nown as pac2ages$ B$ !hat is native code> *he native code is code that after ou compile it" the compiled code runs on a specific hardware platform$ 7$ 4s 0ava code slower than native code> Not reall $ As a platform7independent environment" the 0ava platform can %e a %it slower than native code$ +owever" smart compilers" well7tuned interpreters" and just7in7time % tecode compilers can %ring performance close to that of native code without threatening porta%ilit $ P$ !hat is the seriali9ation> *he seriali9ation is a 2ind of mechanism that ma2es a class or a %ean persistence % having its properties or fields and state information saved and restored to and from storage$ Q$ +ow to ma2e a class or a %ean seriali9a%le> B implementing either the java$io$.eriali9a%le interface" or the java$io$:&ternali9a%le interface$ As long as one class in a classEs inheritance hierarch implements .eriali9a%le or :&ternali9a%le" that class is seriali9a%le$ (0$ +ow man methods in the .eriali9a%le interface> *here is no method in the .eriali9a%le interface$ *he .eriali9a%le interface acts as a mar2er" telling the o%ject seriali9ation tools that our class is seriali9a%le$ (($ +ow man methods in the :&ternali9a%le interface>

*here are two methods in the :&ternali9a%le interface$ You have to implement these two methods in order to ma2e our class e&ternali9a%le$ *hese two methods are read:&ternal13 and write:&ternal13$ (,$ !hat is the difference %etween .eriali9al%le and :&ternali9a%le interface> !hen ou use .eriali9a%le interface" our class is seriali9ed automaticall % default$ But ou can override writeO%ject13 and readO%ject13 two methods to control more comple& o%ject seraili9ation process$ !hen ou use :&ternali9a%le interface" ou have a complete control over our classEs seriali9ation process$ (A$ !hat is a transient varia%le> A transient varia%le is a varia%le that ma not %e seriali9ed$ 4f ou donEt want some field to %e seriali9ed" ou can mar2 that field transient or static$ (O$ !hich containers use a %order la out as their default la out> *he !indow" ;rame and 'ialog classes use a %order la out as their default la out$ (I$ +ow are O%server and O%serva%le used> O%jects that su%class the O%serva%le class maintain a list of o%servers$ !hen an O%serva%le o%ject is updated it invo2es the update13 method of each of its o%servers to notif the o%servers that it has changed state$ *he O%server interface is implemented % o%jects that o%serve O%serva%le o%jects$ (B$ !hat is s nchroni9ation and wh is it important> !ith respect to multithreading" s nchroni9ation is the capa%ilit to control the access of multiple threads to shared resources$ !ithout s nchroni9ation" it is possi%le for one thread to modif a shared o%ject while another thread is in the process of using or updating that o%jectEs value$ *his often causes dirt data and leads to significant errors$ (7$ !hat are s nchroni9ed methods and s nchroni9ed statements> . nchroni9ed methods are methods that are used to control access to an o%ject$ A thread onl e&ecutes a s nchroni9ed method after it has ac/uired the loc2 for the methodEs o%ject or class$ . nchroni9ed statements are similar to s nchroni9ed methods$ A s nchroni9ed statement can onl %e e&ecuted after a thread has ac/uired the loc2 for the o%ject or class referenced in the s nchroni9ed statement$ (P$ !hat are three wa s in which a thread can enter the waiting state>

A thread can enter the waiting state % invo2ing its sleep13 method" % %loc2ing on 4NO" % unsuccessfull attempting to ac/uire an o%jectEs loc2" or % invo2ing an o%jectEs wait13 method$ 4t can also enter the waiting state % invo2ing its 1deprecated3 suspend13 method$ (Q$ -an a loc2 %e ac/uired on a class> Yes" a loc2 can %e ac/uired on a class$ *his loc2 is ac/uired on the classEs -lass o%ject$ ,0$ !hatEs new with the stop13" suspend13 and resume13 methods in 0'F ($,> *he stop13" suspend13 and resume13 methods have %een deprecated in 0'F ($,$ ,($ !hat is the preferred si9e of a component> *he preferred si9e of a component is the minimum component si9e that will allow the component to displa normall $ ,,$ !hat method is used to specif a containerEs la out> *he setLa out13 method is used to specif a containerEs la out$ ,A$ !hich containers use a ;lowLa out as their default la out> *he )anel and Applet classes use the ;lowLa out as their default la out$ ,O$ !hat is thread> A thread is an independent path of e&ecution in a s stem$ ,I$ !hat is multithreading> 8ultithreading means various threads that run in a s stem$ ,B$ +ow does multithreading ta2e place on a computer with a single -)=> *he operating s stemEs tas2 scheduler allocates e&ecution time to multiple tas2s$ B /uic2l switching %etween e&ecuting tas2s" it creates the impression that tas2s e&ecute se/uentiall $ ,7$ +ow to create multithread in a program> You have two wa s to do so$ ;irst" ma2ing our class He&tendsH Thread class$ .econd" ma2ing our class HimplementsH Runnable interface$ )ut jo%s in a run13 method and call start13 method to start the thread$

,P$ -an 0ava o%ject %e loc2ed down for e&clusive use % a given thread> Yes$ You can loc2 an o%ject % putting it in a Hs nchroni9edH %loc2$ *he loc2ed o%ject is inaccessi%le to an thread other than the one that e&plicitl claimed it$ ,Q$ -an each 0ava o%ject 2eep trac2 of all the threads that want to e&clusivel access to it> Yes$ A0$ !hat state does a thread enter when it terminates its processing> !hen a thread terminates its processing" it enters the dead state$ A($ !hat invo2es a threadEs run13 method> After a thread is started" via its start13 method of the *hread class" the 0<8 invo2es the threadEs run13 method when the thread is initiall e&ecuted$ A,$ !hat is the purpose of the wait13" notif 13" and notif All13 methods> *he wait13"notif 13" and notif All13 methods are used to provide an efficient wa for threads to communicate each other$ AA$ !hat are the high7level thread states> *he high7level thread states are read " running" waiting" and dead$ AO$ !hat is the -ollections A)4> *he -ollections A)4 is a set of classes and interfaces that support operations on collections of o%jects$ AI$ !hat is the List interface> *he List interface provides support for ordered collections of o%jects$ AB$ +ow does 0ava handle integer overflows and underflows> 4t uses those low order % tes of the result that can fit into the si9e of the t pe allowed % the operation$ A7$ !hat is the <ector class>

*he <ector class provides the capa%ilit to implement a growa%le arra of o%jects AP$ !hat modifiers ma %e used with an inner class that is a mem%er of an outer class> A 1non7local3 inner class ma %e declared as pu%lic" protected" private" static" final" or a%stract$ AQ$ 4f a method is declared as protected" where ma the method %e accessed> A protected method ma onl %e accessed % classes or interfaces of the same pac2age or % su%classes of the class in which it is declared$ O0$ !hat is an 4terator interface> *he 4terator interface is used to step through the elements of a -ollection$ O($ +ow man %its are used to represent =nicode" A.-44" =*;7(B" and =*;7P characters> =nicode re/uires (B %its and A.-44 re/uire 7 %its$ Although the A.-44 character set uses onl 7 %its" it is usuall represented as P %its$ =*;7P represents characters using P" (B" and (P %it patterns$ =*;7(B uses (B7%it and larger %it patterns$ O,$ !hat is the difference %etween ielding and sleeping> !hen a tas2 invo2es its ield13 method" it returns to the read state$ !hen a tas2 invo2es its sleep13 method" it returns to the waiting state$ OA$ 4s si9eof a 2e word> *he si9eof operator is not a 2e word$ OO$ !hat are wrapped classes> !rapped classes are classes that allow primitive t pes to %e accessed as o%jects$ OI$ 'oes gar%age collection guarantee that a program will not run out of memor > No" it doesnEt$ 4t is possi%le for programs to use up memor resources faster than the are gar%age collected$ 4t is also possi%le for programs to create o%jects that are not su%ject to gar%age collection OB$ !hat is the difference %etween preemptive scheduling and time slicing>

=nder preemptive scheduling" the highest priorit tas2 e&ecutes until it enters the waiting or dead states or a higher priorit tas2 comes into e&istence$ =nder time slicing" a tas2 e&ecutes for a predefined slice of time and then reenters the pool of read tas2s$ *he scheduler then determines which tas2 should e&ecute ne&t" %ased on priorit and other factors$ O7$ Name -omponent su%classes that support painting$ *he -anvas" ;rame" )anel" and Applet classes support painting$ OP$ !hat is a native method> A native method is a method that is implemented in a language other than 0ava$ OQ$ +ow can ou write a loop indefinitel > for1UU377for loopU while1true377alwa s true" etc$ I0$ -an an anon mous class %e declared as implementing an interface and e&tending a class> An anon mous class ma implement an interface or e&tend a superclass" %ut ma not %e declared to do %oth$ I($ !hat is the purpose of finali9ation> *he purpose of finali9ation is to give an unreacha%le o%ject the opportunit to perform an cleanup processing %efore the o%ject is gar%age collected$ I,$ !hich class is the superclass for ever class$ O%ject IA$ !hat is the difference %etween the Boolean V operator and the VV operator> 4f an e&pression involving the Boolean V operator is evaluated" %oth operands are evaluated$ *hen the V operator is applied to the operand$ !hen an e&pression involving the VV operator is evaluated" the first operand is evaluated$ 4f the first operand returns a value of true then the second operand is evaluated$ *he VV operator is then applied to the first and second operands$ 4f the first operand evaluates to false" the evaluation of the second operand is s2ipped$ Operator V has no chance to s2ip %oth sides evaluation and VV operator does$ 4f as2ed wh " give details as a%ove$ IO$ !hat is the 5regorian-alendar class>

*he 5regorian-alendar provides support for traditional !estern calendars$ II$ !hat is the .imple*imeWone class> *he .imple*imeWone class provides support for a 5regorian calendar$ IB$ !hich -ontainer method is used to cause a container to %e laid out and redispla ed> validate13 I7$ !hat is the )roperties class> *he properties class is a su%class of +ashta%le that can %e read from or written to a stream$ 4t also provides the capa%ilit to specif a set of default values to %e used$ IP$ !hat is the purpose of the Runtime class> *he purpose of the Runtime class is to provide access to the 0ava runtime s stem$ IQ$ !hat is the purpose of the . stem class> *he purpose of the . stem class is to provide access to s stem resources$ B0$ !hat is the purpose of the finall clause of a tr 7catch7finall statement> *he finall clause is used to provide the capa%ilit to e&ecute code no matter whether or not an e&ception is thrown or caught$ B($ !hat is the Locale class> *he Locale class is used to tailor program output to the conventions of a particular geographic" political" or cultural region$ B,$ !hat must a class do to implement an interface> 4t must provide all of the methods in the interface and identif the interface in its implements clause$ BA$ !hat is an a%stract method> An a%stract method is a method whose implementation is deferred to a su%class$ Or" a method that has no implementation 1an interface of a method3$

BO$ !hat is a static method> A static method is a method that %elongs to the class rather than an o%ject of the class and doesnEt appl to an o%ject or even re/uire that an o%jects of the class have %een instantiated$ BI$ !hat is a protected method> A protected method is a method that can %e accessed % an method in its pac2age and inherited % an su%class of its class$ BB$ !hat is the difference %etween a static and a non7static inner class> A non7static inner class ma have o%ject instances that are associated with instances of the classEs outer class$ A static inner class does not have an o%ject instances$ B7$ !hat is an o%jectEs loc2 and which o%jectEs have loc2s> An o%jectEs loc2 is a mechanism that is used % multiple threads to o%tain s nchroni9ed access to the o%ject$ A thread ma e&ecute a s nchroni9ed method of an o%ject onl after it has ac/uired the o%jectEs loc2$ All o%jects and classes have loc2s$ A classEs loc2 is ac/uired on the classEs -lass o%ject$ BP$ !hen can an o%ject reference %e cast to an interface reference> An o%ject reference %e cast to an interface reference when the o%ject implements the referenced interface$ BQ$ !hat is the difference %etween a !indow and a ;rame> *he ;rame class e&tends !indow to define a main application window that can have a menu %ar$ 70$ !hat do heav weight components mean> +eav weight components li2e A%stract !indow *ool2it 1A!*3" depend on the local windowing tool2it$ ;or e&ample" java$awt$Button is a heav weight component" when it is running on the 0ava platform for =ni& platform" it maps to a real 8otif %utton$ 4n this relationship" the 8otif %utton is called the peer to the java$awt$Button$ 4f ou create two Buttons" two peers and hence two 8otif Buttons are also created$ *he 0ava platform communicates with the 8otif Buttons using the 0ava Native 4nterface$ ;or each and ever component added to the application" there is an additional overhead tied to the local windowing s stem" which is wh these components are called heav weight$ 7($ !hich pac2age has light weight components>

java&$.wing pac2age$ All components in .wing" e&cept 0Applet" 0'ialog" 0;rame and 0!indow are lightweight components$ 7,$ !hat are peerless components> *he peerless components are called light weight components$ 7A$ !hat is the difference %etween the ;ont and ;ont8etrics classes> *he ;ont8etrics class is used to define implementation7specific properties" such as ascent and descent" of a ;ont o%ject$ 7O$ !hat happens when a thread cannot ac/uire a loc2 on an o%ject> 4f a thread attempts to e&ecute a s nchroni9ed method or s nchroni9ed statement and is una%le to ac/uire an o%jectEs loc2" it enters the waiting state until the loc2 %ecomes availa%le$ 7I$ !hat is the difference %etween the ReaderN!riter class hierarch and the 4nput.treamNOutput.tream class hierarch > *he ReaderN!riter class hierarch is character7oriented" and the 4nput.treamNOutput.tream class hierarch is % te7oriented$ 7B$ !hat classes of e&ceptions ma %e caught % a catch clause> A catch clause can catch an e&ception that ma %e assigned to the *hrowa%le t pe$ *his includes the :rror and :&ception t pes$ 77$ !hat is the difference %etween throw and throws 2e words> *he throw 2e word denotes a statement that causes an e&ception to %e initiated$ 4t ta2es the :&ception o%ject to %e thrown as argument$ *he e&ception will %e caught % an immediatel encompassing tr 7catch construction or propagated further up the calling hierarch $ *he throws 2e word is a modifier of a method that designates that e&ceptions ma come out of the mehtod" either % virtue of the method throwing the e&ception itself or %ecause it fails to catch such e&ceptions that a method it calls ma throw$ 7P$ 4f a class is declared without an access modifiers" where ma the class %e accessed> A class that is declared without an access modifiers is said to have pac2age or friendl access$ *his means that the class can onl %e accessed % other classes and interfaces that are defined within the same pac2age$

7Q$ !hat is the 8ap interface> *he 8ap interface replaces the 0'F ($( 'ictionar class and is used associate 2e s with values$ P0$ 'oes a class inherit the constructors of its superclass> A class does not inherit constructors from an of its superclasses$ P($ Name primitive 0ava t pes$ *he primitive t pes are % te" char" short" int" long" float" dou%le" and %oolean$ P,$ !hich class should ou use to o%tain design information a%out an o%ject> *he -lass class is used to o%tain information a%out an o%jectEs design$ PA$ +ow can a 5=4 component handle its own events> A component can handle its own events % implementing the re/uired event7listener interface and adding itself as its own event listener$ PO$ +ow are the elements of a 5ridBagLa out organi9ed> *he elements of a 5ridBagLa out are organi9ed according to a grid$ +owever" the elements are of different si9es and ma occup more than one row or column of the grid$ 4n addition" the rows and columns ma have different si9es$ PI$ !hat advantage do 0avaEs la out managers provide over traditional windowing s stems> 0ava uses la out managers to la out components in a consistent manner across all windowing platforms$ .ince 0avaEs la out managers arenEt tied to a%solute si9ing and positioning" the are a%le to accommodate platform7specific differences among windowing s stems$ PB$ !hat are the pro%lems faced % 0ava programmers who donEt use la out managers> !ithout la out managers" 0ava programmers are faced with determining how their 5=4 will %e displa ed across multiple windowing s stems and finding a common si9ing and positioning that will wor2 within the constraints imposed % each windowing s stem$ P7$ !hat is the difference %etween static and non7static varia%les>

A static varia%le is associated with the class as a whole rather than with specific instances of a class$ Non7static varia%les ta2e on uni/ue values with each o%ject instance$ PP$ !hat is the difference %etween the paint13 and repaint13 methods> *he paint13 method supports painting via a 5raphics o%ject$ *he repaint13 method is used to cause paint13 to %e invo2ed % the A!* painting thread$ PQ$ !hat is the purpose of the ;ile class> *he ;ile class is used to create o%jects that provide access to the files and directories of a local file s stem$ Q0$ !hat restrictions are placed on method overloading> *wo methods ma not have the same name and argument list %ut different return t pes$ Q($ !hat restrictions are placed on method overriding> Overridden methods must have the same name" argument list" and return t pe$ *he overriding method ma not limit the access of the method it overrides$ *he overriding method ma not throw an e&ceptions that ma not %e thrown % the overridden method$ Q,$ !hat is casting> *here are two t pes of casting" casting %etween primitive numeric t pes and casting %etween o%ject references$ -asting %etween numeric t pes is used to convert larger values" such as dou%le values" to smaller values" such as % te values$ -asting %etween o%ject references is used to refer to an o%ject % a compati%le class" interface" or arra t pe reference$ QA$ Name -ontainer classes$ !indow" ;rame" 'ialog" ;ile'ialog" )anel" Applet" or .croll)ane QO$ !hat class allows ou to read o%jects directl from a stream> *he O%ject4nput.tream class supports the reading of o%jects from input streams$ QI$ +ow are this13 and super13 used with constructors> this13 is used to invo2e a constructor of the same class$ super13 is used to invo2e a superclass constructor$

QB$ +ow is it possi%le for two .tring o%jects with identical values not to %e e/ual under the GG operator> *he GG operator compares two o%jects to determine if the are the same o%ject in memor $ 4t is possi%le for two .tring o%jects to have the same value" %ut located indifferent areas of memor $ Q7$ !hat an 4NO filter> An 4NO filter is an o%ject that reads from one stream and writes to another" usuall altering the data in some wa as it is passed from one stream to another$ QP$ !hat is the .et interface> *he .et interface provides methods for accessing the elements of a finite mathematical set$ .ets do not allow duplicate elements$ QQ$ !hat is the List interface> *he List interface provides support for ordered collections of o%jects$ (00$ !hat is the purpose of the ena%le:vents13 method>

*he ena%le:vents13 method is used to ena%le an event for a particular o%ject$ Normall " an event is ena%led when a listener is added to an o%ject for a particular event$ *he ena%le:vents13 method is used % o%jects that handle events % overriding their event7 dispatch methods$ (0($ !hat is the difference %etween the ;ile and RandomAccess;ile classes>

*he ;ile class encapsulates the files and directories of the local file s stem$ *he RandomAccess;ile class provides the methods needed to directl access data contained in an part of a file$ (0,$ !hat interface must an o%ject implement %efore it can %e written to a stream as an o%ject> An o%ject must implement the .eriali9a%le or :&ternali9a%le interface %efore it can %e written to a stream as an o%ject$ (0A$ !hat is the ResourceBundle class>

*he ResourceBundle class is used to store locale7specific resources that can %e loaded % a program to tailor the programEs appearance to the particular locale in which it is %eing run$ (0O$ !hat is the difference %etween a .croll%ar and a .croll)ane>

A .croll%ar is a -omponent" %ut not a -ontainer$ A .croll)ane is a -ontainer$ A .croll)ane handles its own events and performs its own scrolling$ (0I$ !hat is a 0ava pac2age and how is it used>

A 0ava pac2age is a naming conte&t for classes and interfaces$ A pac2age is used to create a separate name space for groups of classes and interfaces$ )ac2ages are also used to organi9e related classes and interfaces into a single A)4 unit and to control accessi%ilit to these classes and interfaces$ (0B$ !hat are the O%ject and -lass classes used for>

*he O%ject class is the highest7level class in the 0ava class hierarch $ *he -lass class is used to represent the classes and interfaces that are loaded % a 0ava program$ (07$ !hat is .eriali9ation and deseriali9ation>

.eriali9ation is the process of writing the state of an o%ject to a % te stream$ 'eseriali9ation is the process of restoring these o%jects$ (0P$ what is tunnelling>

*unnelling is a route to somewhere$ ;or e&ample" R84 tunnelling is a wa to ma2e R84 application get through firewall$ 4n -. world" tunnelling means a wa to transfer data$ (0Q$ 'oes the code in finall %loc2 get e&ecuted if there is an e&ception and a return statement in a catch %loc2> 4f an e&ception occurs and there is a return statement in catch %loc2" the finall %loc2 is still e&ecuted$ *he finall %loc2 will not %e e&ecuted when the . stem$e&it1(3 statement is e&ecuted earlier or the s stem shut down earlier or the memor is used up earlier %efore the thread goes to finall %loc2$ ((0$ +ow ou restrict a user to cut and paste from the html page>

=sing java.cript to loc2 2e %oard 2e s$ 4t is one of solutions$ ((($ 4s 0ava a super set of 0ava.cript>

No$ *he are completel different$ .ome s nta& ma %e similar$ ((,$ !hat is a -ontainer in a 5=4>

A -ontainer contains and arranges other components 1including other containers3 through the use of la out managers" which use specific la out policies to determine where components should go as a function of the si9e of the container$ ((A$ +ow the o%ject oriented approach helps us 2eep comple&it of software development under control> !e can discuss such issue from the following aspects:
o o o

O%jects allow procedures to %e encapsulated with their data to reduce potential interference$ 4nheritance allows well7tested procedures to %e reused and ena%les changes to ma2e once and have effect in all relevant places$ *he well7defined separations of interface and implementation allows constraints to %e imposed on inheriting classes while still allowing the fle&i%ilit of overriding and overloading$

((O$

!hat is pol morphism>

)ol morphism allows methods to %e written that neednEt %e concerned a%out the specifics of the o%jects the will %e applied to$ *hat is" the method can %e specified at a higher level of a%straction and can %e counted on to wor2 even on o%jects of et unconceived classes$ ((I$ !hat is design % contract>

*he design % contract specifies the o%ligations of a method to an other methods that ma use its services and also theirs to it$ ;or e&ample" the preconditions specif what the method re/uired to %e true when the method is called$ +ence ma2ing sure that preconditions are$ .imilarl " postconditions specif what must %e true when the method is finished" thus the called method has the responsi%ilit of satisf ing the post conditions$ 4n 0ava" the e&ception handling facilities support the use of design % contract" especiall in the case of chec2ed e&ceptions$ *he assert 2e word can %e used to ma2e such contracts$ ((B$ !hat are use cases>

A use case descri%es a situation that a program might encounter and what %ehavior the program should e&hi%it in that circumstance$ 4t is part of the anal sis of a program$ *he collection of use cases should" ideall " anticipate all the standard circumstances and man of the e&traordinar circumstances possi%le so that the program will %e ro%ust$

((7$
o o o o o o o o o

!hat is the difference %etween interface and a%stract class> interface contains methods that must %e a%stractU a%stract class ma contain concrete methods$ interface contains varia%les that must %e static and finalU a%stract class ma contain non7final and final varia%les$ mem%ers in an interface are pu%lic % default" a%stract class ma contain non7pu%lic mem%ers$ interface is used to HimplementsHU whereas a%stract class is used to He&tendsH$ interface can %e used to achieve multiple inheritanceU a%stract class can %e used as a single inheritance$ interface can He&tendsH another interface" a%stract class can He&tendsH another class and HimplementsH multiple interfaces$ interface is a%solutel a%stractU a%stract class can %e invo2ed if a main13 e&ists$ interface is more fle&i%le than a%stract class %ecause one class can onl He&tendsH one super class" %ut HimplementsH multiple interfaces$ 4f given a choice" use interface instead of a%stract class$

Oaster list of Java interview questions 115 questions


B admin X 0ul (P" ,00I ((I /uestions total" not for the wea2$ -overs ever thing from %asics to 0'Bconnectivit " A!* and 0.)$ ($ #!at is t!e $ifference between proce$ural an$ obHect-oriente$ pro+rams'7 a3 4n procedural program" programming logic follows certain procedures and the instructions are e&ecuted one after another$ 4n OO) program" unit of program is o%ject" which is nothing %ut com%ination of data and code$ %3 4n procedural program" data is e&posed to the whole program whereas in OO)s program" it is accessi%le with in the o%ject and which in turn assures the securit of the code$ ,$ #!at are Kncapsulation7 In!eritance an$ Fol0morp!ism'7 :ncapsulation is the mechanism that %inds together code and data it manipulates and 2eeps %oth safe from outside interference and misuse$ 4nheritance is the process % which one o%ject ac/uires the properties of another o%ject$ )ol morphism is the feature that allows one interface to %e used for general class actions$ A$ #!at is t!e $ifference between "ssi+nment an$ InitialiIation' 7 Assignment can %e done as man times as desired whereas initiali9ation can %e done onl once$ O$ #!at is LLFs'7 O%ject oriented programming organi9es a program around its data" i$ e$ " o%jects and a set of well defined interfaces to that data$ An o%ject7 oriented program can %e characteri9ed as data controlling access to code$

I$ #!at are %lass7 %onstructor an$ Frimitive $ata t0pes'7 -lass is a template for multiple o%jects with similar features and it is a %lue print for o%jects$ 4t defines a t pe of o%ject according to the data the o%ject can hold and the operations the o%ject can perform$ -onstructor is a special 2ind of method that determines how an o%ject is initiali9ed when created$ )rimitive data t pes are P t pes and the are: % te" short" int" long" float" dou%le" %oolean" char$ B$ #!at is an LbHect an$ !ow $o 0ou allocate memor0 to it'7 O%ject is an instance of a class and it is a software unit that com%ines a structured set of data with a set of operations for inspecting and manipulating that data$ !hen an o%ject is created using new operator" memor is allocated to it$ 7$ #!at is t!e $ifference between constructor an$ met!o$'7 -onstructor will %e automaticall invo2ed when an o%ject is created whereas method has to %e called e&plicitl $ P$ #!at are met!o$s an$ !ow are t!e0 $efine$'7 8ethods are functions that operate on instances of classes in which the are defined$ O%jects can communicate with each other using methods and can call methods in other classes$ 8ethod definition has four parts$ *he are name of the method" t pe of o%ject or primitive t pe the method returns" a list of parameters and the %od of the method$ A method#s signature is a com%ination of the first three parts mentioned a%ove$ Q$ #!at is t!e use of bin an$ lib in JG6'7 Bin contains all tools such as javac" appletviewer" awt tool" etc$" whereas li% contains A)4 and all pac2ages$ (0$ #!at is castin+'7 -asting is used to convert the value of one t pe to another$ (($ 2ow man0 wa0s can an ar+ument be passe$ to a subroutine an$ e-plain t!em'7 An argument can %e passed in two wa s$ *he are passing % value and passing % reference$ )assing % value: *his method copies the value of an argument into the formal parameter of the su%routine$ )assing % reference: 4n this method" a reference to an argument 1not the value of the argument3 is passed to the parameter$ (,$ #!at is t!e $ifference between an ar+ument an$ a parameter'7 !hile defining method" varia%les passed in the method are called parameters$ !hile using those methods" values passed to those varia%les are called arguments$ (A$ #!at are $ifferent t0pes of access mo$ifiers'7 pu%lic: An thing declared as pu%lic can %e accessed from an where$ private: An thing declared as private can#t %e seen outside of its class$ protected: An thing declared as protected can %e accessed % classes in the same pac2age and su%classes in the other pac2ages$ default modifier : -an %e accessed onl to classes in the same pac2age$ (O$ #!at is final7 finaliIeDE an$ finall0'7 final : final 2e word can %e used for class" method and varia%les$ A final class cannot %e su%classed and it prevents other programmers from su%classing a secure class to invo2e insecure methods$ A final method can#t %e overridden$ A final varia%le can#t change from its initiali9ed value$ finali9e13 : finali9e13 method is used just %efore an o%ject is destro ed and can %e called just prior to gar%age collection$ finall : finall " a 2e word used in e&ception handling" creates a %loc2 of code that will %e e&ecuted after a tr Ncatch %loc2 has completed and %efore the code following the tr Ncatch %loc2$ *he finall %loc2 will e&ecute whether or not an e&ception is thrown$ ;or e&ample" if a

method opens a file upon e&it" then ou will not want the code that closes the file to %e % passed % the e&ception7handling mechanism$ *his finall 2e word is designed to address this contingenc $ (I$ #!at is QSI%LGK'7 =nicode is used for internal representation of characters and strings and it uses (B %its to represent each other$ (B$ #!at is ,arba+e %ollection an$ !ow to call it e-plicitl0'7 !hen an o%ject is no longer referred to % an varia%le" java automaticall reclaims memor used % that o%ject$ *his is 2nown as gar%age collection$ . stem$ gc13 method ma %e used to call it e&plicitl $ (7$ #!at is finaliIeDE met!o$'7 finali9e 13 method is used just %efore an o%ject is destro ed and can %e called just prior to gar%age collection$ (P$ #!at are Transient an$ Molatile Oo$ifiers'7 *ransient: *he transient modifier applies to varia%les onl and it is not stored as part of its o%ject#s )ersistent state$ *ransient varia%les are not seriali9ed$ <olatile: <olatile modifier applies to varia%les onl and it tells the compiler that the varia%le modified % volatile can %e changed une&pectedl % other parts of the program$ (Q$ #!at is met!o$ overloa$in+ an$ met!o$ overri$in+'7 8ethod overloading: !hen a method in a class having the same method name with different arguments is said to %e method overloading$ 8ethod overriding : !hen a method in a class having the same method name with same arguments is said to %e method overriding$ ,0$ #!at is $ifference between overloa$in+ an$ overri$in+'7 a3 4n overloading" there is a relationship %etween methods availa%le in the same class whereas in overriding" there is relationship %etween a superclass method and su%class method$ %3 Overloading does not %loc2 inheritance from the superclass whereas overriding %loc2s inheritance from the superclass$ c3 4n overloading" separate methods share the same name whereas in overriding" su%class method replaces the superclass$ d3 Overloading must have different method signatures whereas overriding must have same signature$ ,($ #!at is meant b0 In!eritance an$ w!at are its a$vanta+es'7 4nheritance is the process of inheriting all the features from a class$ *he advantages of inheritance are reusa%ilit of code and accessi%ilit of varia%les and methods of the super class % su%classes$ ,,$ #!at is t!e $ifference between t!isDE an$ superDE'7 this13 can %e used to invo2e a constructor of the same class whereas super13 can %e used to invo2e a super class constructor$ ,A$ #!at is t!e $ifference between superclass an$ subclass'7 A super class is a class that is inherited whereas su% class is a class that does the inheriting$ ,O$ #!at mo$ifiers ma0 be use$ wit! top-level class'7 pu%lic" a%stract and final can %e used for top7level class$ ,I$ #!at are inner class an$ anon0mous class'7 4nner class : classes defined in other classes" including those defined in methods are called inner classes$ An inner class can have an accessi%ilit including private$ Anon mous class : Anon mous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have e&plicit constructors$

,B$ #!at is a packa+e'7 A pac2age is a collection of classes and interfaces that provides a high7level la er of access protection and name space management$ ,7$ #!at is a reflection packa+e'7 java$ lang$ reflect pac2age has the a%ilit to anal 9e itself in runtime$ ,P$ #!at is interface an$ its use'7 4nterface is similar to a class which ma contain method#s signature onl %ut not %odies and it is a formal set of method and constant declarations that must %e defined % the class that implements it$ 4nterfaces are useful for: a3'eclaring methods that one or more classes are e&pected to implement %3-apturing similarities %etween unrelated classes without forcing a class relationship$ c3'etermining an o%ject#s programming interface without revealing the actual %od of the class$ ,Q$ #!at is an abstract class'7 An a%stract class is a class designed with implementation gaps for su%classes to fill in and is deli%eratel incomplete$ A0$ #!at is t!e $ifference between Inte+er an$ int'7 a3 4nteger is a class defined in the java$ lang pac2age" whereas int is a primitive data t pe defined in the 0ava language itself$ 0ava does not automaticall convert from one to the other$ %3 4nteger can %e used as an argument for a method that re/uires an o%ject" whereas int can %e used for calculations$ A($ #!at is a cloneable interface an$ !ow man0 met!o$s $oes it contain'7 4t is not having an method %ecause it is a *A55:' or 8ARF:R interface$ A,$ #!at is t!e $ifference between abstract class an$ interface'7 a3 All the methods declared inside an interface are a%stract whereas a%stract class must have at least one a%stract method and others ma %e concrete or a%stract$ %3 4n a%stract class" 2e word a%stract must %e used for the methods whereas interface we need not use that 2e word for the methods$ c3 A%stract class must have su%classes whereas interface can#t have su%classes$ AA$ %an 0ou !ave an inner class insi$e a met!o$ an$ w!at variables can 0ou access'7 Yes" we can have an inner class inside a method and final varia%les can %e accessed$ AO$ #!at is t!e $ifference between &trin+ an$ &trin+ Juffer'7 a3 .tring o%jects are constants and immuta%le whereas .tringBuffer o%jects are not$ %3 .tring class supports constant strings whereas .tringBuffer class supports growa%le and modifia%le strings$ AI$ #!at is t!e $ifference between "rra0 an$ vector'7 Arra is a set of related data t pe and static whereas vector is a growa%le arra of o%jects and d namic$ AB$ #!at is t!e $ifference between e-ception an$ error'7 *he e&ception class defines mild error conditions that our program encounters$ :&ceptions can occur when tr ing to open the file" which does not e&ist" the networ2 connection is disrupted" operands %eing manipulated are out of prescri%ed ranges" the class file ou are interested in loading is missing$ *he error class defines serious error conditions that ou should not attempt to recover from$ 4n most cases it is advisa%le to let the program terminate when such an error is encountered$ A7$ #!at is t!e $ifference between process an$ t!rea$'7 )rocess is a program in e&ecution whereas thread is a separate path of e&ecution in a program$ AP$ #!at is multit!rea$in+ an$ w!at are t!e met!o$s for inter-t!rea$ communication an$ w!at is t!e class in w!ic! t!ese met!o$s are $efine$'7

8ultithreading is the mechanism in which more than one thread run independent of each other within the process$ wait 13" notif 13 and notif All13 methods can %e used for inter7thread communication and these methods are in O%ject class$ wait13 : !hen a thread e&ecutes a call to wait13 method" it surrenders the o%ject loc2 and enters into a waiting state$ notif 13 or notif All13 : *o remove a thread from the waiting state" some other thread must ma2e a call to notif 13 or notif All13 method on the same o%ject$ AQ$ #!at is t!e class an$ interface in Hava to create t!rea$ an$ w!ic! is t!e most a$vanta+eous met!o$'7 *hread class and Runna%le interface can %e used to create threads and using Runna%le interface is the most advantageous method to create threads %ecause we need not e&tend thread class here$ O0$ #!at are t!e states associate$ in t!e t!rea$'7 *hread contains read " running" waiting and dead states$ O($ #!at is s0nc!roniIation'7 . nchroni9ation is the mechanism that ensures that onl one thread is accessed the resources at a time$ O,$ #!en 0ou will s0nc!roniIe a piece of 0our co$e'7 !hen ou e&pect our code will %e accessed % different threads and these threads ma change a particular data causing data corruption$ OA$ #!at is $ea$lock'7 !hen two threads are waiting each other and can#t precede the program is said to %e deadloc2$ OO$ #!at is $aemon t!rea$ an$ w!ic! met!o$ is use$ to create t!e $aemon t!rea$'7 'aemon thread is a low priorit thread which runs intermittentl in the %ac2 ground doing the gar%age collection operation for the java runtime s stem$ set'aemon method is used to create a daemon thread$ OI$ "re t!ere an0 +lobal variables in Java7 w!ic! can be accesse$ b0 ot!er part of 0our pro+ram'7 No" it is not the main method in which ou define varia%les$ 5lo%al varia%les is not possi%le %ecause concept of encapsulation is eliminated here$ OB$ #!at is an applet'7 Applet is a d namic and interactive program that runs inside a we% page displa ed % a java capa%le %rowser$ O7$ #!at is t!e $ifference between applications an$ applets'7 a3Application must %e run on local machine whereas applet needs no e&plicit installation on local machine$ %3Application must %e run e&plicitl within a java7compati%le virtual machine whereas applet loads and runs itself automaticall in a java7ena%led %rowser$ d3Application starts e&ecution with its main method whereas applet starts e&ecution with its init method$ e3Application can run with or without graphical user interface whereas applet must run within a graphical user interface$ OP$ 2ow $oes applet reco+niIe t!e !ei+!t an$ wi$t!'7 =sing get)arameters13 method$ OQ$ #!en $o 0ou use co$ebase in applet'7 !hen the applet class file is not in the same director " code%ase is used$ I0$ #!at is t!e lifec0cle of an applet'7 init13 method 7 -an %e called when an applet is first loaded start13 method 7 -an %e called each time an applet is started$ paint13 method 7 -an %e called when the applet is minimi9ed or ma&imi9ed$ stop13 method 7 -an %e used when the %rowser moves off the applet#s page$ destro 13 method 7 -an %e called when the %rowser is finished with the applet$

I($ 2ow $o 0ou set securit0 in applets'7 using set.ecurit 8anager13 method I,$ #!at is an event an$ w!at are t!e mo$els available for event !an$lin+'7 An event is an event o%ject that descri%es a state of change in a source$ 4n other words" event occurs when an action is generated" li2e pressing %utton" clic2ing mouse" selecting a list" etc$ *here are two t pes of models for handling events and the are: a3 event7inheritance model and %3 event7delegation model IA$ #!at are t!e a$vanta+es of t!e mo$el over t!e event-in!eritance mo$el'7 *he event7delegation model has two advantages over the event7inheritance model$ *he are: a34t ena%les event handling % o%jects other than the ones that generate the events$ *his allows a clean separation %etween a component#s design and its use$ %34t performs much %etter in applications where man events are generated$ *his performance improvement is due to the fact that the event7delegation model does not have to %e repeatedl process unhandled events as is the case of the event7inheritance$ IO$ #!at is source an$ listener'7 source : A source is an o%ject that generates an event$ *his occurs when the internal state of that o%ject changes in some wa $ listener : A listener is an o%ject that is notified when an event occurs$ 4t has two major re/uirements$ ;irst" it must have %een registered with one or more sources to receive notifications a%out specific t pes of events$ .econd" it must implement methods to receive and process these notifications$ II$ #!at is a$apter class'7 An adapter class provides an empt implementation of all methods in an event listener interface$ Adapter classes are useful when ou want to receive and process onl some of the events that are handled % a particular event listener interface$ You can define a new class to act listener % e&tending one of the adapter classes and implementing onl those events in which ou are interested$ ;or e&ample" the 8ouse8otionAdapter class has two methods" mouse'ragged13and mouse8oved13$ *he signatures of these empt are e&actl as defined in the 8ouse8otionListener interface$ 4f ou are interested in onl mouse drag events" then ou could simpl e&tend 8ouse8otionAdapter and implement mouse'ragged13 $ IB$ #!at is meant b0 controls an$ w!at are $ifferent t0pes of controls in "#T'7 -ontrols are components that allow a user to interact with our application and the A!* supports the following t pes of controls: La%els" )ush Buttons" -hec2 Bo&es" -hoice Lists" Lists" .croll%ars" *e&t -omponents$ *hese controls are su%classes of -omponent$ I7$ #!at is t!e $ifference between c!oice an$ list'7 A -hoice is displa ed in a compact form that re/uires ou to pull it down to see the list of availa%le choices and onl one item ma %e selected from a choice$ A List ma %e displa ed in such a wa that several list items are visi%le and it supports the selection of one or more list items$ IP$ #!at is t!e $ifference between scrollbar an$ scrollpane'7 A .croll%ar is a -omponent" %ut not a -ontainer whereas .crollpane is a -onatiner and handles its own events and perform its own scrolling$ IQ$ #!at is a la0out mana+er an$ w!at are $ifferent t0pes of la0out mana+ers available in Hava "#T'7 A la out manager is an o%ject that is used to organi9e

components in a container$ *he different la outs are availa%le are ;lowLa out" BorderLa out" -ardLa out" 5ridLa out and 5ridBagLa out$ B0$ 2ow are t!e elements of $ifferent la0outs or+aniIe$'7 ;lowLa out: *he elements of a ;lowLa out are organi9ed in a top to %ottom" left to right fashion$ BorderLa out: *he elements of a BorderLa out are organi9ed at the %orders 1North" .outh" :ast and !est3 and the center of a container$ -ardLa out: *he elements of a -ardLa out are stac2ed" on top of the other" li2e a dec2 of cards$ 5ridLa out: *he elements of a 5ridLa out are of e/ual si9e and are laid out using the s/uare of a grid$ 5ridBagLa out: *he elements of a 5ridBagLa out are organi9ed according to a grid$ +owever" the elements are of different si9e and ma occup more than one row or column of the grid$ 4n addition" the rows and columns ma have different si9es$ B($ #!ic! containers use a Jor$er la0out as t!eir $efault la0out'7 !indow" ;rame and 'ialog classes use a BorderLa out as their la out$ B,$ #!ic! containers use a 5low la0out as t!eir $efault la0out'7 )anel and Applet classes use the ;lowLa out as their default la out$ BA$ #!at are wrapper classes'7 !rapper classes are classes that allow primitive t pes to %e accessed as o%jects$ BO$ #!at are Mector7 2as!table7 /inke$/ist an$ Knumeration'7 <ector : *he <ector class provides the capa%ilit to implement a growa%le arra of o%jects$ +ashta%le : *he +ashta%le class implements a +ashta%le data structure$ A +ashta%le inde&es and stores o%jects in a dictionar using hash codes as the o%ject#s 2e s$ +ash codes are integer values that identif o%jects$ Lin2edList: Removing or inserting elements in the middle of an arra can %e done using Lin2edList$ A Lin2edList stores each o%ject in a separate lin2 whereas an arra stores o%ject references in consecutive locations$ :numeration: An o%ject that implements the :numeration interface generates a series of elements" one at a time$ 4t has two methods" namel has8ore:lements13 and ne&t:lement13$ +as8ore:lemnts13 tests if this enumeration has more elements and ne&t:lement method returns successive elements of the series$ BI$ #!at is t!e $ifference between set an$ list'7 .et stores elements in an unordered wa %ut does not contain duplicate elements" whereas list stores elements in an ordered wa %ut ma contain duplicate elements$ BB$ #!at is a stream an$ w!at are t!e t0pes of &treams an$ classes of t!e &treams'7 A .tream is an a%straction that either produces or consumes information$ *here are two t pes of .treams and the are: B te .treams: )rovide a convenient means for handling input and output of % tes$ -haracter .treams: )rovide a convenient means for handling input V output of characters$ B te .treams classes: Are defined % using two a%stract classes" namel 4nput.tream and Output.tream$ -haracter .treams classes: Are defined % using two a%stract classes" namel Reader and !riter$ B7$ #!at is t!e $ifference between Nea$er9#riter an$ Input&tream9Lutput &tream'7 *he ReaderN!riter class is character7oriented and the 4nput.treamNOutput.tream class is % te7oriented$

BP$ #!at is an I9L filter'7 An 4NO filter is an o%ject that reads from one stream and writes to another" usuall altering the data in some wa as it is passed from one stream to another$ BQ$ #!at is serialiIation an$ $eserialiIation'7 .eriali9ation is the process of writing the state of an o%ject to a % te stream$ 'eseriali9ation is the process of restoring these o%jects$ 70$ #!at is JGJ%'7 0'B- is a set of 0ava A)4 for e&ecuting .?L statements$ *his A)4 consists of a set of classes and interfaces to ena%le programs to write pure 0ava 'ata%ase applications$ 7($ #!at are $rivers available'7 a3 0'B-7O'B- Bridge driver %3 Native A)4 )artl 70ava driver c3 0'B-7Net )ure 0ava driver d3 Native7)rotocol )ure 0ava driver 7,$ #!at is t!e $ifference between JGJ% an$ LGJ%'7 a3 OB'- is for 8icrosoft and 0'B- is for 0ava applications$ %3 O'B- can#t %e directl used with 0ava %ecause it uses a - interface$ c3 O'B- ma2es use of pointers which have %een removed totall from 0ava$ d3 O'B- mi&es simple and advanced features together and has comple& options for simple /ueries$ But 0'B- is designed to 2eep things simple while allowing advanced capa%ilities when re/uired$ e3 O'Bre/uires manual installation of the O'B- driver manager and driver on all client machines$ 0'B- drivers are written in 0ava and 0'B- code is automaticall installa%le" secure" and porta%le on all platforms$ f3 0'B- A)4 is a natural 0ava interface and is %uilt on O'B-$ 0'B- retains some of the %asic features of O'B-$ 7A$ #!at are t!e t0pes of JGJ% Griver Oo$els an$ e-plain t!em'7 *here are two t pes of 0'B- 'river 8odels and the are: a3 *wo tier model and %3 *hree tier model *wo tier model: 4n this model" 0ava applications interact directl with the data%ase$ A 0'B- driver is re/uired to communicate with the particular data%ase management s stem that is %eing accessed$ .?L statements are sent to the data%ase and the results are given to user$ *his model is referred to as clientNserver configuration where user is the client and the machine that has the data%ase is called as the server$ *hree tier model: A middle tier is introduced in this model$ *he functions of this model are: a3 -ollection of .?L statements from the client and handing it over to the data%ase" %3 Receiving results from data%ase to the client and c3 8aintaining control over accessing and updating of the a%ove$ 7O$ #!at are t!e steps involve$ for makin+ a connection wit! a $atabase or !ow $o 0ou connect to a $atabase'a3 Loading the driver : *o load the driver" -lass$ forName13 method is used$ -lass$ forName1Lsun$ jd%c$ od%c$ 0d%cOd%c'riverL3U !hen the driver is loaded" it registers itself with the java$ s/l$ 'river8anager class as an availa%le data%ase driver$ %3 8a2ing a connection with data%ase: *o open a connection to a given data%ase" 'river8anager$ get-onnection13 method is used$ -onnection con G 'river8anager$ get-onnection 1Ljd%c:od%c:somed%L" KuserL" KpasswordL3U c3 :&ecuting .?L statements : *o e&ecute a .?L /uer " java$ s/l$ statements class is used$ create.tatement13 method of -onnection to o%tain a new .tatement o%ject$ .tatement stmt G con$ create.tatement13U A /uer that returns data can %e e&ecuted using the e&ecute?uer 13 method of .tatement$ *his method e&ecutes the statement and returns a java$ s/l$ Result.et that

encapsulates the retrieved data: Result.et rs G stmt$ e&ecute?uer 1L.:L:-* @ ;RO8 some ta%leL3U d3 )rocess the results : Result.et returns one row at a time$ Ne&t13 method of Result.et o%ject can %e called to move to the ne&t row$ *he get.tring13 and getO%ject13 methods are used for retrieving column values: while1rs$ ne&t133 Y .tring event G rs$ get.tring1LeventL3U O%ject count G 14nteger3 rs$ getO%ject1LcountL3U 7I$ #!at t0pe of $river $i$ 0ou use in proHect'7 0'B-7O'B- Bridge driver 1is a driver that uses native1- language3 li%raries and ma2es calls to an e&isting O'Bdriver to access a data%ase engine3$ 7B$ #!at are t!e t0pes of statements in JGJ%'7 .tatement: to %e used create.tatement13 method for e&ecuting single .?L statement )repared.tatement 6 *o %e used prepared.tatement13 method for e&ecuting same .?L statement over and over$ -alla%le.tatement 6 *o %e used prepare-all13 method for multiple .?L statements over and over$ 77$ #!at is store$ proce$ure'7 .tored procedure is a group of .?L statements that forms a logical unit and performs a particular tas2$ .tored )rocedures are used to encapsulate a set of operations or /ueries to e&ecute on data%ase$ .tored procedures can %e compiled and e&ecuted with different parameters and results and ma have an com%ination of inputNoutput parameters$ 7P$ 2ow to create an$ call store$ proce$ures'7 *o create stored procedures: -reate procedure procedurename 1specif in" out and in out parameters3 B:54N An multiple .?L statementU :N'U *o call stored procedures: -alla%le.tatement csmt G con$ prepare-all1LYcall procedure name1>">3ZL3U csmt$ registerOut)arameter1column no$ " data t pe3U csmt$ set4nt1column no$ " column name3 csmt$ e&ecute13U 7Q$ #!at is servlet'7 .ervlets are modules that e&tend re/uestNresponse7oriented servers" such as java7ena%led we% servers$ ;or e&ample" a servlet might %e responsi%le for ta2ing data in an +*8L order7entr form and appl ing the %usiness logic used to update a compan #s order data%ase$ P0$ #!at are t!e classes an$ interfaces for servlets'7 *here are two pac2ages in servlets and the are java&$ servlet and P($ #!at is t!e $ifference between an applet an$ a servlet'7 a3 .ervlets are to servers what applets are to %rowsers$ %3 Applets must have graphical user interfaces whereas servlets have no graphical user interfaces$ P,$ #!at is t!e $ifference between $oFost an$ $o,et met!o$s'7 a3 do5et13 method is used to get information" while do)ost13 method is used for posting information$ %3 do5et13 re/uests can#t send large amount of information and is limited to ,O07,II characters$ +owever" do)ost13re/uests passes all of its data" of unlimited length$ c3 A do5et13 re/uest is appended to the re/uest =RL in a /uer string and this allows the e&change is visi%le to the client" whereas a do)ost13 re/uest passes directl over the soc2et connection as part of its +**) re/uest %od and the e&change are invisi%le to the client$ PA$ #!at is t!e life c0cle of a servlet'7 :ach .ervlet has the same life c cle: a3 A server loads and initiali9es the servlet % init 13 method$ %3 *he servlet handles 9ero or more client#s re/uests through service13 method$ c3 *he server removes the servlet through destro 13 method$

PO$ #!o is loa$in+ t!e initDE met!o$ of servlet'7 !e% server PI$ #!at are t!e $ifferent servers available for $evelopin+ an$ $eplo0in+ &ervlets'7 a3 0ava !e% .erver %3 0Run g3 Apache .erver h3 Netscape 4nformation .erver i3 !e% Logic PB$ 2ow man0 wa0s can we track client an$ w!at are t!e0'7 *he servlet A)4 provides two wa s to trac2 client state and the are: a3 =sing .ession trac2ing and %3 =sing -oo2ies$ P7$ #!at is session trackin+ an$ !ow $o 0ou track a user session in servlets'7 .ession trac2ing is a mechanism that servlets use to maintain state a%out a series re/uests from the same user across some period of time$ *he methods used for session trac2ing are: a3 =ser Authentication 7 occurs when a we% server restricts access to some of its resources to onl those clients that log in using a recogni9ed username and password$ %3 +idden form fields 7 fields are added to an +*8L form that are not displa ed in the client#s %rowser$ !hen the form containing the fields is su%mitted" the fields are sent %ac2 to the server$ c3 =RL rewriting 7 ever =RL that the user clic2s on is d namicall modified or rewritten to include e&tra information$ *he e&tra information can %e in the form of e&tra path information" added parameters or some custom" server7specific =RL change$ d3 -oo2ies 7 a %it of information that is sent % a we% server to a %rowser and which can later %e read %ac2 from that %rowser$ e3 +ttp.ession7 places a limit on the num%er of sessions that can e&ist in memor $ *his limit is set in the session$ ma&residents propert $ PP$ #!at is &erver-&i$e Inclu$es D&&IE'7 .erver7.ide 4ncludes allows em%edding servlets within +*8L pages using a special servlet tag$ 4n man servlets that support servlets" a page can %e processed % the server to include output from servlets at certain points inside the +*8L page$ *his is accomplished using a special internal ..4N-L=':" which processes the servlet tags$ ..4N-L=': servlet will %e invo2ed whenever a file with an$ shtml e&tension is re/uested$ .o +*8L files that include server7side includes must %e stored with an $ shtml e&tension$ PQ$ #!at are cookies an$ !ow will 0ou use t!em'7 -oo2ies are a mechanism that a servlet uses to have a client hold a small amount of state7information associated with the user$ a3 -reate a coo2ie with the -oo2ie constructor: pu%lic -oo2ie1.tring name" .tring value3 %3 A servlet can send a coo2ie to the client % passing a -oo2ie o%ject to the add-oo2ie13 method of +ttp.ervletResponse: pu%lic void +ttp.ervletResponse$ add-oo2ie1-oo2ie coo2ie3 c3 A servlet retrieves coo2ies % calling the get-oo2ies13 method of +ttp.ervletRe/uest: pu%lic -oo2ie[ \ +ttp.ervletRe/uest$ get-oo2ie13$ Q0$ Is it possible to communicate from an applet to servlet an$ !ow man0 wa0s an$ !ow'7 Yes" there are three wa s to communicate from an applet to servlet and the are: a3 +**) -ommunication1*e&t7%ased and o%ject7%ased3 %3 .oc2et -ommunication c3 R84 -ommunication Q($ #!at is connection poolin+'7 !ith servlets" opening a data%ase connection is a major %ottlenec2 %ecause we are creating and tearing down a new connection for ever page re/uest and the time ta2en to create connection will %e more$ -reating a connection pool is an ideal approach for a complicated servlet$ !ith a

connection pool" we can duplicate onl the resources we need to duplicate rather than the entire servlet$ A connection pool can also intelligentl manage the si9e of the pool and ma2e sure each connection remains valid$ A num%er of connection pool pac2ages are currentl availa%le$ .ome li2e '%-onnectionBro2er are freel availa%le from 0ava :&change !or2s % creating an o%ject that dispenses connections and connection 4ds on re/uest$ *he -onnection)ool class maintains a +asta%le" using -onnection o%jects as 2e s and Boolean values as stored values$ *he Boolean value indicates whether a connection is in use or not$ A program calls get-onnection13 method of the -onnection)ool for getting -onnection o%ject it can useU it calls return-onnection13 to give the connection %ac2 to the pool$ Q,$ #!0 s!oul$ we +o for interservlet communication'7 .ervlets running together in the same server communicate with each other in several wa s$ *he three major reasons to use interservlet communication are: a3 'irect servlet manipulation 7 allows to gain access to the other currentl loaded servlets and perform certain tas2s 1through the .ervlet-onte&t o%ject3 %3 .ervlet reuse 7 allows the servlet to reuse the pu%lic methods of another servlet$ c3 .ervlet colla%oration 7 re/uires to communicate with each other % sharing specific information 1through method invocation3 QA$ Is it possible to call servlet wit! parameters in t!e QN/'7 Yes$ You can call a servlet with parameters in the s nta& as 1>)aram( G &&& XX m, G 3$ QO$ #!at is &ervlet c!ainin+'7 .ervlet chaining is a techni/ue in which two or more servlets can cooperate in servicing a single re/uest$ 4n servlet chaining" one servlet#s output is piped to the ne&t servlet#s input$ *his process continues until the last servlet is reached$ 4ts output is then sent %ac2 to the client$ QI$ 2ow $o servlets !an$le multiple simultaneous requests'7 *he server has multiple threads that are availa%le to handle re/uests$ !hen a re/uest comes in" it is assigned to a thread" which calls a service method 1for e&ample: do5et13" do)ost13 and service133 of the servlet$ ;or this reason" a single servlet o%ject can have its service methods called % man threads at once$ QB$ #!at is t!e $ifference between T%F9IF an$ QGF'7 *-)N4) is a two7wa communication %etween the client and the server and it is a relia%le and there is a confirmation regarding reaching the message to the destination$ 4t is li2e a phone call$ =') is a one7wa communication onl %etween the client and the server and it is not a relia%le and there is no confirmation regarding reaching the message to the destination$ 4t is li2e a postal mail$ Q7$ #!at is Inet a$$ress'7 :ver computer connected to a networ2 has an 4) address$ An 4) address is a num%er that uni/uel identifies each computer on the Net$ An 4) address is a A,7%it num%er$ QP$ #!at is Gomain Samin+ &erviceDGS&E'7 4t is ver difficult to remem%er a set of num%ers14) address3 to connect to the 4nternet$ *he 'omain Naming .ervice1'N.3 is used to overcome this pro%lem$ 4t maps one particular 4) address to a string of characters$ ;or e&ample" www$ mascom$ com implies com is the domain name reserved for =. commercial sites" moscom is the name of the compan and www is the name of the specific computer" which is mascom#s server$

QQ$ #!at is QN/'7 =RL stands for =niform Resource Locator and it points to resource files on the 4nternet$ =RL has four components: http:NNwww$ address$ com:P0Ninde&$html" where http 7 protocol name" address 7 4) address or host name" P0 7 port num%er and inde&$html 7 file path$ (00$ #!at is NOI an$ steps involve$ in $evelopin+ an NOI obHect'7 Remote 8ethod 4nvocation 1R843 allows java o%ject that e&ecutes on one machine and to invo2e the method of a 0ava o%ject to e&ecute on another machine$ *he steps involved in developing an R84 o%ject are: a3 'efine the interfaces %3 4mplementing these interfaces c3 -ompile the interfaces and their implementations with the java compiler d3 -ompile the server implementation with R84 compiler e3 Run the R84 registr f3 Run the application (0($ #!at is NOI arc!itecture'7 R84 architecture consists of four la ers and each la er performs specific functions: a3 Application la er 7 contains the actual o%ject definition$ %3 )ro& la er 7 consists of stu% and s2eleton$ c3 Remote Reference la er 7 gets the stream of % tes from the transport la er and sends it to the pro& la er$ d3 *ransportation la er 7 responsi%le for handling the actual machine7to7machine communication$ (0,$ w!at is QnicastNemoteLbHect'7 All remote o%jects must e&tend =nicastRemoteO%ject" which provides functionalit that is needed to ma2e o%jects availa%le from remote machines$ (0A$ K-plain t!e met!o$s7 rebin$DE an$ lookupDE in Samin+ class'7 re%ind13 of the Naming class1found in java$ rmi3 is used to update the R84 registr on the server machine$ Naming$ re%ind1LAdd.everL" Add.erver4mpl3U loo2up13 of the Naming class accepts one argument" the rmi =RL and returns a reference to an o%ject of t pe Add.erver4mpl$ (0O$ #!at is a Java Jean'7 A 0ava Bean is a software component that has %een designed to %e reusa%le in a variet of different environments$ (0I$ #!at is a Jar file'7 0ar file allows to efficientl deplo ing a set of classes and their associated resources$ *he elements in a jar file are compressed" which ma2es downloading a 0ar file much faster than separatel downloading several uncompressed files$ *he pac2age java$ util$ 9ip contains classes that read and write jar files$ (0B$ #!at is JG6'7 B'F" Bean 'evelopment Fit is a tool that ena%les to create" configure and connect a set of set of Beans and it can %e used to test Beans without writing a code$ (07$ #!at is J&F'7 0.) is a d namic scripting capa%ilit for we% pages that allows 0ava as well as a few special tags to %e em%edded into a we% file 1+*8LNM8L" etc3$ *he suffi& traditionall ends with $jsp to indicate to the we% server that the file is a 0.) files$ 0.) is a server side technolog 7 ou can#t do an client side validation with it$ *he advantages are: a3 *he 0.) assists in ma2ing the +*8L more functional$ .ervlets on the other hand allow outputting of +*8L %ut it is a tedious process$ %3 4t is eas to ma2e a change and then let the 0.) capa%ilit of the we% server ou are using deal with compiling it into a servlet and running it$ (0P$ #!at are J&F scriptin+ elements'7 0.) scripting elements lets to insert 0ava code into the servlet that will %e generated from the current 0.) page$ *here

are three forms: a3 :&pressions of the form R]G e&pression ]S that are evaluated and inserted into the output" %3 .criptlets of the formR] code ]Sthat are inserted into the servlet#s service method" and c3 'eclarations of the form R]^ -ode ]Sthat are inserted into the %od of the servlet class" outside of an e&isting methods$ (0Q$ #!at are J&F Girectives'7 A 0.) directive affects the overall structure of the servlet class$ 4t usuall has the following form:R]T directive attri%uteGLvalueL ]S +owever" ou can also com%ine multiple attri%ute settings for a single directive" as follows:R]T directive attri%ute(GLvalue(_ attri%ute ,GLvalue,_ $ $ $ attri%uteN GLvalueNL ]S *here are two main t pes of directive: page" which lets to do things li2e import classes" customi9e the servlet superclass" and the li2eU and include" which lets to insert a file into the servlet class at the time the 0.) file is translated into a servlet ((0$ #!at are Fre$efine$ variables or implicit obHects'7 *o simplif code in 0.) e&pressions and scriptlets" we can use eight automaticall defined varia%les" sometimes called implicit o%jects$ *he are re/uest" response" out" session" application" config" page-onte&t" and page$ ((($ #!at are J&F "%TILS&'7 0.) actions use constructs in M8L s nta& to control the %ehavior of the servlet engine$ You can d namicall insert a file" reuse 0avaBeans components" forward the user to another page" or generate +*8L for the 0ava plugin$ Availa%le actions include: jsp:include 7 4nclude a file at the time the page is re/uested$ jsp:useBean 7 ;ind or instantiate a 0avaBean$ jsp:set)ropert 7 .et the propert of a 0avaBean$ jsp:get)ropert 7 4nsert the propert of a 0avaBean into the output$ jsp:forward 7 ;orward the re/uester to a newpage$ 0sp: plugin 7 5enerate %rowser7specific code that ma2es an OB0:-* or :8B:' ((,$ 2ow $o 0ou pass $ata Dinclu$in+ JavaJeansE to a J&F from a servlet'7 1(3 Re/uest Lifetime: =sing this techni/ue to pass %eans" a re/uest dispatcher 1using either KincludeL or forwardL3 can %e called$ *his %ean will disappear after processing this re/uest has %een completed$ .ervlet: re/uest$ setAttri%ute1LtheBeanL" m Bean3U Re/uest'ispatcher rd G get.ervlet-onte&t13$ getRe/uest'ispatcher1Lthepage$ jspL3U rd$ forward1re/uest" response3U 0.) )A5::Rjsp: useBean idGLtheBeanL scopeGLre/uestL classGL$ $ $ $ $ L NS1,3 .ession Lifetime: =sing this techni/ue to pass %eans that are relevant to a particular session 1such as in individual user login3 over a num%er of re/uests$ *his %ean will disappear when the session is invalidated or it times out" or when ou remove it$ .ervlet: +ttp.ession session G re/uest$ get.ession1true3U session$ put<alue1LtheBeanL" m Bean3U N@ You can do a re/uest dispatcher here" or just let the %ean %e visi%le on the ne&t re/uest @N 0.) )age:Rjsp:useBean idGLtheBeanL scopeGLsessionL classGL$ $ $ L NS A3 Application Lifetime: =sing this techni/ue to pass %eans that are relevant to all servlets and 0.) pages in a particular app" for all users$ ;or e&ample" 4 use this to ma2e a 0'B- connection pool o%ject availa%le to the various servlets and 0.) pages in m apps$ *his %ean will disappear when the servlet engine is shut down" or when ou remove it$ .ervlet: 5et.ervlet-onte&t13$ setAttri%ute1LtheBeanL" m Bean3U 0.) )A5::Rjsp:useBean idGLtheBeanL scopeGLapplicationL classGL$ $ $ L NS

((A$ 2ow can I set a cookie in J&F'7 response$ set+eader1L.et7-oo2ieL" Kcoo2ie stringL3U *o give the response7o%ject to a %ean" write a method setResponse 1+ttp.ervletResponse response3 7 to the %ean" and in jsp7file:R] %ean$ setResponse 1response3U ]S ((O$ 2ow can I $elete a cookie wit! J&F'7 .a that 4 have a coo2ie called Kfoo" L that 4 set a while ago V 4 want it to go awa $ 4 simpl : R] -oo2ie 2ill-oo2ie G new -oo2ie1LfooL" null3U Fill-oo2ie$ set)ath1LNL3U 2ill-oo2ie$ set8a&Age103U response$ add-oo2ie12ill-oo2ie3U ]S ((I$ 2ow are &ervlets an$ J&F Fa+es relate$'7 0.) pages are focused around +*8L 1or M8L3 with 0ava codes and 0.) tags inside them$ !hen a we% server that has 0.) support is as2ed for a 0.) page" it chec2s to see if it has alread compiled the page into a servlet$ *hus" 0.) pages %ecome servlets and are transformed into pure 0ava and then compiled" loaded into the server and e&ecuted$

Vous aimerez peut-être aussi