Chapter 4: Methods and Encapsulation Flashcards

1
Q

Name the 4 access modifiers in order of least restrictiveness

A

public - proctected - default - private

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which of these optional modifiers will you need for the exam? static abstract syncronized native strictfp final

A

static final abstract

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the rules regarding use of varargs in a method?

A

1) a vararg parameter must come last in a methods parameter list 2) you can only have one vararg parameter per method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you call a method with a vararg parameter?

A

1) you can either pass in an array e.g method( new int[] {4,5}); 2) list the elements of the array and java will create it for you e.g method(4,5): 3) omit the values and java creates an array of size 0 e.g - method( )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you access a vararg parameter?

A

like you would an array e.g nums[0]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the default access modifier do?

A

only classes in the same package can access the member

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the protected access modifier do?

A

only classes in the same package and subclasses in any other package can access the member

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what does static mean?

A

something belonging to a class rather than to an instance of that class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Would this method compile public int get2X(int x){ if(x>0) return 2*x;

A

No, you cannot return a value conditionally as you must return the type you’ve declared in the signature

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the rules for a method with a void return type

A

1) it returns nothing 2) it can use the word return but with a semicolon at the end. eg return;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Are these valid method declarations? void add(int a, b) // 1 void add(int a, final int b) // 2 add (int a, int b) // 3

A

1) invalid parameter declaration for b. 2) valid, a parameter can be declared final as long as its value is not changed in the method. if this happens, compile error. 3) invalid - no return type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Does java allow methods to return a value of a different type than the one specified?

A

yes only on 3 occasions: 1) numeric promotion 2) Autoboxing/unboxing 3) With inheritance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Will this code compile? public int getVal(int x) { char ch = ‘a’; byte b = 0; if(x>0) return ch; else return b; }

A

yes, due to numeric promotion, a byte or char can be returned in the place of an int. if the return type is numeric, then the value that is returned is only allowed to be smaller than the type declared. e.g short, byte & char can be returned in an int method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Will these lines of code compile? public int getVal(){ return new Short( (short) 10); // 1 return new Long(10); //2 }

A

1) compiles as return type can be a wrapper object of a smaller type than the return type. This wrapper object will be unboxed into a primitive short. 2) will not compile, Long cannot be converted to int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Will these lines of code compile when run separately? public Integer getval(){ byte b = 10; return 10; // 1 return b; // 2

A

1) compiles as autoboxing is legal when it comes to return type. int 10 will be boxed into an Integer object 2) will not compile, byte cannot be converted to Integer. The constructor to turn a byte prim into a wrapper only takes a string or a byte. e.g byte b = new Byte((byte) 10);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Will this compile? String getValue(){ return new Object();

A

This will not compile as an Object is not a String. A String is an object though.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Are the following legal in java? class Foo{ private static void baz(){ } static public final void boz(){ }

A

yes // the static keyword has to come before the return type however the order of the modifies doesn’t matter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What types can’t be declared static in java?

A

Top level classes, interfaces, enums or local variables can’t be declared static.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are the different ways of accessing static members of a class from another class?

A

1) it is convention to access a static member by referencing the class name. 2) Java also allows static members to be accessed through an instance variable. 3) you can also access static members through an implicit reference to an instance e.g public class Order { public static double taxRate = 0.05; // static variable public Order(){}. // constructor public double checking() { // instance method return new Order().taxRate = 5.0; // implicit reference to constructor is accessing a static variable inside an instance variable }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Assume Birds is a class and fly() is a static method of the Birds class. what will this print? class TestClass{ public static void main(String[] args){ Birds eagles = null; eagles.fly(); } }

A

It will compile and run without any output. Accessing static members with a null instance reference doesn’t throw an exception as the compiler determines that fly() is a static member of class Birds and translates it to Birds.fly(); The compiler doesn’t care what eagles might point to at runtime

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Is access to static members determined at runtime or at compile time and how?

A

At compile time by the compiler by checking the declared type of variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do you access static members from the same class?

A

you can access static members from both instance and static members of the same class without referencing the class name.

23
Q

Explain what is happening on each line of code: class InstanceCounter{ static int count; InstanceCounter() { count++; // 1 } static void printCount() { System.out.println(count); // 2 } void reduceCount() { count–; //3 } }

A

1 ) directly accessing count from a constructor without referencing the class 2 directly accessing count from a static method without referencing the class 3) directly accessing count from an instance method without referencing the class

24
Q

How do you declare that you will be using a static member from another class in your class?

A

By using static imports with the keyword: import static

25
Q

Describe the two ways you can use static imports

A

You can import static members either using a wildcard (*) after the class name or you can directly import a specific static member. E.g - import static java.lang.Integer.* OR import static java.lang.Integer.MAX_VALUE;

26
Q

Will the following lines compile? class Book{ int name; static void printName1(){ System.out.println(this.name); // 1 System.out.println(name); // 2 } void printName2(){ System.out.println(this.name); //3 System.out.println(name); // 4 } }

A

1) will not compile as this is not available in a static method. There is no instance associated with a static method. 2) still will not compile 3) compiles fine 4)compiles fine

27
Q

Do we always need to use “this” when accessing instance members?

A

You don’t always need to explicitly use this, only if there’s a local variable with the same name and you want to refer to instance instead of the local one.

28
Q

Can instance fields be accessed from a static method?

A

Yes it can however it has to specify the instance whose member it will be accessing. e.g class Book { int name; // instance variable static void printName(){. // static method Book b1 = new Book(); System.out.println(b1.name); // compiles fine

29
Q

What is the purpose a static block

A

allows us to initialise static fields of a class

30
Q

What are the four rules applied to static blocks?

A

1) A class can have any number of static block 2) A static block can access both static variables and members of the class. However if a static variable is declared after a static block, you can only set this value in a static block. 3) If the class has a superclass, and if the superclass hasn’t already been initialised, the JVM will initialise the superclass first and then proceed with the initialisation of the child class. 4) static blocks can’t be invoked like how you would call a method or constructor. They are invoked only once by the JVM when the class loads

31
Q

Will these lines of code compile? class TestClass{ static int a; static{ System.out.println(a); // 1 System.out.println(b); //2 b = 10; // 3 m() // 4 } static void m(){ System.out.println(b); //5 } static int b; // 6 static variable public static void main(String[] args){ } static{ System.out.println(b); // 7 } }

A

1) compiles fine as a is declared before 2) wont compile as we are unable to read b’s value as it is declared on line 6 after it is being printed on 2. 3) line is valid as b is assigned a value in a static block 4) valid, you can call a method anywhere in the class 5) valid, a method can do anything with a variable that is declared later in the code 7) it is legal to print b here as it has been declared and assigned a value

32
Q

What members do instance initialisers have access to?

A

They have access to all members of a class including static members

33
Q

what is method overloading?

A

When a class has multiple methods with the same name but different param types

34
Q

What will be printed? public class TestClass{ static void doSomething(Integer i, short s){ System.out.println(“1”); } static void doSomething(int in, Short s){ System.out.println(“1”); } public static void main(String[] args){ int b = 10; short x = 20; doSomething(b, x); }}

A

Code will not compile as its too ambiguous. The compiler is unable to determine which one of the methods to use because both of them are equally applicable.

35
Q

Which line will be called when “hello” is passed in void processData(Object obj){ } // 1 void processData(String str){ } // 2

A

line 2 will get called as “hello” is a string literal and thus an exact match for the method.

36
Q

What are the 5 rules regarding method overloading?

A

1)compile error for ambiguity or if methods are too similar as in not overloaded correctly. 2) exact match - if the compiler finds a method whose parameter list is an exact match, it will be called 3) most specific method - if more than one method matches the criteria, the most specific one will be called.e.g subtype over parent/interface 4) consider widening before autoboxing - a primitive is most likely to be called over a wrapper 5)autoboxing before varargs - wrapper obj is more likely to be picked over a varargs parameter

37
Q

What is happening in this code & what does it print? class Data{ int value = 100; } public class TestClass { public static void main(String[] args){ Data d = new Data(); modifyData(d); System.out.println(d.value); } public static void modifyData(Data x){ x.value = 2*x.value; } }

A

1) inside main, we are creating a new data object and passing it to reference d. 2) main then invokes the modifyData method and passes it a copy of d( which stores the object that has the value of 100) 3)The modifyData method then uses the reference variable x to modify the value field of Data object , the same object that x is pointing to. 4)The value is changed to 200 . When the control goes back to the main method, it prints d.value, which is now 200 .

38
Q

What is “this”?

A

this is an implicit variable used to refer to any member of a current object(class) from within an instance method or constructor

39
Q

How can this be used?

A

it can be used to refer to an instance variable instead of a local if both have the same name 2) it can be used inside a constructor to call another constructor in the same class. this is required as a constructor can’t be called explicitly 3) it can be used inside a method to call another method inside the same class

40
Q

What is happening on line 1? class Data{ int value = 100; } public class TestClass { public static void main(String[] args){ modifyData(new Data()); // 1 } public static void modifyData(Data x){ x.value = 2*x.value; } }

A

1) main is calling the method modifyData and is passing in an a temporary reference variable that holds the data object. This variable is created implicitly by the compiler As we have not saved the result of this call to an explicit reference, we can’t refer to it.

41
Q

What is constructor overloading

A

This is when a class has more than one constructor

42
Q

What is the rule regarding constructor chaining?

A

When referring to another constructor, you must use this or super as the first line of your statement not both

43
Q

What are rules regarding final static variables and initialisation?

A

1)you can either assign a value to a final static variable at the time of declaration or in any one of the static initialisers 2) you can initialise a static final var in any static block but in only one of them

44
Q

Will the following compile? class TestClass{ final static int value; static { value = 10; // 1 } static { value = 20; // 2 }

A

No line 2 won’t compile as value has already been initialised and once the value has been set, you can’t change it

45
Q

What are rules regarding instance final variables and initialisation?

A

this is the same as for static final variables, the only difference is that final instance variables would be initialised inside instance blocks as well as constructors.

46
Q

Which one of these lines won’t compile? class TestClass{ final int value; { // 1 } TestClass(){ value = 10; // 2 } TestClass(int x){ value = x; } TestClass(int a, int b){ // 3 }

A

Line 3 won’t compile as you aren’t declaring value inside the static initialiser which is called first or in the constructor.

47
Q

What are the rules for final local variables in a method?

A

if they are to be used, they have to be explicitly initialised first, if not used they can be left uninitialised.

48
Q

What does the method signature include?

A

method name & its ordered list of parameters e.g these all have the same signature: 1) void process(int a, string str); 2) public void process(int value, String name); 3) void process(int a, String str) throws Exception;

49
Q

Which method will get picked when processData( (byte) b); is called? void processData(short value){ }. // 1 void processData(Byte value){ } // 2

A

1 will get picked based on the rules of overloading methods that state widening is chosen over autoboxing.

50
Q

What will be the output of this program?

class Program{

public static void main(String args[]) {

String [] x = {“A”,”B”, “C”, “D”, “E”};

nxt(x);

for(String s: x)

System.out.print(s+” “);

}

static void nxt(Object obj) {

String [] y = (String[]) obj;

for(int i = 5, j = 0; i> 0; –i, j++) {

y[j] = Integer.toString(i)

}

}

}

  1. 12345
  2. 1234
  3. 54321
  4. 5432
  5. Compilation fails
A

3) 54321 is the correct answer

This qtn focuses on pass by value and using loops.

Method nxt is called inside main and is passed x, a String array. nxt accepts any object as a parameter thus an array will work. Inside this method, a new String array called y is created and assigned a copy of array x that is now an object thus requiring a cast to fit into an array.

Inside the for loop: we use variable j to access elements of the y array and then assign these elements a number in string format starting from i which is 5. Now y contains {5,4,3,2,1}

y and x are reference variables that point to the same object. any changes made to y will reflect in x thus when we access the elements in x inside main, we get the same result 5,4,3,2,1.

51
Q
class Program{
 public static void main(String args[]) {
 Double d1 = 0.0/0.0;
 System.out.println(Double.isNaN());
 System.out.println(d1.isInfinite());

What will be the output of this program?

A, true false

B. false false

C. An Exception is thrown

D. Compilation fails on line 7

E. Compilation fails on line 8

A

D is correct.

Double has 2 isNaN() methods, one static and one instance. The static method takes a Double as a param whereas the instance takes no args.

the code doesn’t compile as we are attempting to access the instance no args method from a static context which isnt allowed.

If the code said d1.isNaN();, then this would compile and print true. you can access an instance method from static context only if you use the instance (d1) to access it.

52
Q

Which statement when inserted on line 1 will compile the code?

class Program{
 public static void main(String args[]) {
 Print p = new Print();
// line 1
 }
}
class Print {

private void p2(int i){

System.out.println(i*2);

}

static void p2(int i){

System.out.println(i);

}

}

A, Print.p2(6)

B. P.p2(6)

C. p.print(6)

D. Print.print()

E. None of the above

A

C) p.print(6) is correct

you can access a static method using an instance variable. its not recomended but its legal.

53
Q

What will be the output of this program?

  1. class Program{
  2. static {
  3. x = 10;
  4. y = 5;
  5. }
  6. final int x;
  7. final static int y;
  8. public static void main(String args[]) {

9 try{

10 Program pr = new Program();

11 int c = pr.x/y;

12 System.out.print(c);

13 } catch (ArithmeticException E) {

14 System.out.print(“Arithmetic Exception”);

15 }

16 }

17 }

A. 2

B. 0

C. Compilation fails on line 3

D. Compilation fails on line 11

E. Compilation fails on multiple lines

A

C) Compilation fails on line 3 as we are attempting to access a non-static member from a static initialiser