Tips

Share Embed Donate


Short Description

tips to pass java SE 6...

Description

QuickRevisionNotes

Page 1 of 16

Print

SCJP 5.0 Quick Revision Notes Objective: Declarations, Initialization and Scoping

1.

The static import construct allows unqualified access to static members without inheriting from the type that contains those static members. Static imports can be performed for individual members or for a group of members. For example: import static java.lang.Math.PI; // Here we import the constant PI individually from the Math class. import static java.lang.Math.*; //Here we import all the static members from the Math class.

2.

There are three top-level elements that may appear in a compilation unit. None of these elements is mandatory. If they are present, then they must appear in the following order: • package declaration import statements • • class definitions

3.

The filed members in an interface are implicitly public, final, and static. Interface methods cannot be native, static, synchronized, final, private, and protected. They are implicitly public, abstract, and non-static.

4.

A constructor • • • •

5.

6.

has has can can

the same name as the class. no return type. be overloaded, but not inherited. have any access, including private.

Abstract classes a. cannot be instantiated. b. have one or more constructors. c. may or may not have abstract methods. d. may or may not have non-abstract methods. A default constructor is created by the compiler only if you have not provided any other constructor in the class. The default constructor has no arguments and has the same access modifier as the class.

7.

A class can implement any number of interfaces, but it can extend only one class. An interface can extend any number of interfaces, but it cannot implement another interface.

8.

A concrete (non-abstract) class implementing an interface has to implement all the methods declared in the interface. A concrete class extending an abstract class must define all the abstract methods defined in the latter.

9.

An enumeration is defined using the enum keyword, as shown below. For example, enum Fruit{ Apple,

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 2 of 16

Mango, Banana } Variable of the defined enum type can then be created like this. Fruit f; 10.

All enumerated types implicitly extend the java.lang.Enum class.

11.

You can add methods to enums.

12.

Invoking the values() method on an enum returns an array of all the values in that type.

13.

When an array is created, all its elements are initialized to their default values, even if the array is declared locally. Static and instance variables of a class are also initialized with a default value. Local variables are never given a default value; they have to be explicitly initialized before use.

14.

A final class cannot be extended, so it is forbidden to declare a class to be both final and abstract.

15.

According to the JavaBean naming standards, if the property name is 'x' and the type is ‘Type’, the accessor method is of the form Type getX() and the mutator method is of the form void setX(Type newValue) However, a boolean property uses a different convention boolean isX() void setX(boolean newValue)

16.

Variable arguments (varargs) allow you to specify a method that can take multiple arguments of the same type and does not require that the number of arguments be predetermined. For example, the format method is now declared as follows: public static String format(String pattern, Object... arguments); The three periods(ellipsis) after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

17.

You can only use one ellipsis per method. For example, the following is not allowed: public Computer(String companyName, String model, String... components, double... componentPrices) Also, the ellipsis must appear as the last argument to a method.

18.

It is legal to call the method without passing in the varargs parameter. For example, we can invoke Computer myComp=new Computer("HCL", "Celeron Model xxx"); even if the only constructor defined in the class is

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 3 of 16

public Computer(String companyName, String model, String... features) 19.

So, a variable-length argument can take from zero to n arguments. An array can be passed in as the varargs parameter.

20.

Static methods and static variables of a class can be used without having any instances of that class at all. A static method cannot access non-static variables of the class. Static methods cannot be redefined as non-static in subclasses, and vice versa.

21.

An identifier is composed of a sequence of characters where each character can be a letter, a digit, an underscore, or a dollar sign. An identifier cannot be a Java keyword and it cannot start with a digit. It is possible to use class names as identifiers even though it is not a smart choice. For Example: number, $$abc, _x, String // Legal new, 15bb, he-he // Illegal

22.

To get the array size, use the array instance variable called length. Arrays are indexed beginning with zero and end with length-1. Whenever you attempt to access an index value outside the range 0 to n-1, an ArrayIndexOutOfBoundsException is thrown.

23.

The return type of an overriding method should match that of the overridden method except in the case of covariant returns, as discussed in the next point. Return types of overloaded methods can be different, but changing only the return type is not legal. The arguments should also be different.

24.

Covariant return types allow a method in a subclass to return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

25.

A method that declares a class as a return type can return any object which is of the subclass type. A method that declares an interface as a return type can return any object whose class implements that interface.

26.

A static nested class is a static member of the enclosing class. It does not have access to the instance variables and methods of the class. MyOuter.MyNested n = new MyOuter.MyNested();

27.

As the above example shows, a static nested class does not need an instance of the outer class for instantiation.

28.

To instantiate a non-static inner class, you need an instance of the outer class. A non-static inner class has access to all the members of the outer class. From inside the outer instance code, use the inner class name alone to instantiate it: MyInner myInner = new MyInner(); From outside the outer instance code, the inner class name must be included in the outer instance:

MyClass myClass = new MyClass(); MyClass.MyInner inner = myClass.new MyInner();

Objective: Flow Control

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 4 of 16

29. The argument to the switch statement can be a byte, a short, a char, an int, or an enum type. The argument passed to the case statement should be a literal or a final variable. 30. The switch statement now supports the use of enum values. You must not preface each enumerated type with the enum class name, in the case statement. So it is ‘case A’ and not ‘case Grade.A’. 30. When a break statement is encountered, the control moves out of the switch statement. If no break statement is encountered, all the case statements are executed till a break is encountered or the switch statement ends. 31. The body of the ‘while’ loop may not be executed even once. For example: while(false){} The body of the ‘do-while loop’ is always executed at least once. For example: do {

} while(false);

32. The syntax of the ‘for’ loop is as follows: for(expr1; expr2; expr3) { body } where expr1 is the initialization expression, expr2 is the conditional test, and expr3 is the iteration expression. Any or all of these three sections could be omitted and the code would still be legal. For example: for( ; ; ) {}

// an endless loop

33. The enhanced ‘for’ loop (also known as the ‘for-each’ loop) provides a simpler way to iterate over collections, arrays or other Iterable objects. It has the following syntax for ( Type Identifier : Expression ) { Statements } Here Expression must be an instance of a new interface called java.lang.Iterable, or an array. 34. The break statement is used to exit from a loop or a switch statement. The continue statement is used to stop just the current iteration of a loop and to proceed to the next one. 35. Breaking to a label (using break ;) means that the loop at the label will be terminated and any outer loop will keep iterating. While a continue to a label (using continue ;) proceeds with the execution of the next iteration of the labeled loop. 36. An assertion is a conditional expression that should evaluate to true if and only if your code is working correctly. If the expression evaluates to false, an error is signaled. Assertions are like error checks, except that they can be turned completely off, and they have a simpler syntax. 37. Assertions can be used in two forms as mentioned below: assert Expression1 ; assert Expression1 : Expression2 ; Expression1 must always yield a boolean value. Expression2 can be anything which results in a value. The value is used to generate a String message that displays more debugging information.

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 5 of 16

38. One of the most common uses of assertions is to ensure that the program remains in a consistent state. Assertions are not alternative to exception handling, rather complementary mechanism to improve discipline during the development phase. 39. Assertions may be used in the following situations: 

To enforce internal assumptions about the current state of data structures



To enforce constraints on arguments to private methods



To check conditions at the end of any kind of method



To check for conditional cases that should never happen



To check related conditions at the start of any method



To check things in the middle of a long-lived loop

40. Assertions may not be used in the following situations: •

To enforce command-line usage



To enforce constraints on arguments to public methods



To enforce public usage patterns or protocols



To enforce a property or a piece of user-supplied information



As a shorthand for tests, such as, if (something) error();



As an externally controllable conditional statement



As a check on the correctness of your compiler, operating system, or hardware, unless you have a specific reason to believe there is something wrong with any of them and you are in the process of debugging it.

41. All exceptions are derived from the java.lang.Throwable class. A java.lang.Error indicates serious problems that a reasonable application should not try to catch. For example: StackOverflowError. 42. A java.lang.RuntimeException and its subclasses are unchecked exceptions. All remaining exceptions are checked exceptions. Checked exceptions should either be handled by declaring the exception using the throws keyword in the method declarator, or by using try/catch blocks. Unchecked exceptions are not required to be handled. 43. The try block contains the code which might throw an exception. One or more catch clauses can be provided to handle the different exception types that might be thrown from the code in the try block. All the catch blocks must be ordered from the most specific exception to the most general one. 44. A try block should have either a catch block or a finally block, but it’s not compulsory to have both. 45. The finally block is always executed after the try block and all catch blocks have been executed, whether an exception is thrown or not. The only exception is when the System.exit() is invoked before it. 46. The checked exceptions that a method can throw must be declared using the ‘throws’ keyword. To throw an exception explicitly from the code, use the ‘throw’ keyword.

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 6 of 16

For example: void f() throws Exception { if(x > y) throw new Exception(); } 47. More than one exception can be listed in the throws clause of a method using commas. For example: public void myMethod() throws IOException, ArithmeticException 48. You can also rethrow the same exception which you caught. For example: catch(IOException e) { throw e; } 49. NumberFormatException is thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. It is a subclass of IllegalArgumentException. 50. AssertionError is thrown to indicate that an assertion has failed. StackOverflowError is thrown when a stack overflow occurs because an application recurses too deeply and exhausts all the available stack space. 51. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.

Objective: API Contents

52. All the wrapper classes except the Character class have two constructors; one that takes a primitive value and one that takes a String representation of the value as argument. 53. Instances of the String class in Java are immutable. Once an instance is created, the wrapped string value cannot be changed. But the StringBuffer class provides support for mutable string instances. 54. StringBuilder is almost identical to the StringBuffer class, however it isn't thread-safe, while StringBuffer is. If you know you are going to create a string within a single thread, it is better to use StringBuilder. However, if it involves multiple threads, using StringBuffer is recommended. 55. Autoboxing is the automatic conversion process between primitive types and primitive wrapper types. A boxing conversion converts a value of a primitive type to the corresponding value of the wrapper type.An unboxing conversion converts a value of a wrapper type to the corresponding value of the primitive type. 56. A File object represents a file's name and path, not the physical file on disk. Thus, you can create a File object to represent a name and a path, even if a file of that name at the given path doesn't exist. This also means that creating a new File object does not result in the creation of a new physical file on the disk. 57. Some useful methods provided by the File class are – • • • • •

boolean boolean boolean boolean boolean

• • • •

String String String String

exist(); canWrite(); canRead(); isFile(); isDirectory(); getName(); getPath(); getCanonicalPath(); getAbsolutePath();

- Specifies if the file exists - Specifies if the file can be written to - Specifies if the file can be read - Specifies if the File object represents a file - Specifies if the File object represents a directory -

Returns Returns Returns Returns

the the the the

name of the file (excluding path) abstract path name of the file canonical name of the file with path absolute path of the file

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 7 of 16

58. FileReader is meant for reading streams of characters. For reading streams of raw bytes, a FileInputStream should be used. FileWriter is meant for writing streams of characters. For writing streams of raw bytes, you should use a FileOutputStream. 59. The BufferedReader class reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. It is advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders andInputStreamReaders. For example, BufferedReader in

= new BufferedReader(new FileReader("foo.in"));

will buffer the read operations from the specified file. 60. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example: BufferedWriter out = new BufferedWriter(new FileWriter(“foo.out”)); will buffer the write operations to the specified file. 61. The following method allows to create a FileWriter object, given a File object. public FileWriter(File file, boolean append) throws IOException If the second argument is true, then bytes will be appended at the end of the file. Otherwise, the contents of the file are overwritten. 62. A class is serializable if it implements the java.io.Serializable interface. All subtypes of a serializable class are themselves serializable. 63. For complete and explicit control of the serialization process, a class must implement the Externalizable interface. For Externalizable objects, only the identity of the object's class is automatically saved by the stream. The class is responsible for writing and reading its contents, and it must coordinate with its superclasses to do so. The Externalizable interface extends the Serializable interface. 64. The Serializable interface has neither fields nor methods. The Externalizable interface defines the following methods. void readExternal(ObjectInput in) The object implements the readExternal() method to restore its contents by calling the methods of DataInput for primitive types and readObject() method of ObjectInput for objects, strings, and arrays. void writeExternal(ObjectOutput out) The object implements the writeExternal() method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject() method of ObjectOutput for objects, strings, and arrays. 65. The java.util.Scanner class represents a simple text scanner for parsing primitive types and strings using regular expressions. A scanner splits its input into tokens using a delimiter pattern. The methods used to change the delimiter for tokenizing the input are

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 8 of 16

Scanner useDelimiter(String) Scanner useDelimiter(Pattern) 66. The Formatter class provides a constructor which creates a new Formatter instance with the specified destination and locale. Formatter(Appendable a, Locale l) The Appendable interface must be implemented by any class whose instances are intended to receive formatted output from a Formatter. This interface is implemented by StringBuilder but not by the String class. 67. The format() method of the Formatter class writes a formatted string to this object's destination using the specified format string and arguments. Formatter format(String format, Object... args) The format() method of the String class returns a formatted string using the specified format string and arguments. static String format(String format, Object... args) 68. A Locale object represents a specific geographical, political, or cultural region. The available constructors are • • •

Locale(String language) Locale(String language, String country) Locale(String language, String country, String variant)

69. The Locale class provides a number of convenient constants to create Locale objects for commonly used locales. For example, the following creates a Locale object for the United States: Locale locale = Locale.US; 70. DateFormat class has methods to format and parse dates for any locale. DateFormat d = DateFormat.getDateInstance(); String str = d.format(date); // Formats a date for the current Locale. DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.US); String str = d.format(date); // Formats a date for the specified Locale Date myDate = df.parse("07/10/96 4:5 PM, PDT"); // Parses a date/time string to a Date 71. The NumberFormat class helps you to format and parse numbers for any locale. Use getInstance() or getNumberInstance() to get the normal number format. Use getIntegerInstance() to get an integer number format. Use getCurrencyInstance() to get the currency number format. Use getPercentInstance() to get a format for displaying percentages. 72. To format a number for the current Locale, use one of the factory class methods: myString = NumberFormat.getInstance().format(myNumber);

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 9 of 16

To format a number for a different Locale, specify it in the call to getInstance(): NumberFormat nf = NumberFormat.getInstance(Locale.US); 73. The Pattern class is a compiled representation of a regular expression. The compile() method of the Pattern class compiles the given regular expression into a pattern and then the matcher method creates a matcher that will match the given input against this pattern. 74. The split() method of the String class returns an array containing the tokens into which the invoking string has been split. It takes the regular expression, which is to be used as the delimiter, as the argument. The two overloaded versions of the method are • •

public String[] split(String regex, int limit) public String[] split(String regex)

75. The System.out.printf() method sends formatted numerical output to the console. It uses a java.util.Formatter object internally. System.out.printf(" %s

", x);

The simplest of the overloaded versions of the method goes as follows printf (String format, Object... args)

Objective: Concurrency

76. A thread in Java is represented by an object of the Thread class. 77. There are two ways to define threads in Java: • By extending the Thread class, or • By implementing the Runnable interface 78. To implement Runnable you need to define only one method, public void run() This method will be executed by the new thread after it has been started by the thread scheduler. 79. When the start() method is called on a Thread object, the thread moves from the NEW state to the RUNNABLE state. When the Thread scheduler gives the thread a chance to execute, the run() method is invoked. 80. Many threads can be in the RUNNABLE state, but only one thread can be actually running at a given time on a mono-processor machine. The order in which threads were started might be different from the order in which they actually run. 81. It is legal to invoke the run() method directly, but it does not start a new thread of execution. Instead, the current thread executes it like a normal method. 82. The start() method should be invoked only once on a Thread object, otherwise it will throw an IllegalStateException.

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 10 of 16

83. A thread is considered dead, when its run method returns. A dead thread cannot be started again. 84. The sleep() method puts the milliseconds.

currently executing thread to sleep for a given time in

public static void sleep(long millis) 85. The yield() method causes the current thread to move from the RUNNING state to the RUNNABLE state, so that another thread can have a chance to run. There is no guarantee that the next chosen thread chosen will be a different thread. public static void yield() 86. The isAlive() method returns true if the thread upon which it is called has been started, but is not yet dead. public final boolean isAlive() 85. By default, every thread gets the priority of the thread of execution that creates it. The setPriority() method is used to set the priority of a Thread, which varies from 1 to 10. 86. When a thread calls join() on another thread, the currently running thread will wait until the thread it joins with has finished executing.  

void join() - Waits for this thread to die void join(long millis)- Waits at most millis milliseconds for this thread to die

87. Every object in Java has one and only one lock which ensures synchronized access to the resource. 88. If a thread has obtained the lock, no other thread can enter the synchronized code till the lock is released. When the thread holding the lock exits the synchronized code, the lock is released. 89. If a thread tries to get the lock of an object and finds that the lock is already taken, the thread goes into a blocked state till the lock is released. 90. There are two ways to mark code as synchronized (thread-safe): a.) Synchronize an entire method by using the synchronized modifier in the method declaration. b.) Synchronize a block, using the synchronized keyword with an expression that evaluates to an object reference. The block must be enclosed in curly braces. For example, void funct(){ synchronized(obj) { // code to be thread protected } } 85. Static methods can be synchronized, using the lock from the java.lang.Class object representing that class. 86. If a thread sleeps while executing synchronized code, the lock is not released. 87. Methods or code blocks can be synchronized, but not variables.

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 11 of 16

88. A class can have both synchronized and non synchronized methods. 89. Only one thread can access the synchronized code of an object at a time, but any number of threads can access the same object’s non-synchronized code. 90. The wait(), notify(), and notifyAll() methods are defined in the java.lang.Object class. 91. A thread gives up the lock on a synchronized object and moves from the RUNNING state to the WAITING state when the wait() method is invoked. 92. The notify() method is used to signal one of the threads waiting on the object to return to the RUNNABLE state. The notifyAll() method sends the signal to all the threads waiting on the object to return to the RUNNABLE state. 93. A thread can invoke wait() or notify() on a particular object, only if it currently holds the lock on that object. So these methods can only be invoked from synchronized code

Objective: OO Concepts

90. Cohesion is the degree to which all the elements of a component are directed towards and essential for performing the same task. A well-designed class must have high cohesion. 91. High cohesion makes it easier to: • understand what a class or method does. • use descriptive names. • reuse classes or methods. 92. Coupling indicates the degree of dependence among components. Tight coupling tends to indicate poor design of classes, since it makes modifying parts of the system difficult, for example, modifying a component affects all the components to which the component is connected. 93. Loose coupling has the following advantages. • •

Helps understand one class without studying other related ones Minimizes changes in other classes, when one class is changed

94. The relationship of a subclass with its superclass is termed "IS-A". It is implemented using the ‘extends’ keyword. The relationship of a subinterface with its superinterface is termed "IS-A". It is also implemented using the ‘extends’ keyword. 95. Two objects, X and Y are in a HAS-A relationship if Y is a property or a component of X. If X HAS-A Y, than Y will be an member variable in class X. 96. Hiding the implementation details of a class behind a public programming interface is called encapsulation. A class is considered to be well encapsulated if the instance variables are private (or protected if need be) and access is allowed only through public methods. 97. All constructors implicitly call the no argument constructor of the immediate superclass using super(); if no explicit call is made to the superclass constructor. 98. A superclass / interface type reference variable can refer to an object of the subclass, but the opposite is not true. 99. Overloading methods. • Must have the same name • Must have different argument lists

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

• • •

Page 12 of 16

May or may not have different return types May use different access modifiers May throw different exceptions

100. A class can overload both the methods declared in it as well as the methods of its superclass. 101. Constructors can be overloaded, but not overridden, since they are not inherited by subclasses. 102. The overriding method • must have the same name, arguments, and return type as the overridden method, except in the case of covariant return types. • cannot be less public than the overridden method. • must not throw new or broader checked exceptions. 103. Polymorphism comes into action during overriding, the method invoked depends on the actual object type at runtime. 104. To invoke the superclass version of an overridden method from the subclass, use super.method(). 105. Static methods can be hidden by subclasses, but not overridden. 106. Final methods cannot be overridden. Private methods cannot be overridden since they are not inherited.

Objective: Collections / Generics

107. A collection is a data structure in which objects are stored. They can grow and shrink dynamically. 108. Collection is an interface whereas Collections is a helper class which has utility methods for sorting, collections searching, etc. 109. Set and List extend the java.util.Collection interface, but Map does not implement the Collection interface, though it is a part of Java's collection framework. 110. A List is a collection, which can contain duplicate elements and the elements are ordered. 111. The classes implementing List interface are: • ArrayList – For fast iteration and fast random access • Vector - Similar but slower than ArrayListsince all methods are synchronized • LinkedList - Good for adding elements at the beginning/end, used for implementing stacks and queues 112. A Set is a collection, which cannot contain any duplicate elements and has no explicit order to its elements. 113. The classes implementing Set interface are: • • •

HashSet - Ensures no duplicates, not ordered TreeSet - No duplicates, returns elements in the sorted order LinkedHashSet- No duplicates, insertion order is maintained

114. A Map is an object that maps keys to values. It cannot contain duplicate keys; each key can map to at most one value. 115. Classes implementing Map interface are: • HashMap - Faster updates, allows one null key and many null values • Hashtable - Similar to HashMap, but slower and synchronized, does not allow null keys and values • LinkedHashMap - Faster iterations, iterates by insertion or last accessed order.

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 13 of 16

Allows 1 null key and many null values • TreeMap - A sorted map in natural order of keys 116. The hashcode value of an object gives a number which can be used to effectively index objects in a collection. 117. If two objects are equal as determined by the equals() method, their hashcodes should be the same. So whenever equals() is overridden, hashCode()should also be implemented. The reverse is not required, i.e., two objects that are not equal can have the same hashcode. For Example: public int hashCode() { return (int)(value^5); } 118. It is incorrect to involve a random number or transient variable directly when computing the hashcode because it would not return the same hashcode for multiple invocations of the method. 119. When comparing reference variables using the “==” operator, it returns true if the reference variables are referring to the same object. 120. The Object class provides the equals(Object obj) method, which can be overridden to return “true” if two objects are considered meaningfully equal. 121. The default implementation of the equals() method in Object class returns true only if an object is compared to itself i.e., it behaves like “==” 122. The equals() method is overridden by the String and wrapper classes. However, the StringBuffer class does not override this method. 123. In the Arrays class, there are sort methods for all primitive type and object arrays, of the form Arrays.sort(primitivetype[]) • Arrays.sort(Object[]) • You can perform binary search on sorted arrays of primitive type or Object type using the binarySearch() method. Arrays.binarySearch(type[],type key) 124. It is possible to restrict a collection type to contain objects of a particular data type only. Such types are called generic types. For example, the declaration below indicates that List is a generic interface that takes a type parameter, which is a Double. The compiler guarantees that only Double objects are added to this List. List myList=new LinkedList(); 125. The TreeSet class guarantees that the set will be sorted according to the natural order of the elements (if the elements implement the Comparable interface), or by the comparator provided at the set creation time. 126. The Comparable interface defines the int compareTo(Object o) method which compares this object with the specified object for order. It returns a negative integer, zero, or a positive integer depending on whether this object is less than, equal to, or greater than the specified object. 127. The Comparator interface defines the int compare(Object o1, Object o2) method which compares two objects. They can be passed to a sort method (such as Collections.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as TreeSet or TreeMap). 128. The Queue interface extends the Collection interface and adds the following methods:

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

• • • • •

Page 14 of 16

E element() boolean offer(E o) E peek() E poll() E remove()

The offer method is used to add elements to the Queue. It returns false if the element cannot be added. The remove() and poll() methods are for removing the first element of the Queue. The remove method throws NoSuchElementException when it is called on an empty collection, the poll method just returns null. The peek() and element() methods can return the element at the head of the queue, without removing it. The peek() method returns null if the queue is empty, while the element() method throws NoSuchElementException in that case. 129. All instances of a generic class have the same runtime class, regardless of their actual type parameters. So it is not meaningful to use the instanceof operator to check if an object is the instance of a particular invocation of a generic type. 130. When a generic type is used without a type parameter, it is called a raw type. Since you can insert all type of objects into these raw types, it is not possible to check their correctness. So assigning generic types to raw types generates an unchecked warning. 131. In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G is a subtype of G. For example, the second line of code here will not compile. List ls = new ArrayList(); //1 List lo = ls; //2 132. The supertype of all kinds of collections is written as Collection (pronounced as “collection of unknown”) , that is, a collection whose element type matches anything. It is called a wildcard type. For example, void printCollection(Collection c) { for (Object e : c) { System.out.println(e); } } And now, we can call it with any type of collection. Note that the following code can take only Collection void printCollection(Collection c) { for (Object e : c) { System.out.println(e); } } 133. We cannot add arbitrary objects to a collection of wild card type. Collection c = new ArrayList(); c.add(new Object()); // compile time error Since we don’t know what type that is, we cannot pass in anything. The sole exception is null, which is a member of

file://E:\Program%20Files\Whizlabs%20Suite\SCJP%205.0\Database\htmlfile.html

4/19/2006

QuickRevisionNotes

Page 15 of 16

every type. 134. We can declare variables which can accept collections of any subclass of a particular class, say X, by using the bounded wild card type
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF