SCJP Chapter 3

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Based on the rules we just discussed, can you determine the output of the following program? class Init { Init(int x) { System.out.println("1-arg const"); } Init() { System.out.println("no-arg const"); } static { System.out.println("1st static init"); } { System.out.println("1st instance init"); } { System.out.println("2nd instance init"); } static { System.out.println("2nd static init"); } public static void main(String [] args) { new Init(); new Init(7); } }

1st static init 2nd static init 1st instance init 2nd instance init no-arg const 1st instance init 2nd instance init 1-arg const

❑Arrays are indexed beginning with ____ .

Arrays are indexed beginning with zero.

❑Arrays have a ____ variable whose value is the number of array elements.

Arrays have a length variable whose value is the number of array elements. array.length

As of Java 5, ____ allows you to convert primitives to wrappers or to convert wrappers to primitives ____ .

As of Java 5, boxing allows you to convert primitives to wrappers or to convert wrappers to primitives automatically.

What is the format for constructing an array?

Constructing an array means creating the array object on the heap (where all objects live)—i.e., doing a new on the array type. To create an array object, Java must know how much space to allocate on the heap, so you must specify the size of the array at creation time. The size of the array is the number of elements the array will hold. int[] testScores; // Declares the array of ints testScores = new int[4]; // constructs an array and assigns it // to the testScores variable

What is the format for array declarations?

Declaring an array of object references: Thread[] threads; // Recommended Thread threads[]; // Legal but less readable

How do double literals end?

Double literals end in a digit or D or d.

How do float literals end?

Float literals end in For f.

Instance initialization blocks run ____ ____ a new instance is created. They run ____ all super-constructors and ____ the constructor's code has run.

Instance initialization blocks run every time a new instance is created. They run after all super-constructors and before the constructor's code has run.

Integer literals can be ____ , ____ (e.g. 013), or ____ (e.g. 0x3d).

Integer literals can be decimal, octal (e.g. 013), or hexadecimal (e.g. 0x3d).

Is NumberFormatException a run-time exception or a compile-time exception

It is a run-time exception, meaning it is thrown by the JVM. 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.

Literal integers are implicitly ____ .

Literal integers are implicitly ints.

What is the form or literals for chars?

Literals for chars are a single character inside single quotes: 'd'.

How do literals for Longs end?

Literals for longs end in L or l.

Local variables ( ____ variables) live on the ____ .

Local variables (method variables) live on the stack.

Do they take arguments?

No

Do they return anything/ do they have a return statement?

No.

Do initialization blocks have names?

Nope.

____ and their ____ variables live on the heap.

Objects and their instance variables live on the heap.

Can you remember these rules? ■What order do init blocks run in? ■Static init blocks run ____ ■Instance init blocks run ____ ____ a class instance is created. ■Instance init blocks run ____ the constructor's call to super().

Remember these 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().

Scope refers to the ____ of a variable.

Scope refers to the lifetime of a variable.

____ occurs when two variables with different scopes share the same name. This leads to hard-to-find bugs, and hard-to-answer exam questions :)

Shadowing occurs when two variables with different scopes share the same name. This leads to hard-to-find bugs, and hard-to-answer exam questions.

The boolean literals are ____ and ____ .

The boolean literals are true and false.

Will the compiler choose boxing or widening? class AddBoxing { static void go(Integer x) { System.out.println("Integer"); } static void go(long x) { System.out.println("long"); } public static void main(String [] args) { int i = 5; go(i); // which go() will be invoked? } }

The compiler will ALWAYS choose widening over boxing.

Using = = with wrappers created through boxing is tricky; those with the same small values (typically lower than 127), will ____ be = =, larger values will ____ be = =.

Using == with wrappers created through boxing is tricky; those with the same small values (typically lower than 127), will definitely be ==, larger values will not be ==.

What is an initialization block?

We've talked about two places in a class where you can put code that performs operations: methods and constructors. Initialization blocks are the third place in a Java program where operations can be performed. Initialization blocks run when the class is first loaded (a static initialization block) or when an instance is created (an instance initialization block). Let's look at an example: class SmallInit { static int x; int y; static { x = 7 ; } // static init block { y = 8; } // instance init block } They don't have names, they can't take arguments, and they don't return anything. A static initialization block runs once, when the class is first loaded. An instanceinitialization block runs once every time a new instance is created

When an array of objects is instantiated, objects within the array are ____ instantiated ____

When an array of objects is instantiated, objects within the array are not instantiated automatically Declaring an array of object references: Thread[] threads; // Recommended Thread threads[]; // Legal but less readable

When an array of ____ is instantiated, elements get default values.

When an array of primitives is instantiated, elements get default values.

When creating a new object, e.g., Button b = new Button();, three things happen: ❑Make a reference variable named ____ , of type ____ ❑Create a new Button ____ ❑Assign the Button object to the reference variable b

When creating a new object, e.g., Button b = new Button();, three things happen: ❑Make a reference variable named b, of type Button ❑Create a new Button object ❑Assign the Button object to the reference variable b

Which one wins? boxing vs widening var-arg vs widening boxing vs var-arg

Widening beats boxing ■Widening beats var-arg boxing beats var-arg A var-args method is more like a catch-all method, in terms of what invocations it can handle, and as we'll see in Chapter 5, it makes most sense for catch-all capabilities to be used as a last resort

When using Wrapper methods, when is the NumberFormatException thrown?

Wrapper classes that take a String throw NumberFormatException if the String provided cannot be parsed into the appropriate primitive. For example "two" can't be parsed into 2

❑Wrapper constructors can take a ____ or a primitive, except for ____ , which can only take a ____ .

Wrapper constructors can take a String or a primitive, except for Character, which can only take a char. Integer i1 = new Integer(42); Integer i2 = new Integer("42"); The Character class provides only one constructor, which takes a char as an argument—for example, Character c1 = new Character('c');

Wrappers have two main functions: ❑ To wrap primitives so that they can be handled like ____ ❑ To provide ____ methods for primitives (usually conversions)

Wrappers have two main functions: ❑ To wrap primitives so that they can be handled like objects ❑ To provide utility methods for primitives (usually conversions)

Do they perform functions?

Yes. Apart from methods and constructors, they are the only location in which you can perform functions.

You ____ widen and then box.

You CANNOT widen and then box. (An int can't become a Long.)

What is the format for declaring and constructing an array in one line?

You can also declare and construct an array in one statement as follows: int[] testScores = new int[4];

You ____ box and then widen.

You can box and then widen. (An int can become an Object, via an Integer.)

You ____ combine var-args with either widening or boxing.

You can combine var-args with either widening or boxing.

❑You ____ include the size of an array when you construct it (using new) unless you are creating an ____ array.

You must include the size of an array when you construct it (using new) unless you are creating an anonymous array.

❑You'll get a ____Exception if you try to use an array element in an object array, if that element does not refer to a real ____ .

You'll get a NullPointerException if you try to use an array element in an object array, if that element does not refer to a real object.

If you make a mistake in your static init block, what exception do you get? And is it a runtime or compile time exception

if you make a mistake in your static init block, the JVM (at runtime) can throw an ExceptionInInitializationError. class InitError { static int [] x = new int[4]; static { x[4] = 5; } // bad array index! public static void main(String [] args) { } } which produces something like: Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.ArrayIndexOutOfBoundsException: 4 at InitError.<clinit>(InitError.java:3)

When a class has overloaded methods, one of the compiler's jobs is to determine which method to use whenever it finds an invocation for the overloaded method. Let's look at an example that doesn't use any new Java 5 features: class EasyOver { static void go(int x) { System.out.print("int "); } static void go(long x) { System.out.print("long "); } static void go(double x) { System.out.print("double "); } public static void main(String [] args) { byte b = 5; short s = 5; long l = 5; float f = 5.0f; go(b); go(s); go(l); go(f); } } What is the product?

int int long double

class AddVarargs { static void go(int x, int y) { System.out.println("int,int");} static void go(byte... x) { System.out.println("byte... "); } public static void main(String[] args) { byte b = 5; go(b,b); // which go() will be invoked? } } What is the output?

int, int

You can use valueOf and ParseXXX with radix expressions long L2 = Long.parseLong("101010", 2); // binary String to a // primitive System.out.println("L2 = " + L2); // result is: L2 = 42 Long L3 = Long.valueOf("101010", 2); // binary String to // Long object System.out.println("L3 value = " + L3); // result is: // L3 value = 42

long L2 = Long.parseLong("101010", 2); // binary String to a // primitive System.out.println("L2 = " + L2); // result is: L2 = 42 Long L3 = Long.valueOf("101010", 2); // binary String to // Long object System.out.println("L3 value = " + L3); // result is: // L3 value = 42

❑ Wrapper class methods: ____ () Takes a String, returns a wrapped object, throws ____

valueOf()Takes a String, returns a wrapped object, throws NFE (NumberFormatException) Example: Double d5 = Double.valueOf("3.14"); // create a Double obj System.out.println(d5 instanceof Double); // result is "true"

❑ Wrapper methods: ____ () Takes no arguments, returns a primitive

xxxValue()Takes no arguments, returns a primitive When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue()methods. Integer i2 = new Integer(42); // make a new wrapper object byte b = i2.byteValue(); // convert i2's value to a byte primitive short s = i2.shortValue(); // another of Integer's xxxValue methods double d = i2.doubleValue(); // yet another of Integer's xxxValue //methods Float f2 = new Float(3.14f); // make a new wrapper object short s = f2.shortValue(); // convert f2's value to a short // primitive System.out.println(s); // result is 3 (truncated, not // rounded)

Block variables (e.g., in a ____ or an ____ ) live until the block completes.

❑ Block variables (e.g., in a foror an if) live until the block completes.

❑ Wrapper methods: ____ () Takes a String, returns a primitive, throws ____

❑ parseXxx()Takes a String, returns a primitive, throws NFE (NumberFormatException) Example: double d4 = Double.parseDouble("3.14"); // convert a String // to a primitive System.out.println("d4 = " + d4); // result is d4 = 3.14

A primitive argument is an ____ copy of the original primitive.

❑A primitive argument is an unattached copy of the original primitive.

Is a reference argument a copy of an original?

❑A reference argument is another copy of a reference to the original object.

A reference variable holds the ____ that are used to refer to an object.

❑A reference variable holds the bits that are used to refer to an object.

An object is eligible when no ____ ____ can reach it.

❑An object is eligible when no live thread can reach it.

Arrays can hold primitives or objects, but the array itself is always a/ an ____ .

❑Arrays can hold primitives or objects, but the array itself is always an object.

Class ____ has a finalize()method.

❑Class Object has a finalize()method.

____ ____ (e.g. +=), perform an automatic cast.

❑Compound assignments (e.g. +=), perform an automatic cast. The following will compile, byte b = 3; b += 7; // No problem - adds 7 to b (result is 10) and is equivalent to byte b = 3; b = (byte) (b + 7); // Won't compile without the // cast, since b + 7 results in an int

Floating-point numbers are implicitly ____ ( ____ bits).

❑Floating-point numbers are implicitly doubles (64 bits).

If you ____ an array to a previously declared array ____ , the array you're assigning must be the ____ dimension as the reference you're assigning it to.

❑If you assign an array to a previously declared array reference, the array you're assigning must be the same dimension as the reference you're assigning it to.

In Java, garbage collection (GC) provides ____ ____ management.

❑In Java, garbage collection (GC) provides automated memory management.

Instance variables are ____ initialized with a default value.

❑Instance variables are always initialized with a default value.

Instance variables live as long as their ____ lives.

❑Instance variables live as long as their object lives.

Integer expressions always result in an ____ - ____ result, never ____ .

❑Integer expressions always result in an int-sized result, never smaller.

Islands of objects ____ be GCed

❑Islands of objects can be GCed, even though they refer to each other.

❑It is ____ legal to include the size of an array in the declaration.

❑It is never legal to include the size of an array in the declaration.

Java applications ____ run out of memory.

❑Java applications can run out of memory.

Local variables live as long as their ____ is on the ____ ; however, if their method invokes another method, they are temporarily ____ .

❑Local variables live as long as their method is on the stack; however, if their method invokes another method, they are temporarily unavailable.

Local/ ____ / ____ variables are ____ given a default value.

❑Local/automatic/method variables are never given a default value. If you attempt to use one before initializing it, you'll get a COMPILER ERROR.

Method arguments are ____ copies. Method arguments are ____ actual objects.

❑Method arguments are always copies. ❑Method arguments are never actual objects (they can be references to objects).

Do methods take primitives or object references as arguments?

❑Methods can take primitives and/or object references as arguments.

❑Multidimensional arrays are just arrays of ____ .

❑Multidimensional arrays are just arrays of arrays.

Narrowing a primitive ____ the high orderbits.

❑Narrowing a primitive truncates the high orderbits.

Objects must be considered ____ before they can be garbage collected.

❑Objects must be considered eligible before they can be garbage collected.

Only the ____ decides when to run the GC, ____ can only suggest it.

❑Only the JVM decides when to run the GC, you can only suggest it.

Primitive widening uses the " ____ " method argument possible.

❑Primitive widening uses the "smallest" method argument possible.

Radix refers to ____ (typically) other than 10; octal is radix = 8, hex = 16.

❑Radix refers to bases (typically) other than 10; octal is radix = 8, hex = 16.

Reference variables can refer to ____ of the declared type but not to ____ .

❑Reference variables can refer to subclasses of the declared type but not to superclasses.

Request garbage collection with ____ ();(only ____ the SCJP 6).

❑Request garbage collection with System.gc();(only before the SCJP 6).

Static initialization blocks run ____ , when the ____ is ____ loaded.

❑Static initialization blocks run once, when the class is first loaded.

Static variables live basically as long as their ____ lives.

❑Static variables live basically as long as their class lives.

❑The dimensions in a multidimensional array ____ have different lengths.

❑The dimensions in a multidimensional array can have different lengths.

The finalize()method is guaranteed to run once and only once ____ the garbage collector deletes an object.

❑The finalize()method is guaranteed to run once and only once before the garbage collector deletes an object.

The garbage collector makes ____ guarantees, finalize() ____ ____ run.

❑The garbage collector makes no guarantees, finalize()may never run.

❑The last index you can access is always ____ ____ than the length of the array.

❑The last index you can access is always one less than the length of the array.

The purpose of GC is to ____ objects that can't be ____ .

❑The purpose of GC is to delete objects that can't be reached.

❑The ____ classes correlate to the ____ types.

❑The wrapper classes correlate to the primitive types.

To reach an object, you must have a ____ , ____ reference to that object.

❑To reach an object, you must have a live, reachable reference to that object.

Used individually, boxing and var-args are ____ compatible with overloading.

❑Used individually, boxing and var-args are definitely compatible with overloading.

❑When you declare an array, where must the bracket be in relation to the name of the array?

❑When you declare an array, the brackets can be left or right of the name.

You ____ widen from one wrapper type to another.

❑You CANNOT widen from one wrapper type to another. (IS-A fails.)

You ____ assign an array of one type to a previously declared array reference of one of its supertypes

❑You can assign an array of one type to a previously declared array reference of one of its supertypes. For example, a Honda array can be assigned to an array declared as type Car (assuming Honda extends Car).

You ____ uneligibilize an object for GC from within finalize().

❑You can uneligibilize an object for GC from within finalize().

You ____ know the GC algorithm for sure.

❑You can't know the GC algorithm for sure.

When do init blocks run?

After all super constructors but before the object's own constructor.

When an array of objects is instantiated, what value do all of the references get?

All the references get the default value of null.

❑An ____ Exception occurs if you use a bad index value.

An ArrayIndexOutOfBoundsException occurs if you use a bad index value.

An array of ____ can hold any object that passes the IS-A (or instanceof) test for the declared ____ of the array.

An array of objects can hold any object that passes the IS-A (or instanceof) test for the declared type of the array. For example, if Horse extends Animal, then a Horse object can go into an Animal array.

An array of ____ can accept any value that can be promoted ____ to the array's declared type;. e.g., a byte variable can go in an intarray.

An array of primitives can accept any value that can be promoted implicitly to the array's declared type;. e.g., a byte variable can go in an int array.

❑Elements in an array of ____ are not automatically created, although ____ array elements are given default values.

Elements in an array of objects are not automatically created, although primitive array elements are given default values

If multiple init blocks exist in a class, they follow the rules stated above. But what order do they run in?

If multiple init blocks exist in a class, they follow the rules stated above, AND they run in the order in which they appear in the source file.

Wrapper objects are mutable or immutable?

Immutable. Once they've been given a value, the value cannot be changed.

There are ____ basic scopes:

There are four basic scopes:

_______ The Integer and Long wrapper classes let you convert numbers in base 10 to other bases

These conversion methods, toXxxString(), take an intor long, and return a String representation of the converted number, for example, String s3 = Integer.toHexString(254); // convert 254 to hex System.out.println("254 is " + s3); // result: "254 is fe" String s4 = Long.toOctalString(254); // convert 254 to octal System.out.print("254(oct) ="+ s4); // result: "254(oct) =376"

What is the difference between a non-static initialization block and a constructor?

They are the same. The reason that initializer blocks is allowed is to allow the existence of anonymous classes. They have no name, therefore they have no matching constructor. So they MUST do all the same stuff in an initializer block. "Instance initializers are a useful alternative to instance variable initializers whenever: (1) initializer code must catch exceptions, or (2) perform fancy calculations that can't be expressed with an instance variable initializer. You could, of course, always write such code in constructors. But in a class that had multiple constructors, you would have to repeat the code in each constructor. With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. Instance initializers are also useful in anonymous inner classes, which can't declare any constructors at all."


संबंधित स्टडी सेट्स

ENDOCRINE SYSTEM - Parathyroid Glands

View Set

weather 今天 天(tiān)气(qì)怎(zěn)么(me)样(yàng)

View Set

Capstone Chap.4 The Internal Assessment, Capstone Chap.5 Strategies in Action, Capstone Chap.6 Strategy Analysis and Choice

View Set