Java concepts and questions
Upcoming SlideShare
Loading in...5

Java concepts and questions






Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

Java concepts and questions Java concepts and questions Document Transcript

  • JAVA notes Prepared by Farag Zakaria Safy Saad Master Student @ Cairo University Faculty of Computers & Information ITI-JAVA Intake 30 farag_cs2005@yahoo.comThis is my own study notes; please keep free to send me any errors exist or any other top you need to add. 1. Key word & reserved word key word is a word whose meaning is defined by the programming language as int,… Reserved word  they have no meaning by programming language as goto,const You cannot use any key word or reserved word in defining variables 2. Allowed access modifiers for the public class are public , final , abstract , strictfp only 3. Defining memory heap size when running java applications -Xms32m defines minimum heap space as 32 mega -Xmx32m defines maximum heap space as 32 mega. Ex. java -Xms32m –Xmx512m Test // run Test class with minimum heap size 32mega and maximum heap size 512 mega bytes 4. Garbage collection JVM parameters -XX:+UseSerialGC run serial garbage collection. -XX:+UseParallelGC runs parallel garbage collection. -XX:+UseParallelOldGC runs parallel compact collector -XX:ParallelCMSThreads=n runs concurrent Mark and Sweep collector with n threads. -XX:+UseConcMarkSweepGC runs Concurrent Mark and Sweep collector. 5. strictfp Marking aclass as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating point s 6. All wrapper classes have no default constructor Wrapper classes constructors are WrapperType(Type) , Wrapper(String). see next example. 7. Byte wrapper class constructors are Byte(byte), Byte(String) ex. Byte b = new Byte(); // compilation error undefined constructor Byte() Byte b = new Byte(3); // compilation error Byte b = new Byte((byte)3); // true Byte b = 21; // true
  • 8. All data types are signed except char or boolean char is integral but unsigned  its range from 0 to (2^7-1) // ^ stands for power9. Identifiers Identifier must begin with one of ( $,_,letter ) only Ex. int %t = 1; compilation error illegal identifier10. Array Declaration int marks[] ; // [] doesnt matter before array name or after it. int []marks; in methods also  int[] myMethod() int myMethod()[] //// [] doesnt matter before method name or after it int myMethod[] () // Compilation error ////////////// int[] marks; // declaration to the compiler marks = new int[2]; // construction of array in runtime == when an array constructed its all elements are initialized to their defaults11. Static import introduced in java 1.5 Ex. instead of using Math.PI you can do = import static Math.PI and use PI in your code without referring to class Math Ex. double pi = PI12. Variable types 1. Member variable  these are the non static variables of the class when an object is constructed(belongs to specific object). The Compiler initialize them to their default values. 2. Automatic variables(local variables)  are the variables of a method when it executed. Must be explicity initialized before being used. 3. Class variables (static variables)  exists even if the class is not instanciated (no object created from this class). Compiler initialize them to their default values; class ABC { int x; // member variable initialized with 0; int z; // class variable initialized with 0; public void printZ() { int z; System.out.println(z); /// compilation error z must be initialized } }13. Compilation units in java source file a. package declaration
  • b. import statements c. class, interface , enum definitions You compile with the file name but run with the class name for example if you have file which contains class ABC { public static void main(String args[]) {} } compilation command is ====== javac to run === java ABC14. Evaluation order Ex. int[] a = {4,4}; int b = 1; a[b] = b = 0; // evaluation from left to right requires that a[b] evaluated first then b so  a[1] = b; and b = 0;  then a[1]=015. Difference between & and && in & both left operand and right operands are evaluated in && the right operand is not evaluated if the left operand is false because the whole operation is false boolean a = true; boolean b = false; if ( b && (a = false) ) { System.out.println("test"); } System.out.println("a = " + a + " , b = " + b); // prints a = true , b = false boolean a = true; boolean b = false; if ( b & (a = false) ) { System.out.println("test"); } System.out.println("a = " + a + " , b = " + b); // prints a = false , b = false16. Difference between | and || | will evaluate two operands || if the first operand is evaluated to true the second operand will not evaluated Example public static void test(String s) { if ( str == null | str.length() == 0)
  • { System.out.println("String is empty"); } } when called with test(null) the first operand is evaluated to ture and the second operand will be evaluated so it will through NullPointerException // public static void test(String s) { if ( str == null // str.length() == 0) { System.out.println("String is empty"); } } when called with test(null) the first operand is evaluated to true and prints String is empty17. switch(x) x must be one of (1. byte 2. short 3. char 4. int) Each of the values specified in the case statements must be of a type compatible with or assignable to the switch expression. Each case value must be a compile time constant/expression, not a variable. Ex. int x = 10; final int a = 5; int b = 10; final int c; //c is final variable but not constant. c = 10; switch (x) { case a: // a must be final (compile time constant) case b: // compilation error (b must be constant) case c: // compilation error c is not a constant default: }18. Conversion & Casting All conversion rules are enforced at compile time. Conversion occurs in the three situations 1. Assignment. 2. Method call. 3. Arithmetic promotions.19. You cannot cast Boolean to any type or vice versa
  • 20. Arithmetic promotion rules 1. For unary operators (++ , -- , …….) - if operand is byte,short,char it is converted to an int. - if it is any other type it is not converted. 2. For binary operands - if one of the operands is double, float, long, the second is converted to the same type ELSE Both operands converted to int.21. + operator with strings and numbers The + operator is syntactically left-associative, the expression a + b + c is always regarded as (a + b) + c. Ex. System.out.println(1 + 2 + " fiddlers"); // prints 3 fiddlers // it is computed as ((1+2)+"fiddlers")  3 + "fiddlers" = 3 fiddlers System.out.println("fiddlers " + 1 + 2); // prints fiddlers 12 // ( ("fiddlers " + 1 ) + 2)  ("fiddlers 1" + 2) = "fiddlers 12"22. Implicit narrowing conversion The implicit narrowing conversion work with the method return statement constants. Ex. class ABC { byte method_1() { return 126; // ok no problems, although 126 is an integer not byte } } Ex.2 class ABC { byte method_1() { final int m = 127; return m; // ok no problems, although m is an integer not byte } } Ex.3 class ABC { byte method_1() { final int m = 128; return m; // compilation error 128 is greater than a byte. } } Ex.4 class ABC {
  • byte method_1() { int m = 126; return m; // compilation error m is not final. // return type must be of type byte or final variable and its value must be allocated to byte value. } }23. Final variable in enhanced for loop Ex. String[] strArr = {"A", "B", "C", "D"}; for (final String s : strArr) { // compiles because it is local variable to the for loop System.out.println(s); } this code compiles and run without errors because it is equal to the following code. String[] strArr = {"A", "B", "C", "D"}; for (int index = 0; index < strArr.length; index++) { final String s = strArr[index]; // compiles because it is local variable to the for loop System.out.println(s); }24. Enumeration is a set of constants(special kind of class) syntax enum WeekDays { Saturday,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday }; // ; is optional enum properties 1. Cannot be defined in a method Ex. public void print() { enum A{} // compilation error enum A cannot be local } 2. Enum cannot extends anther because multiple inheritance is not allowed in JAVA Ex. enum Day{} enum Week extends Day{} // compilation error Defining constructors enum WeekDays { Saturday(1),Sunday(2),Monday(3),Tuesday(4),Wednesday(5),Thursday(6),Friday(7); // ; is mandatory int order;
  • WeekDays(int order) { this.order = order; } public int getOrder() { return order; }}; // ; is optionalEnum types must not be declared abstract; doing so will result in a compile-timeerror.Ex.abstract enum Dog{D1,D2}; // Compile Error// Illegal modifier for the member enum Dog; only public, protected, private & static are// permittedIt is a compile-time error for an enum type E to have an abstract method m as amember unless E has one or more enum constants, and all of Es enum constantshave class bodies that provide concrete implementations of m. It is a compile-timeerror for the class body of an enum constant to declare an abstract methodEx.enum Dog{ abstract void print(); // Compilation error Enum Dog must have constants // because it defines abstract method}Ex. 2enum Dog{ D1, D2; // compilation error D1,D2 must implement abstract method print() abstract void print();}The correct code of the previousenum Dog{ D1 { void print(){} } , D2 { void print(){} }; abstract void print();}
  • 25. Method overriding - Done at runtime - you cannot override methods with their return type only except the following case. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. covariant returns - that is, the specialization of the return type to a subtype (but only for reference types) Ex. class A { A getObject() { System.out.println("A"); return new A(); } } class B extends A { B getObject() // Ok because B is subclass of A // if anything other than A,B it will give compilation error { System.out.println("B"); return new B(); } } in main method A a = new B(); a.getObject(); // will print B - you cannot override methods to be more restricted in visibility. - if you override method that throws exception, the overriding method must 1. Throws the same exception or children of that exception or doesnt throws any exceptions. 2. It may throw any runtime exception as RuntimeException, IndexOutOfBoundsException, … class ABC { protected void method() throws FileNotFoundException {} } class ABChild extends ABC { void method() throws NotSerializableException // two errors here { // 1. You cannot reduce method scope (method must be protected or public)
  • } // 2. Method must throws FileNotFoundException or one of its children } // This method can throw any runtime exception ////////////// interface X { void print(); } class YZ implements X { protected void print() // compilation error you cannot reduce method visibility { // because default access modifier for interface methods is public } } -------------- A compile-time error occurs if a static method hides an instance method(non- static methods) BUT for variables it is permissible for a static variable to hide an instance variable Ex. class A { int x = 90; void print(){} } class B extends A { static int x = 90; // ok no errors static void print(){} // compile time error // This static method cannot hide the instance method from A // This method can hide print() method in class A if it is static. }26. Constructors -- cannot be static -- cannot be final  only allowed access modifiers for constructors are public, protected, private, default Default constructors created if there is no any constructor in the class with the same access modifier of the class otherwise it is not created. Ex. class ABC { public ABC(int x) // because existence of this constructor default const. doesnt {} created }
  • if you tried ABC a = new ABC(); in main it will give compilation error because ABC() is undefined. this() used to call another constructor in the same class and must appear in the first line of the constructor super() used to call the constructor of the super class and must appear in the first line of the constructor. Ex. class A { A(int x) // because this constructor default didnt created {} } class B extends A { B() // compilation error because there is embedded super() and default constructor for A is not created {} // to remove this error put call super(0); in B constructor } when creating an object from a class the compiler creates the super and member classes first then creates the current object27. Accessing protected member of super class from subclass via super class reference. A method in subclass has access to the protected instance members/methods of its superclass, but only if it accesses them via a subclass object Ex. package points; public class Point { protected int x, y; } package threePoint; import points.Point; public class Point3d extends Point { protected int z; public void delta(Point p) { p.x += this.x; // compile-time error: cannot access p.x p.y += this.y; // compile-time error: cannot access p.y // x,y can be accessed but using reference from subclass Point3d because it is // outside its package } public void delta3d(Point3d q) { q.x += this.x; q.y += this.y;
  • q.z += this.z; } }28. Objects and classes Data Hiding  defining the scope visibility of variables to public, protected, private Encapsulation  aggregation of data and behavior. (data hiding) + How to access these data(setters, getters, ….). is-a  relationship indicates super class (Inheritance). has-a  relationship describes the member variables.(Aggregation). Overloading is the reuse of function name with different types and numbers of parameters.(done at compilation time)  Cant be done with return type only Public level classes cannot be private or protected because it has no meaning Ex. public class XYZ {} private class ABC /// compilation error private is not allowed here {} Inner classes is a class inside class or method. - when you create an object from inner class you must have an object from the outer class. - It is a compile-time error if a static class contains a usage of a non-static member of an enclosing class. - Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier class Outer { class Inner { void print() {System.out.println("Inner");} } } // to create object from Inner inside main Outer out = new Outer(); Inner inner = Inner(); // or Inner in = new Outer().new Inner(); Local Inner classes (inside methods) class Outer { int a; void print(final int z , int x) { final int xn = 9; int abc = 0;
  • class Inner // allowed to access members of Outer class and final variables { //inside the method print and final variables of its parameters } // only a , z, xn variables are visible to Inner class }}Static Inner classesclass Outer{ static class Inner { }}// to create object from Inner  Outer.Inner in = new Outer.Inner();////////////////////// Local inner classes override inner classes (see shadowing)class Outer{ class Inner { void print() { System.out.println("Inner class"); } } void printMessage() { class Inner { void print() { System.out.println("Local Inner class"); } } Inner in = new Inner(); in.print(); //// will print  Local Inner class } // if local Inner class is not exist it will print  "Inner class"}inner classes cannot have static declarations unless they are compile-time constant fieldsEx.class Outer{ class Inner { static final int x = 3; // OK no compilation errors static int x; // compilation error  inner classes cant have static declarations static void getX() // compilation error { return x;
  • } } static class NestedButNotInner { static int z=3; // OK no errors, not an inner class } interface NeverInner{} // interfaces are never inner because they are static by // default } - Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language - Member interfaces are always implicitly static so they are never considered to be inner classes. Annonymous classes can be declared to extends another class or to implement a single interface BUT not both. Annonymous classes cannot have constructors because the name of the constructor is the same as the name of the class and they didnt have names. Nesting Classes A compile-time error occurs if a class has the same simple name as any of its enclosing classes or interfaces Ex. class Test { class Test{} /// compilation error The nested type Test cannot hide an enclosing type }29. Class Instance Initializers It is compile-time error if an instance initializer of a named class can throw a checked exception unless that exception or one of its supertypes is explicitly declared in the throws clause of each constructor of its class and the class has at least one explicitly declared constructor. An instance initializer in an anonymous class can throw any exceptions. Ex. class Test { { throw new Exception(); // compilation error } }30. Final fields 1. A field can be declared final. Both class and instance variables (static and non-static fields) may be declared final. 2. It is a compile-time error if a blank final class variable is not definitely
  • assigned by a static initializer of the class in which it is declared. 3. A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs. Ex. class Test { final int x; public Test() { x = 10; // x must be assigned value in the constructor or compile time error occur } } Ex.2 class Test { static final int x; public Test() { x = 3; // compile time error  final field x cannot be assigned } static { x = 10; // x must be assigned value in the static initializer or compile time error occur } }31. Interface is a collection of constants and abstract methods. interface MyInterface { // final , static , public  only allowed for variables // variables must have initial value public static final int x = 0; // public static final is default for variables // public abstract are default for methods // } interface ABC { int a; //// compilation error a must be initialized because its default is // public static final } Static by default so that they cannot be defined in Inner classes or inside methods Ex. class Outer {
  • class Inner { interface X // Compilation error {} } } protected and private declarations are not allowed in interfaces, only allowed public and abstract interface X { protected void print(); // Compilation error protected and private is not allowed. }32. Static class loading vs dynamic class loading Static class loading done using new operator Ex. Car c = new Car(); // throws NoClassDefFoundException if Car cannot be found Dynamic class loading done using reflection Class.forName(String classname) // throws ClassNotFoundException33. Static blocks (or static initializer) executed only once before constructors to initialize static fields.34. Null interfaces (marker interfaces), (Empty interfaces) They dont have any function declaration on them just an empty interface. They are treated differently in compiler such as Serializable interface. Ex. interface ABC { }35. Abstract class // is a collection of abstract and non-abstract methods and variables Abstract class Interface May contain implemented methods All methods are abstract Variables can be modified inside objects Variables are final static by default Cannot extends an interface Cannot implements another interface Can implements an interface Can extends another interface(one or more) May have no methods May have no methods (Marker interface) May have a constructor Cannot have constructors Static by default so that cannot defined inside Inner classes because static is not allowed in Inner classes.36. Abstract classes and interfaces are away to defer implementation to sub classes They CANNOT be final because their methods should be overridden by children classes.37. … operator  for method parameters only used to pass variable length of arguments to method void print(int … x) // you can call it with print(1), print(1,2),print(1,2,…….) // or print(new int[]{1,2,3,4}); // void print(int x…)  gives compilation error since … is not defined
  • ///////////// void print(int… x){} void print(int x){} // No errors void print(int[] x){} // compilation error (duplicate method) the same as print(int…x)38. Checked Exceptions are exceptions that doesnt descend from RuntimeException which must be handled by try and catch or throws-declaration.39. Runtime Exceptions(Unchecked Exceptions). avoidable exceptions that are your own fault.(they should never happen) Ex. RuntimeException, ArrayIndexOutOfBoundsException,…………….. Class Error and its subclasses also are unchecked.40. Finally block in exceptions finally{} block executed in all circumstances. what prevents finally block from completion a. death of the current thread. b. Execution of System.exit(). b. Turning off the computer.41. Exception’s subclasses have to be caught first before the General Exception Ex. FileNoFoundException is inherited from the IOException try { } catch (IOException exp) // compilation error { } catch(FileNoFoundException exp) // Need to be catched // first before IOException // Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException { }42. If there is an overriding method in the sub class and this method throws an exception in the super class then it must throw the same exception which it throws in the super class or throw an exception which is a sub class of the exception which it throws in the super class. Ex. class ABC { public void printABC() throws MyException {} } class XYZ extends ABC {
  • public void printABC() // it must throws MyException or any child of it or throws // None or any runtime exception }43. Volatile A field may be declared volatile, in which case the Java memory model ensures that all threads see a consistent value for the variable. When any thread accesses volatile fields it performs automatic synchronization (automatic locking). A compile-time error occurs if a final variable is also declared volatile. Ex. class ABC { final volatile int x = 10; // compilation error }44. Static If the keyword this or the keyword super occurs in an initialization expression for a class variable, then a compile-time error occurs. Ex. class ABC { int x = 10; } class XYZ extends ABC { int a = 10; static int z = super.x; // compilation error (super and this cant be used in static context) static int y = this.a; // compilation error }45. Initializers for Instance Variables (related to classes) Initialization expressions for instance variables may use the simple name of any static variable declared in or inherited by the class, even one whose declaration occurs textually later. Ex.1 class Test { float f = j; // no compilation error static int j = 10; } Ex.2 class Test { int i = j; // compilation error -- incorrect forward reference int j = 10; }
  • 46. Abstract Methods 1. It is a compile-time error for a private method to be declared abstract. 2. It is a compile-time error for a static method to be declared abstract. 3. It is a compile-time error for a final method to be declared abstract. 4. An abstract class can override an abstract method by providing another abstract method declaration.47. Native Methods - A method that is native is implemented in platform-dependent code(in another programming language). - A compile-time error occurs if a native method is declared abstract. Ex. class Test { abstract native void print(); // compile error }48. Run method of threads doesnt throws any checked exceptions but it may throw any runtime exception class ABC implements Runnable { public void run() throws Exception // compilation error } class ABC implements Runnable { public void run() throws RuntimeException // NO ERRORS public void run() throws ArrayIndexOutOfBoundsException // NO ERRORS }49. Assertion provide a convenient mechanism for verifying that a classs method are called correctly and used commonly to check 1. Preconditions 2. Post conditions 3. Class invariants (a constraint on a classs state that must be met before and after execution of any non-private method of a class). ex. assert Exp1; assert Exp1:Exp2; // Exp1 must be boolean type // Exp2 may have any type;50. Parameters passing in java In java  parameters passing is by value BUT if you pass a reference the jvm makes a copy of the reference (You can use it inside function but you cannot assign it another object). class Value { public int i = 15;
  • } public class Test { public static void main(String[] args) { Test t = new Test(); t.first(); } public void first() { int i = 5; Value v = new Value(); v.i = 25; second(v,i); System.out.println(v.i); // prints 20 the last value assigned to v.i in // second() function } public void second(Value v, int i) { i = 0; v.i = 20; Value val = new Value(); v = val; // ok no compilation error but visible inside function only System.out.println(v.i); // prints 15 because v assigned to a new object } }51. instanceof  used to test type of objects not references public class Test { static Test t1; public static void main(String[] args) { Test t2 = new Test(); if ( t1 instanceof Test) { System.out.println(" t1 instanceof Test = true"); } else { System.out.println(" t1 instanceof Test = false"); // will be printed // because t1 is a reference (doesnt refer to any object) }
  • if ( t2 instanceof Test) { System.out.println("t2 instanceof Test = true"); // will be printed because t2 // holds an object } } } // Example 2 class Cup { } class PassionCup {} in main Cup c = new PassionCup(); PassionCup pc = new PassionCup(); if ( c instance of PassionCup ) { System.out.println("c instanceof PassionCup is true"); // will be printed because instanceof // test objects not references } if ( pc instanceof Cup ) { System.out.println("pc instanceof Cup is true"); // will be printed because of // PassionCup extends Cup }52. Auto boxing Boxing is the automatic assignment of a primitive value to a compatible wrapper type. Ex. Integer x = 1; Unboxing  is the automatic extraction of a wrapped value. Integer z = 1; int y = z; Boxing pool If the value that is being boxed is true, false, a byte, a char in the range u0000 to u007f, or an int or short number between -128 and 127 then the object is pooled.
  • Ex. Integer i1 = 2; Integer i2 = 2; Integer i3 = 200; Integer i4 = 200; System.out.println( i1 == i2 ); // will print true because objects are not pooled System.out.println( i3 == i4 ); // will print false because objects are not pooled so references are not equal.53. Mutable & Immutable Mutable  once the object is created you can edit it. Immutable  once the object is created you cant edit or modify it. Ex. String contains immutable string StringBuffer  contains mutable strings and is thread safe (all of its methods are synchronized). StringBuffer sb = "abc"; // compilation error cannot convert from String to StringBuffer StringBuilder  contains mutable strings but is not thread safe. (faster than StringBuffer) StringBuilder sb = "ab" ; // compilation error cannot convert from String to StringBuilder To apply Immutable concept to your own defined objects. Ex. if you have class Person with first name and last name and you need to make sure that all objects of this class are immutable see the following class code class Person { String firstName; String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } String getFirstName() { return firstName; } String getLastName() { return lastName; } } because there is no setters in this class, once an object is created you cannot modify it54. Final classes cannot be extended and final methods cannot be overridden
  • 55. The class must be abstract if 1. The class has one or more abstract methods. 2. The class inherits abstract methods and doesnt provide an implement to any of them. 3. Class implements an interface and dont implement every method.56. Static features (static variables, static methods) Static features belong to the class not to its instances so it exists before any object (instance) of the class is created. Static Methods 1. May access only the static data of its class, it may not access non-static data. 2. May call only the static methods of its class, it may not call non-static methods. 3. Static methods has no this pointer (reference). 4. Static methods may not be overridden by non-static methods57. Serialization is the process of storing the state of a java object by converting it to byte stream. Rules of serialization 1. Static fields are not serialized because they are not belonging to any object. 2. Transient fields are not serialized. 3. Fields from the base class are handled only if those are serializable. What is preserved when an object is serialized? 1. Only the objects data are preserved. 2. Methods and constructors are not part of the serialized stream. 3. Class information is included. What is the difference between serializable and externalizable Serializable -- provides the default serialization mechanism of the compiler(JVM). Externalizable -- provides customized serialization mechanism which allows you to implement your own protocols through the methods writeExternal (…) and readExternal (…) Version Control All serialized objects are automatically assigned a unique identifier. If the identifier of the class doesnt equal the identifier of the serialized object a is thrown. Ex. class ABC implements Serializable { int x = 20; } then you create an object ABC myObject = new ABC() ; and wrote it to a file the compiler assigns default value for hidden variable serialVersionUID . And after that another variable is added to the class.
  • class ABC implements Serializable { int x = 20; int y = 300; } -- at this point the compiler assigns another value to serialVersionUID if you tried to read myObject now will be thrown To prevent this exception you should add serialVersionUID to ABC class Ex. class ABC implements Serializable { private static final long serialVersionUID = 1; int x = 20; } if you create and object ABC myObject = new ABC(); and wrote it to a file. and you add another data to ABC class class ABC implements Serializable { private static final long serialVersionUID = 1; int x = 20; int y = 300; } Now if you need to read the stored old object from file the compiler checks if serialVersionUID of the stored object is equal to serialVersionUID of the new class the compiler reads the old object and initialize the new features to their default vales (y will be initialized to 0 NOT 300 )58. Objects of some system-level classes are not serializable59. Threads - Single threaded java program has one entry point (main function) and one exit point. - Multi-threaded java program has one entry point (main function) and multiple end points.60. A thread can enter the waiting state by the following ways: 1. Invoking its sleep() method, 2. By blocking on I/O 3. By unsuccessfully attempting to acquire an object’s lock 4. By invoking an object’s wait() method. 5. It can also enter the waiting state by invoking its (deprecated) suspend() method.61. What is the difference between preemptive scheduling and time slicing?
  • Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then re-enters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.62. What invokes a thread’s run() method? After a thread is started, via its start() method of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.63. What is daemon thread and which method is used to create the daemon thread? Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon() When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads.64. How would you implement a thread pool? public class ThreadPool implements ThreadPoolInt This class is an generic implementation of a thread pool, which takes the following input a) Size of the pool to be constructed b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool. This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.65. Is there a separate stack for each thread in Java? Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations, called activation records or stack frame. The activation record contains pertinent information about a method like local variables.66.67. How you can run Garbage collection? I can run GC through calling System.gc() or Runtime.getRuntime().gc(); but this didnt guarantee that GC will run it only put its thread in ready state. GC informs the object when it is about destroying it by calling its finalize() method68. Reflection Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. see Class,Method, Constructor,Member  to know the attributes ,methods and constructors of an object in runtime69. Collections Set - didnt contain duplicates and may contain at most one null value.
  • - A Set stores elements in an unordered way and does not contain duplicate elements. Map  is set of objects that map key with value, cannot contain duplicate keys List - set of elements that maintain its insertion order. - stores elements in an ordered way but may contain duplicate elements.70. Generics An enhancement to the type system that supports operations on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting. Ex. ArrayList<String> myList = new ArrayList<String>(); the previous generics restrict the type of objects in this ArrayList to String at compile time and prevent casting Objects to String. Sub-typing is not allowed in generics Ex. ArrayList<Object> myList = new ArrayList<String>(); // compile error // cannot covert from ArrayList<String> to ArrayList<Object> Inheritance relationship is maintained between collection elements. Ex. class A {} class B extends A {} class C extends B {} ArrayList<A> myList = new ArrayList<A>(); ArrayList<A> myList = new ArrayList<B>(); // compilation errors myList.add(new A()); // ok no errors myList.add(new B()); // ok no errors myList.add(new C()); // ok no errors Wildcards ?  means collection of unknown type Ex. public void printCollection(ArrayList<Object> list) {} ArrayList<Object> list1 = new ArrayList<Object>(); ArrayList<String> list2 = new ArrayList<String>(); when calling printCollection function printCollection(list1); // ok no errors printCollection(list2); // compilation error to prevent the last error see the following code public void printCollection(ArrayList<?> list) // ? maps to any type { // the only allowed here is to read elements of list as Objects // add elements to list is not allowed(list.add(new Object()) gives compilation errors)
  • } ArrayList<Object> list1 = new ArrayList<Object>(); ArrayList<String> list2 = new ArrayList<String>(); when calling printCollection function printCollection(list1); // ok no errors printCollection(list2); // ok no errors Bounded wildcards <? extends ...> bounds unknown type to be subtype of another type Ex. public void printCollection(ArrayList<? extends Object> list) // maps to any subtype of Object { // the only allowed here is to read elements of list as Objects // add elements to list is not allowed(list.add(new Object()) gives compilation errors) } ArrayList<Object> list1 = new ArrayList<Object>(); ArrayList<String> list2 = new ArrayList<String>(); when calling printCollection function printCollection(list1); // ok no errors printCollection(list2); // ok no errors71. Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements.72. Properties class The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.73. Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You cannot remove elements from Enumeration.74. What method should the key class of Hashmap override? The methods to override are equals() and hashCode().75. What is the difference between Enumeration and Iterator? The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn’t. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only.76.77. Shadowing(Hiding) A variable is shadowed if there is another variable with the same name that is closer
  • in scope. In other words, referring to the variable by name will use the one closest inscope , the one in the outer scope is shadowed.Ex.1class A{ String name="A"; String getName() { return name; }}class B extends A{ String name="B"; // shadows the name variable of class A String getName() // really this is the same as overriding but for variables and declarations { return name; }}A a = new B();System.out.println(a.getName()); // will print B due to shadowingEx.2class Outer{ class Inner { void print() { System.out.println("Inner class"); } } void printMessage() { class Inner { void print() { System.out.println("Local Inner class"); } } Inner in = new Inner(); // due to shadowing this is the Inner class inside this method in.print(); //// will print  Local Inner class }}
  • 78. Double indirection in most JVMs, the reference value is actually the address of and address. The second address refers to the real data.79. Code exercises difference between null and "" in string String s = null; s+= "abc"; System.out.println(s); /// will print nullabc; String s = ""; s+= "abc"; System.out.println(s); /// will print abc; Division by zero Dividing integer by zero int i=12; System.out.println( i/0 ); // will give ArithmaticException division by zero // with integers Dividing floats and doubles by zero double d = 12; System.out.println( d/0 ); // gives Infinity with floating and double variables Division remainder with floats and doubles int i=12; System.out.println( i%0 ); // will give ArithmaticException division by zero // with integers Division remainder with floats and doubles double d = 12; System.out.println( d%0 ); // gives NaN with floating and double variables Casting Object to interface Ex.1 interface MyInterface { } class MyObject { } in main() MyObject o = new MyObject(); MyInterface myInterface = (MyInterface)o; // no compilation errors but it will throw // ClassCastException at runtime The idea is that even if the class does not implement the interface, but one of its subclass might. If the actually object class does not implement the interface then
  • you will get a ClassCastException error at runtime. Ex.2 interface MyInterface { } final class MyObject { } in main() MyObject o = new MyObject(); MyInterface myInterface = (MyInterface)o; // compilation error cannot cast MyObject // to MyInterface The compiler knows at compile time exactly what interfaces are implemented by the final class. If the compiler can determine at compile time that the final class can never be instanceof the interface, thats a compile time error. Static with null references Ex. public class Test { static String name="Farag"; static Test getName() { System.out.println("Getting Name"); return null; } public static void main(String[] args) { System.out.println(getName().name); // it will executes without NullPointerException } } when getName() returns null reference and calling static variable name using this reference the compiler recognizes that static variable name is not associated with an object so it will execute it without throwing NullPointerException casting array of primitives to array of objects. Ex. Object c = new long[4]; // OK Object[] c1 = new Long[4]; // OK Object[] c = new long[4]; // compilation error cannot convert from long[] to Object[]80. Thread safe and non thread safe java classes Thread safe Not Thread safe Vector ArrayList Hashtable Hashmap StringBuffer StringBuilder
  • 81. Vector vs. ArrayList Vector ArrayList Synchronized Not synchronized Implement the List interface. Implement the List interface. implemented using dynamically resizable implemented using dynamically resizable arrays arrays providing fast random access and fast providing fast random access and fast traversal traversal data is retrieved using the elementAt() data is retrieved using the get() method method has a default size of 10 has no default size82. Difference between Hashtable & HashMap Hashtable HashMap Doesnt store null values Store null values Ex. ht.put("f",null); will throw Ex. hm.put("f",null); compiles and runs OK NullPointerException at runtime without exceptions Synchronized Not synchronized doesn’t allow nulls allows null values as key and value does not guarantee that the order of the map will remain constant over time. enumerator for the Hashtable isn’t fail- Iterator in the HashMap is fail-safe safe can be synchronized by Map m = Collections.synchronizeMap(hashMap);83. Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.84. String pooling & computation if you create String as String s="my string"; the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returned. If the string does not exist in the pool, a new String object instantiates, then it is placed in the pool.  Concatenation of constant Strings computed in compile time.  Concatenating string expressions is computed at runtime. Ex. String hello = "Hello"; String lo = "lo"; System.out.println( hello == ( "Hel" + "lo") ); // prints true (pool computed at compile time)
  • System.out.println( hello == ( "Hel" + lo ) ); // prints false (pool computed at runtime) String computation rules 1. Literal strings within the same class in the same package represent references to the same String object. 2. Literal strings within different classes in the same package represent references to the same String object. 3. Literal strings within different classes in different packages likewise represent references to the same String object. 4. Strings computed by constant expressions are computed at compile time and then treated as if they were literals. 5. Strings computed by concatenation at run time are newly created and therefore distinct.85. JDBC JDBC architecture decouples an abstraction from its implementation so that the implementation can vary independent from the abstraction this is an example of adapter design pattern. JDBC API provides the abstraction and the JDBC drivers provide the implementation. So new drivers can be plugged-in to the JDBC API without changing the client code. Statements. 1. Statement (regular statement) Statement stmt = myConnection.createStatement(); stmt.executeQuery(""); or stmt.execute(""); or stmt.executeUpdate(""); 2. PreparedStatement more efficient due to pre-compilation of sql. PreparedStatement pstmt = myConnection.prepareStatement("select * from emp where id=?"); more secure because it prevent sql injection attack 3. CallableStatement used to call stored procedure CallableStatement callableStmt = myConnection.prepareCall("{call proc_showbooks}"); callableStmt.executeQuery(); Ex. CallableStatement cs = myConnection.prepareCall("{ call abc(?, ?)}"); cs.setLong(1, customerID); cs.registerOutParameter(2, java.sql.Types.NVARCHAR); cs.execute(); String customerName = cs.getString(2); --- create or replace procedure abc(custId in number, custName out nvarchar2(100))86. DataSource DataSource DriverManager a DataSource object has properties that identify and describe the data source it represents Work with JNDI and managed separately Managed by the application code from application (Ex. by Application Server) An application does not need to hardcode Driver information are hardcoded in driver information application code Connection pooling and distributed No connection pooling
  • transactions No distributed transactions87.88. What is the difference between DOM and SAX parsers DOM SAX Object based Event Based Creates tree of xml in memory Dont so it is faster Read/write Read only89. Weak reference is one that does not prevent the referenced object from being garbage collected. You might use them to manage a HashMap to look up a cache of objects.90. public class Test { public void print(String match) { System.out.println("--== String ==--"); } public void print(StringBuffer match) { System.out.println("--== String Buffer ==--"); } public static void main(String[] args) { Test t = new Test(); t. print (null); // Compilation error The method match(String) is ambiguous } }91. public class Test { public void print(Object match) { System.out.println("--== Object ==--"); } public void print(String match) { System.out.println("--== String ==--"); } public static void main(String[] args) { Test t = new Test(); t. print (null); // will print --== String ==-- } }
  • 92. A hidden class (static) method can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods. The example: class Super { static String greeting() { return "Goodnight"; } String name() { return "Farag"; } } class Sub extends Super { static String greeting() { return "Hello"; } String name() { return "Ali"; } } public class Test { public static void main(String[] args) { Super s = new Sub(); // Super has the declaration of static method System.out.println(s.greeting() + ", " +; // prints Goodnight, Ali } }93. final volatile int x; // compile time error // The field x can be either final or volatile, not both94. public class Doubler { static int two() { return two(1); } private static int two(int i) { return 2*i; } } class Test extends Doubler { public static long two(long j) {return j+j; } public static void main(String[] args) { System.out.println(two(3)); System.out.println(Doubler.two(3)); // compile-time error // The method two(int) from the type Doubler is not visible } }95. class ColoredPoint { int x, y; byte color; void setColor(byte color) { this.color = color; } } class Test { public static void main(String[] args) {
  • ColoredPoint cp = new ColoredPoint(); byte color = 37; cp.setColor(color); cp.setColor(37); // compile-time error } } Here, a compile-time error occurs for the second invocation of setColor, because no applicable method can be found at compile time. The type of the literal 37 is int, and int cannot be converted to byte by method invocation conversion.96. Overloading Ambiguity class Point { int x, y; } class ColoredPoint extends Point { int color; } class Test { static void test(ColoredPoint p, Point q) { System.out.println("(ColoredPoint, Point)"); } static void test(Point p, ColoredPoint q) { System.out.println("(Point, ColoredPoint)"); } public static void main(String[] args) { ColoredPoint cp = new ColoredPoint(); test(cp, cp); // compile-time error } } This example produces an error at compile time. The problem is that there are two declarations of test that are applicable and accessible, and neither is more specific than the other. Therefore, the method invocation is ambiguous. Solutions is to add third method static void test(ColoredPoint p, ColoredPoint q) { System.out.println("(ColoredPoint, ColoredPoint)"); } =================================================================== General Questions(allapplabs)97. What if the main method is declared as private? The program compiles properly but at runtime it will give "Main method not public." message.98. What if the static modifier is removed from the signature of the main method? Program compiles. But at runtime throws an error "NoSuchMethodError".99. What if I do not provide the String array as the argument to the method? Program compiles but throws a runtime error "NoSuchMethodError".
  • 100. If I do not provide any arguments on the command line, then the String array of Main method will be empty or null? It is empty. But not null. Ex. class Test { public static void main(String[] args) { System.out.println(args.length); // if you run with java Test // it will print 0 } } 101. Can I import same package/class twice? Will the JVM load the package twice at runtime? One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class. 102. Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*? No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of its subpackage. 103. Can main method be declared final? Yes, the main method can be declared final, in addition to being public static. 104. 105. S 106. S 107. S 108. A 109. 110. 111.To be seen laterThread.setDefaultUncaughtExceptionHandler(newThread.UncaughtExceptionHandler()References 1. The Java Language Specification, Third Edition
  • 2. Java community process JAVA Docs5. Certification books and sites8.