SCJP MOCK QUESTIONS - 2

Question 2

Given:
10. public class Bar {
11.static void foo(int...x) {
12. // insert code here
13. }
14. }
Which two code fragments, inserted independently at line 12, will allow
the class to compile? (Choose two.)
A. foreach(x) System.out.println(z);
B. for(int z : x) System.out.println(z);
C. while( x.hasNext()) System.out.println( x.next());
D. for( int i=0; i< x.length; i++ ) System.out.println(x[i]);


Answer: BD

Answer:


type... x is used in function arguments where type can be any data type
for example:
int... x


which can take variable arguments
for example a function named var having declarations

var(int... x)

we can pass var(1); , var(1,1); , var(1,2,3);

so it can take 1 to any number of integers as arguments


int... x here x is just like an array and we can iterate over its elements using simple and enhanced for loop

other options are invalid

foreach is a method which is not defined
And hasnext() is used to iterate over collections(sets,lists,maps)

Hence the answer is B,D

SCJP MOCK QUESTIONS - 1

QUESTION

Given:
11. public interface Status {
12. /* insert code here */ int MY_TRUE_VALUE = 10;
13. }
Which three are valid on line 12? (Choose three.)
A. final
B. static
C. native
D. public
E. private
F. abstract
G. protected




ANS - ABD

In Interfaces we can define constants for example:

interface you
{ int i=10;
}

now in interfaces every variable is implicitly public static final
Therefore, though we define int i=10 but for the compiler it is
public static final int i=10;

Now you can even define like this way :

  1. final int i=10;
  2. static int i=10;
  3. public int i=10;
  4. public static int i=10;
  5. public final int i=10;
  6. static final int i=10;
  7. public static final int i=10;
All these declarations are valid but for the compiler all these declarartions lead to the same declaration - public static final int i=10;


Invalid Declarations:

native - can be only applied to methods
private - variables in interfaces are public
protected - variables in interfaces are public
abstract - As the variables are implicitly final and we know final and abstract cannot be together, therefore it is invalid.