Try English version of Quizful



Раздаем бесплатные Q! подробности в группе Quizful.Alpha-test
Партнеры
Рекрутерам: Прескрининг кандидатов about
Топ контрибуторов
loading
loading
Знаете ли Вы, что

После прохождения теста можно комментировать вопросы теста, а Ваши комментарии увидят модераторы теста и пользователи, которым когда-либо эти вопросы попадались.

Лента обновлений
ссылка 15:12:18
Комментарий от C00Lman:
В векторе же константный поиск. Почему он в правильных о...
ссылка 13:19:05
Комментарий от MikeVazovskiy:
Разве в C# есть деструкторы? По-моему в C# финализ...
ссылка 08:27:14
Комментарий от Russik:
"top будет иметь приоритет." т.е ответ вверх на 20px?
ссылка 06:45:53
Комментарий от Saddius:
отвратительная статья.
ссылка 02:17:01
Комментарий от ssf:
Спасибо большое за объяснение!
Статистика

Тестов: 152, вопросов: 8542. Пройдено: 369590 / 1788783.

Подготовка к SCJP 6. Выдержки

head tail Статья
категория
SCJP
дата17.03.2010
авторuniservise
голосов46

1         DECLARATION & ACCESS CONTROL

1.1       Ranges of Numeric Primitives

Table #1.1

Type

Bits

Bytes

Min. Range -2(bits-1) 

Max. Range 2(bits-1)-1 

byte

8

1

-27

27-1

short

16

2

-215

215-1

int

32

4

-231

231-1

float

32

4

n/a

n/a

long

64

8

-263

263-1

double

64

8

n/a

n/a

1.2       Comparison of modifiers on variables vs. methods

Table #1.2

Local Variables

Non-local Variables

Methods

final

final public protected private static transient volatile

final public protected private static   abstract synchronized strictfp native

1.3       Enumerations

  • An enum can be declared outside or inside a class but not in a method
  • An enum declared outside a class must not be marked staticfinalabstractprotected or private
  • An enum can implement any interface  
  • Enums can contain constructors, methods, variables and constant class bodies
  • Enum constructors can never be invoked directly in code
  • MyEnum.values() returns an array of MyEnum’s values    

2         OBJECT ORIENTATION

2.1       Overriding

  • Appear in subclasses
  • Have the same name as a superclass method
  • Have the same parameter list as a superclass method
  • Have the same return type as a superclass method
  • The access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method:
  1. if the superclass method is public, the overriding method must be public
  2. if the superclass method is protected, the overriding method may be protected or public
  3. if the superclass method is package, the overriding method may be packageprotected, or public
  4. if the superclass methods is private, it is not inherited and overriding is not an issue
  • The throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including it's subclasses  

2.2       Overloading

  • Overloaded methods must change the argument list
  • Overloaded methods can change the return type
  • Overloaded methods can change the access modifier
  • Overloaded methods can declare new or broader checked exceptions  

2.3       Coupling

  • Coupling refers to the degree to which one class knows about or uses members of another class
  • Loose coupling is the desirable state of having classes that are well encapsulated, minimize references to each other, and limit the breadth of API usage
  • Tight coupling is the undesirable state of having classes that break the rules of loose coupling  

2.4       Cohesion

  • Cohesion refers to the degree in which a class has a single, well-defined role or responsibility
  • High cohesion is the desirable state of a class whose members support a single, well-focused role or responsibility
  • Low cohesion is the undesirable state of a class whose members support multiple, unfocused roles or responsibilities  

3         ASSIGMENTS

3.1       Initialization rules

  • Init blocks execute in the order they appear
  • Static init blocks run once, when the class is first loaded
  • Instance init blocks run every time a class instance is created
  • Instance init blocks run after the constructor’s call to super()

3.2       Boxing

  • Primitive widening uses the “smallest” method argument possible
  • Used individually, boxing and var-args are compatible with overloading  
  • You cannot widen and then box (int can't become Long)
  • You cannot widen from one wrapper type to another (IS-A fails)  
  • You can box and then widen (int can become an Object via Integer)
  • You can combine var-args with either widening or boxing    

4         OPERATORS

4.1       Bit Shift Operators

  Table #4.1

Operation

Meaning

Example

>>>

unsigned shift operator

1011 >>> 1 = 0101

>>, <<

signed shift operator

1011 >> 1 = 1101

5         FLOW CONTROLS

5.1        Exceptions


Picture 5.1  

5.2       Assertions

5.2.1       Identifier vs. Keyword

  • To use assert as identifier compile code with: v  javac -source 1.3 *.java  
  • To use assert as keyword compile code with: v  javac -source 1.4/1.5/5/1.6/6 *.java  

5.2.2       Assertion Rules

  • Don’t use assertions to validate arguments to a public method
  • Don’t use assertions to validate command-line arguments
  • Don’t use assert expressions that can cause side effects
  • Do use assertions to validate arguments to a private method
  • Do use assertions, even in public methods, to check for cases that you know are never, ever supposed to happen  

6         STRINGS, I/O, FORMATTING, PARSING

6.1        String

  • intern() - when the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is trueif and only if s.equals(t) is true.
  • substring(start, end) - returns a new string that is a substring of this string [start, end)

6.2       StringBuffer & StringBuilder

  • StringBuilder & StrignBuffer are identical in functionality but StringBuilder isn’t thread safe
  • substring(start, end) - returns a new string that is a substring of this string [start, end)
  • equals() – is not overridden; it doesn’t compare values

6.3       Console

Example #6.1

//Get a Console
java.io.Console c = System.console();
       
//Read string
String input1 = c.readLine();
String input2 = c.readLine("%s", "input string");
       
//Read password
char password[];
password = c.readPassword();
password = c.readPassword("%s", "input password");

6.4       Serialization

  • If a superclass implements Serializable I, then its subclasses do automatically  
  • If a superclass doesn’t implement Serializable, then when a subclass object is deserialized, the superclass constructor will be invoked, along with its super constructor(s)
  • If a class has object reference to another class that doesn’t implement Serializable the runtime exception will be thrown – java.io.NotSerializableException
  • Serialization is not for Statics  

6.5       Dates, Numbers, Currency

Table #6.1

Class

Key Instance Creation Options

util.Date

new Date();

new Date(long millisecondsSince01011970);  

util.Calendar

Calendar.getInstance();

Calendar.getInstance(Locale);  

util.Locale

Locale.getDefault();

new Locale(String lang)

new Locale(String lang, String country)  

text.DateFormat

DateFormat.getInstance();

DateFormat.getDateInstance();

DateFormat.getDateInstance(style);

DateFormat.getDateInstance(style, Locale);  

text.NumberFormat

NumberFormat.getInstance();

NumberFormat.getInstance(Locale);

NumberFormat.getNumberInstance();

NumberFormat.getNumberInstance(Locale);

NumberFormat.getCurrencyInstance();

NumberFormat.getCurrencyInstance(Locale);  

6.6        Regular expressions

Table #6.2

Metacharacter

Meaning

\d

A digit: [0-9]

\D

A non-digit: [^0-9]

\s

A whitespace character: [ \t\n\x0B\f\r]

\S

A non whitespace character: [^\s]

\w

A word character: [a-zA-Z_0-9]

\W

A non-word character: [^\w]

.

Any character

Table #6.2  

Greedy Quantifier

Meaning

*

Zero or more occurrences

?

Zero or one occurrences

+

One or more occurrences

{n}

Exactly n times

{n,}

At least n times

{n,m}

At least n but not more than m times

6.7        Tokenizing

Example #6.2


//Example#1

String str = "Monday,Tuesday,,Thursday,Friday";

//String split
String[] tokens = str.split(","); // [Monday,Tuesday,,Thursday,Friday]
 int count = tokens.length; // count = 5

//StringTokenizer
StringTokenizer tokenizer = new StringTokenizer(str, ",");
int count3 = tokenizer.countTokens(); //count = 4
while (tokenizer.hasMoreTokens()) {
System.out.print(tokenizer.nextToken() + " ");
} // [Monday,Tuesday,Thursday,Friday]

6.8       Formatting

Table #6.3

%[arg_index$] [flags] [width] [.precision] conversion char

arg_index

an integer followed directly by a $, this indicates which argument should be printed in this position

flags

“-” – left justify this argument “+” – include a sign (+ or -) with this argument “0” – pad this argument with zeroes “,” – use locale-specific grouping separators “(” – enclose negative numbers in parentheses

width

indicates the minimum number of character to print

precision

indicates the number of digits to print after the decimal point

conversion

b– boolean c – char d – integer f – floating point s – string

7         GENERICS & COLLECTIONS

7.1       Class hierarchy for collections


Picture #7.1

7.2       Collections details

Table #7.1

Class

Common Features

Individual Features

ArrayList

·   ordered by index position ·   unsorted ·   could have nullelements

·  fast iteration ·  fast random access

Vector

·  thread safe

LinkedList

·  fast insertion ·  fast deletion ·  peek() - retrieves, but does not remove, the head (first element) of this list ·  poll() - retrieves and removes the head (first element) of this list ·  offer() - adds the specified element as the tail (last element) of this list

PriorityQueue

·  ordered by natural order ·  could NOT have null element ·  first in first out  

HashSet

·  doesn’t allow duplicates  

·  unsorted ·  unordered ·  could have null elements  

LinkedHashSet

·  ordered ·  could have null elements  

TreeSet

·  sorted ·  cant have null elements ·  ceiling(e)returns the lowest element >= e, otherwise null. ·  floor(e) - Returns the least element in this set greater than or equal to the given element, or null if there is no such element.

Hashtable

·  unique identifiers

·   unsorted ·   unordered ·   doesn’t allow anything that’s have null

HashMap

·  unsorted ·  unordered ·  allows one null key ·  allows multiple null values  

LinkedHashMap

·  ordered ·  allows one null key ·  allows one null value  

TreeMap

·  ordered ·  sorted by natural order or custom ·  doesn’t allow null key ·  allows multiple null values ·  ceilingKey(key)returns the lowest key >= key, otherwise null

Table #7.2  

java.lang.Comparable

java.util.Comparator

public int compareTo(T o)

public int compare(T o1, T o2)

Returns:

  • negative – if this object < anotherObject
  • zero – if this object = anotherObject
  • positive – if this object > anotherObject

You must modify the class whose instances you want to sort.

You build a class separate from the class whose instances you want to sort.

Only one sort sequence can be created.

Many sort sequences can be created.

Implemented frequently in the API by: String, Wrapper classes, Date, Calendar…

Meant to be implemented to sort instances of third-party classes.

Table #7.3  

java.util.Arrays

Description

static List asList(T[])

Convert an array to a List

static int binarySearch(Object[], key) static int binarySearch(primitive[], key)

Search a sorted array for a given value, return an index or insertion point.

static int binarySearch (T[], key, Comparator)

Search a Comparator-sorted array for a value.

static boolean equals (Object[], Object[]) static boolean equals (primitive [],primitive [])

Compare two arrays to determine if their contents are equal.

static void sort (Object[]) static void sort (primitive[])

Sort the elements of an array by natural order.

static void sort (T[], Comparator)

Sort the elements of an array using a Comparator.

static String toString (Object[]) static String toString (primitive[])

Create a String containing the contents of an array.

Table #7.4  

java.util.Collections

Description

static int binarySearch (List, key) static int binarySearch (List, key, Comparator)

Search a “sorted” List for a given value, return an index or insertion point.

static void reverse(List)

Reverse the order of elements in a List.

static Comparator reverseOrder() static Comparator reverseOrder(Comparator)

Returns a Comparator that sorts the reverse of the collection’s current sort sequence.

static void sort(List) static void sort(List, Comparator)

Sort a List either by natural order or by a Comparator

8         INNER CLASSES

8.1       Class-Local Inner Class

8.1.1       Instantiating

To create an instance of an inner class, you must have an instance of the outer class to tie to the inner class.  

Example #8.1


//Example#1
MyOuter mo =
new MyOuter();
MyOuter.MyInner inner = mo.
new MyInner();

//Example#2
MyOuter.MyInner inner =
new MyOuter().new MyInner();

8.1.2       Member modifiers

Member modifies applied to inner classes:

  • final
  • abstract
  • public
  • private
  • protected
  • strictfp
  • static – for static nested class(not inner)  

8.2       Method-Local Inner Class

8.2.1       Instantiating

  • A method-local inner class can be instantiated only within the method where the inner class is defined
  • The inner class object can’t user the local variables of the method the inner class is in
  • A local class declared in a static method has access to only static members of the enclosing class  

Example #8.2

 //Example#1
public class MyOuter {
int b = 9;
static int s = 9;
 
[
static] public voidmyFunc() {
int a = 0;

class MyInner {

intadd(int value) {
value += a; // Illegal use of local variable 'a'
value += b; // Legal use of member variable 'b'
[value += s]; // Legal use of static variable 's'
return value;

}
}

MyInner mi =
new MyInner();
mi.add(5);
}
}

8.2.2       Member modifiers

  • The same rules apply to method-local inner classes as to local variable declarations, i.e. you can mark a method-local inner class as abstractor final, but never both at the same time  

8.3       Anonymous

8.3.1       Instantiating

  • Inner class declared without any class name at all
  • A semicolon is required after declaration of anonymous class
  • Polymorphism is in play when anonymous inner class are involved  

Example #8.3

 //Example#1
class MyOuter {
void myFunc() {
System.out.println("MyOuter");
}
}
 
class MainClass {
MyOuter mo =
new MyOuter() {
void newFunc() {
System.out.println("Anonymous
Class"
);
}
}; // WATCH OUT about semicolon!

public void doIt() {
mo.myFunc(); // Legal, MyOuter
has a 'myFunc()'
mo.newFunc(); // Not legal! MyOuter
doesn't have a 'newFunc()'

}
}

8.4       Static Nested Class

8.4.1       Instantiating

  • The static nested class can be accessed without having an instance of the outer class
  • The static nested class doesn't have access to the instance variables and nonstatic methods of the outer class   

Example #8.4


//Example#1
class Outer {
static abstract class Nested {
abstract void doIt();
}
}
 
class Runing {
static int a = 0;
int b = 0;

public static void main(String[]
args) {
Outer.Nested
on =
new Outer.Nested() {
@Override
void doIt() {
System.out.println(a); //OK
System.out.println(b); //Not legal!

}
};
}
}

9         THREADS

9.1       Thread states


Picture #9.1  

9.2       Class Thread

Table #9.1

java.lang.Thread

Constructors

public Thread()

public Thread(Runnable target)

public Thread(ThreadGroup group, Runnable target)

public Thread(String name)

public Thread(ThreadGroup group, String name)

public Thread(Runnable target, String name)

public Thread(ThreadGroup group, Runnable target, String name)

public Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Three thread-related methods

public final void wait()

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

public final native void notify()

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait() methods.

public final native void notifyAll()

Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait() methods.

Static methods

sleep(long millis) throws InterruptedException sleep(long millis, int nanos) throws InterruptedException

Causes the currently executing thread to sleep for the specified number of milliseconds. The thread does not lose ownership of any monitors.

yield()

Causes the currently executing thread object to temporarily pause and allow other threads to execute.

currentThread()

Returns a reference to the currently executing thread object.

Non static methods

interrupt()

Interrupts this thread. Throws: SecurityException §  if the current thread cannot modify this thread InterruptedException §  if this thread is blocked in an invocation of the wait() methods of the Object class, or of the join() or sleep(), methods of Thread class §  if this thread is blocked in an I/O operation §  if this thread is blocked in a Selector  §  if none of the previous conditions hold §  interrupting a thread that is not alive

join() throws InterruptedException join(long millis) throws InterruptedException join(long millis, int nanos) throws InterruptedException

Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever. Throws: InterruptedException §  if any thread has interrupted the current thread.

setContextClassLoader(ClassLoader cl)

Sets the context ClassLoader for this Thread. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader to code running in the thread when loading classes and resources. First, if there is a security manager, its checkPermission method is called with a RuntimePermission("setContextClassLoader") permission to see if it's ok to set the context ClassLoader. Throws: SecurityException §  if the current thread cannot set the context ClassLoader.

9.3       Synchronization and Locks

  Key points about locking and synchronization:

  • Only methods (or blocks) can be synchronized, not variables or classes
  • Each object has just one lock
  • Not all methods in a class need to be synchronized
  • Once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class
  • If a class has both synchronized and non-synchronized methods, multiple threads can still access the class’s non-synchronized methods
  • If a thread goes to sleep, it holds any locks it has – it doesn’t release them
  • A thread can acquire more than one lock
  • Static methods can be synchronized  

10    DEVELOPMENT

10.1  Java & Javac 

10.1.1  Execute a class:

java [-options] class [args...]

10.1.2  Execute a jar file:

java [-options] -jar jarfile [args...]

10.1.3  Basic search algorithm:

Java and Javac use the same basic search algorithm:

  • They both have the same list of places they search, to look for classes
  • They both search through this list of directories in the same order
  • As soon as they find the class they are looking for, they stop searching for that class. In the case that their search lists contain two or more files with the same name, the first file found will be the file that is used
  • The first place they look is in the directories that contain the class that come standard with J2SE
  • The second place they look is in the directories defined by classpaths
  • Classpaths should be thought of as "class search paths." They are lists of directories in which classes might be found
  • There are two places where classpaths can be declared:
  1. A classpath can be declared as an operating system environment variable. The classpath declared here is used by default, whenever java or javacare invoked
  2. v  A classpath can be declared as a command-line option for either java or javac. Classpaths declared as command-line options override the classpath declared as an environment variable, but they parsist only for the length of the invocation  

10.2  Jar archive

Table #10.1  

Command

Operation

jar cf jar-file input-file(s)

create a JAR file

jar tf jar-file

view the contents of a JAR file

jar xf jar-file

extract the contents of a JAR file

jar xf jar-file archived-file(s)

extract specific files from a JAR file

java -jar app.jar

run an application packaged as a JAR file (requires the Main-class manifest header)

< applet code = AppletClassName.class archive="JarFileName.jar" width=width height=height> </ applet>

invoke an applet packaged as a JAR file

10.3  Javadoc

Include tags in the following order:

* @author      (classes and interfaces only, required)
* @version
(classes and interfaces only, required)
* @param (methods and constructors only)
* @return
* @exception (@throws is a synonym added in Javadoc 1.2)
* @see
* @since
* @serial (or @serialField or @serialData)
* @deprecated

10.4  Annotation

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate. Annotations have a number of uses, among them:

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings
  • Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth
  • Runtime processing — Some annotations are available to be examined at runtime

There are three annotation types that are predefined by the language specification itself: @Deprecated, @Override, and @SuppressWarnings.

@Deprecated — annotation indicates that the marked element is deprecated and should no longer be used.

Example #10.1

  /**
*
@deprecated
* explanation of why it was deprecated
*/

@Deprecated
static void deprecatedMethod() { }


@Override— annotation informs the compiler that the element is meant to override an element declared in a superclass.


Example #10.2

 // mark method as a superclass method
// that has been overridden

@Override
int overriddenMethod() { }

@SuppressWarnings — annotation tells the compiler to suppress specific warnings that it would otherwise generate.  Every compiler warning belongs to a category. The Java Language Specification lists two categories: "deprecation" and "unchecked." To suppress more than one category of warnings, use the following syntax:

@SuppressWarnings({"unchecked", "deprecation"})


Example #10.3

 // use a deprecatedmethod and tell 
// compiler not to generate a warning

@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
objectOne.deprecatedMethod();
//deprecation
warning - suppressed

}

10.5  JVM

Table #10.2

Parameter

Meaning

–Xms<size>

initial Java heap size

–Xmx<size>

maximum Java heap size

–Xss<size>

java thread stack size

-----
Literature:

1. Sun Certified Programmer for Java 6 Study Guide - SCJP. Kathy Sierra, Bert
Bates.

2. http://java.sun.com/javase/6/docs/api/

Если Вам понравилась статья, проголосуйте за нее

Голосов: 46  loading...
yohan   bioflash   WhOwl   uniservise   hkvd   bulgari   c0nst   admin   bu_ma_ga   izen   xupypr   elankaa   helsinki   isemenov   ayscha   Skvorec   Stan   rufatina   makk   mandrake   Aldo   san   prostodenis   ieronim   sheff4ik   dimakkk   snoopy1   maxsbelt   Alexander_1   dynarsis   zjobru   A_N_R_I   fenrirwolf   ikruk   St1G   rize   royksopp   publo   thismk   kisce86   DarkTror   javamaster   movul   d_polupan   Irene   winner