Chapter 1- Java Building blocks Flashcards

1
Q

What is happening on these lines of code?

1) int x = 10;
2) int x = new Integer(10);
3) String SomeClass obj = new SomeClass();
4) int a = 10, b = 20, c = 30;
5) String s1 = “123”, s2 = “hello”;

6 )int m = 20; int p = m = 10;

7) int a, b = 10, c = 20;
8) String s1 = “123”, s2;
9) int a = 10, int b;
10) int a, Object b;
11) int x = y = 10;

A

1) initialising x using an int literal 10
2) initialising x using a primitive wrapper class
3) initialising obj by creating a new instance of SomeClass
4) initialising each variable of the same type with a different value
5) same as no. 4
6) assign 20 to m for the first statement. For the second, evaluate from right to left, reset m to 10 and use the new value of m to initialise p; so m & p both equal 10
7) a is declared but not initialised. b and c are being declared as well as initialised
8) Only s1 is being initialised
9) Doesn’t compile as you can have only one type name in one statement.
10) same as no. 9
11) Doesn’t compile, y must be defined before using it to initialise x.

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

What will be printed?

public class TestClass {

static int i;

static float d;

static boolean f;

static String s;

public static void main(String[] args){

System.out.println(i);

System.out.println(d);

System.out.println(f);

System.out.println(s);

}

}

A

0 0.0 false null

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

Will this compile?

public class TestClass {

public static void main(String[] args){

int p;

System.out.println(p);

}

}

A

Compile error. local variables must be explictly initialised before use

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

Will this compile?

public class TestClass {

public static void main(String[] args) throws Exception {

int val;

val = 10;

System.out.println(val);

}

}

A

compiles fine and prints 10 Even though the variable val is not initialised when declared, it is assigned before its used.

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

Will this compile?

public class TestClass {

public static void main(String[] args) throws Exception {

int val;

int i = 0; //LINE 4

if(i == 0){ val = 10; }

System.out.println(val);

}

}

A

no it wont compile. Even though we know i == 0 is true, the compiler won’t know what the actual value of i will be at the time of execution because i is not a compile time constant. Therefore, the compiler concludes that if the if condition evaluates to false , the variable val will be left uninitialised. you can solve this making line 4 a final variable. this makes i a compile time constant meaning that i ==0 will always be true

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

Will this compile?

int val;

int i = 0;

if(i == 0) {

val = 10;

} else {

val = 20;

} System.out.println(val);

A

yes. Even though i isn’t a compile time constant(final) the compiler doesn’t have to know the value of i here. If-else is one statement and the compiler is now sure that no matter what the value of i is, val will definitely be assigned a value.

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

What is a final variable?

A

A variable whose value doesn’t change once its has a value assigned to it.

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

Will these lines of code compile when run independently?

class Data{

int x = 10;

}

public class TestClass {

public static void main(String[] args){

final Data d = new Data();

d = new Data(); // 1

d.x = 20; // 2

}

}

A

line 1 will not compile as d i final. // once assigned a value, you can’t reassign it another value / it can’t refer to another object. line 2 compiles as we aren’t changing d but using it to access an instance variable which we then assign the value of 10.

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

What are the rules for identifiers in java?

A

1) you can’t use a Java reserved word 2) The name must begin with either letters, the symbol $ or _ 3) subsequent characters can be numbers

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

Are these legal?

1) _also0K1d3ntifi3r
2) hollywood@vine
3) strictfp
4) goto*
5) native
6) __SStill0kbutKnotsonice$

A
  1. legal
  2. illegal @ isn’t recognised
  3. illegal, reserved word
  4. illegal, reserved word
  5. illegal, reserved word
  6. legal
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What will be the output of compiling class B?

package one;

class A { // 1

protected int j = 12; // 2

}

package two

class B extends A { // 3

public static void main(String [] args) {

A a = new A(); // 4

}

}

A

Compilation will fail on lines 2 & 4.

class A has a defualt access modifier meaning it can’t be accessed from another package as a result, instantiating class A would also fail.

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

Given the code below, what is the output?

  1. public class Whiz {
  2. public static void main(String [] a) {
  3. int [] a = {1,2,3};
  4. System.out.println(a[3]);
  5. }
  6. }
A

Compilation will fail on line 3 as you can’t declare two variables with the same name in the same scope - the main method also has variable a

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

Which of the following is not a valid int literal?

A. 1_000

B. 012

C. 0B01

D. 0XE

E. None of these

A

E is correct.

As of java 7, integral types can be expressed using binary, octal & hexadecimal literals

B is octal literal

C is binary

D is hexadecimal

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

Which of the following is not a valid int literal?

A. 1_000

B. 012

C. 0B021

D. 0X33

E. 10

A

C is not a valid literal

this option uses 2 which is not possible in a binary number

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

Given:

……………. is responsible for the hardware- and operating system- independence of the Java SE platform, the small size of the compiled code(bytecodes) and platform security.

A. Java Development Kit (JDK)

B. Java Virtual Machine (JVM)

C. Java Runtime Environment (JRE)

D. Java SE platform

E. None of the above

A

B. Java Virtual Machine (JVM)

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

What is the role of the JDK?

A

The Java Development Kit is the superset of the JRE since it contains the JRE i.e JVM & libraries as well as dev tools such as java compile, debuggers and core classes necessary for developing applications

JDK is what you need to compile Java source code.

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

What does the JRE do?

A

Java Runtime Environment is a container that holds all the libraries, the JVM and other files needed to run java applications.

The JRE is the environment in which the JVM uses these libraries and files to run applications at runtime

JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc) + runtime libraries.

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

What does the JVM do?

A

After our java program is compiled it is converted to byte code and a .class file is created. The (JVM) is responsible for converting this byte code to the machine-specific code.

provides platform independence & security

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

Which of the following must be included in a java source file to compile and generate bytecode?

A. Package declaration

B. Class declaration

C. Import statement/s

D. Main method

E. field declaration

A

Class declaration is required inorder to generate a .class file which contains the bytecode after compiling

The class doesnt have to have a main method for this .classfile to be generated, only the class signature.

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

What does the javac command do when run?

A

it compiles a .javafile and creates a .classfile that contains bytecode

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

How would you compile and run a class named Program.java?

A

To compile use - javac Program.java

To run use - java Program

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

What will be the output of the code below?

public class DataTypes {

static int x = 4;

public static void main (String [] args) {

for(int x = 5; x<10; x++)

x++;

System.out.println(x–);

}

}

A

the output will be 4.

Due to the absence of curly braces on the for statement, th print statement is not in scope for the loop thus it prints the static int varaible x.

Had brackets been around the print statement aswell, the answer would have been 678910.

for(int x = 5; x<10; x++) {

x++;

System.out.println(x–);

}

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

What is the output of this code?

public class Whiz {

public static void main (String [] args) {

int x =0;

do{

int y = x++;

System.out.println(x–);

} while(y<5);

}

}

A

Compilation fails as y was declared inside the do loop, it is out of scope when we try to access it out of that block

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

Which of the following are sufficient enough to run a Java program only?

A. Java Development Kit (JDK)

B. Java Virtual Machine (JVM)

C. Java Runtime Environment (JRE)

D. Java SE platform

E. None of the above

A

C. Java Runtime Environment (JRE)

JRE consists of the JVM and the core java classes and libraries

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

Given the following class in the file programs/mine/whiz/Fan.java :

// line 1

public class Fan { }

Which of the following replaces line 1 if we compile the class from programs?

A. package programs. mine.whiz;

B. package Fan;

C. package mine.whiz;

D. package whiz

E. None of the above

A

C. package mine.whiz;

The package name represents any folders underneath the curent path.

As we would be compiling from the programs folder, we would only need to provide mine.whiz.

26
Q

What happens when you use the javac command an empty java file?

A

nothing, the .classfile doesnt get generated.

27
Q

What will be the output of this code?

  1. public class Whiz {
  2. static int x = 9;
  3. public static void main (String [] args) {
  4. int x = 8;
  5. for (; x>-1; x–)
  6. System.out.println(x);
  7. }
  8. }

A. 9876543210

B. 876543210

C. Compilation fails on line 4

D. Compilation fails on line 5

E. Compilation fails on multiple lines

A

B. 876543210

Whenever there are 2 variables declared with the same name, in two different scopes, the closest scope overshadows the other variable. the for loop on line 5 uses the local variable at line 4 as its closer than the one on line 2

28
Q

What will be the output of this code?

  1. public class Whiz {
  2. public static void main (String [] args) {
  3. for (int x = 3; x>-1; x–);
  4. System.out.println(x);
  5. }
  6. }

A. 3210

B. 210

C. 0

D. -1

E. Compilation fails

A

E. Compilation fails

Code fails to compile on line 4 as x is out of scope. x is declared in the for loop that ends on line 3 due to the semi colon.

29
Q

Which symbol is used to create multi line comments in java?

A

/* */

30
Q

Which symbol is used to create a java doc comment in java?

A

/**

comment here

*/

31
Q

Which symbol is used to create a single line comment in java?

A

//

32
Q

Which one of the following is a valid top level class declaration?

A. class one(){}

B. static class Test{}

C. protected class Test{}

D. class If{}

E. All of the above

A

D. class If{}

eventhough “if” is a reserved word, java is case senstive thus “If” is acceptable

A. - method declaration due to the paranthesis

B- can’t use static with top level classes

C - can’t use protected ir private accesses modifers on top level classes

33
Q

What will be the output of attempting to compile and run this class?

public class Java8ExamPractice {

static
{
System.out.println(“This java program will run without main”);
System.exit(0);
}
}

A. This java program will run and the print statement will be displayed

B. Compilation succeeds and no output

C. An Exception is thrown at runtime

D. Compilation fails

E. None of the above

A

E. None of the above

The program will compile successfully however an error will be thrown at runtime.

34
Q

Which of the following are true?

A. Java is platform independent

B. Java is object oriented programming language

C. Java doesnt support multiple inheritance completely

D. All of the above

E. None of the above

A

D. All of the above

35
Q

Consider the following two classes defined in two .java files.

//in file /root/com/foo/X.java
package com.foo;
public class X{
 public static int LOGICID = 10;
 public void apply(int i){
 System.out.println("applied");
 }
}
//in file /root/com/bar/Y.java
package com.bar;
//1 \<== INSERT STATEMENT(s) HERE
public class Y{
 public static void main(String[] args){
 System.out.println(X.LOGICID);
 }
}
What should be inserted at //1 so that Y.java can compile without any error?

A. import static X;

B. import static com.foo.*;

C. import static com.foo.X.*;

D. import com.foo.*;

E. import com.foo.X.LOGICID;

A

D. import com.foo.*;

This is required because Y is accessing class X. static import of LOGICID is NOT required because Y is accessing LOGICID through X ( X.LOGICID). Had it been just System.out.println(LOGICID), only one import statement: import static com.foo.X.*; would have worked.

A and B are bad syntax, you can’t use static to import a package

E is also bad syntax, you can only import static fields using “import static

36
Q

True or False, It is not required to import java.io.* or import java.io.IOException because java.io package is imported automatically.

A

false if you want to use IOException, you must import the java.io package. only java.lang is imported automatically

37
Q

Which of these options will compile?

You have to select 2 options

1) //In file A.java
import java.io.\*;
package x;
public class A{
}
2) //In file B.java
import java.io.\*;
class A{
 public static void main() throws IOException{ }
}
3) //In file A.java
public class A{
 int a;
 public void m1(){
 private int b = 0;
 a = b;
 }
}
4) //In file A.java
public class A{
 public static void main(String[] args){
 System.out.println(new A().main);
 } 
 int main;
}

5) Only one of the above options is correct.

A

2 and 4 are correct.

**2** - You can have a non-public class in a file with a different name.
 You can have a main method that doesn't take String[] as an argument however It will not make the class executable from the command line.

4 - you can have a method and a field with the same name in a class

wrong options -

1 - package statement comes before import

3 - you cant add access modifiers to local variables.

38
Q

Which of these statements are true? Choose 2

A. A static method can call other non-static methods in the same class by using the ‘this’ keyword.

B. A class may contain both static and non-static variables and both static and non-static methods.

C. Each object of a class has its own copy of each non-static member variable.

D. Instance methods may access local variables of static methods.

E. All methods in a class are implicitly passed a ‘this’ parameter when called.

A

B and C

this is not availabe in static methods as there isnt an instance/ current object available for them

‘this’ is assigned a reference to the current object automatically by the JVM. Thus, within an instance method foo, calling this.foo(); is same as calling foo();

D - local variables can only be accessed in the method they are defined, accessing them anywhere outside that method would be out of scope.

39
Q

Consider the following class:

public class ArgsPrinter{

public static void main(String args){

for(int i=0; i<3; i++){

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

}

}

}

What will be printed when the above class is run using the following command line: java ArgsPrinter 1 2 3 4

A. 1 2 3

B .ArgsPrinter 1 2

C. java ArgsPrinter 1 2

D. 1 1 1

E. None of the above.

A

E. None of the above.

The main method doesn’t declare the String array correctly, misses [] thus an exception will be thrown at runtime saying no main(String [] ) method found.

40
Q

What is the equivalent of using String[] in the main method?

A

String…

varags parameter is the same as declaring a String Array

41
Q

Consider the following two classes defined in two .java files.

//in file /root/com/foo/X.java
package com.foo;
public class X{
 public static int LOGICID = 10;
 public void apply(int i){
 System.out.println("applied");
 }
}
//in file /root/com/bar/Y.java
package com.bar;
**//1 \<== INSERT STATEMENT(s) HERE**
public class Y{
 public static void main(String[] args){
 X x = new X();

x. apply(LOGICID);
}
}
What should be inserted at //1 so that Y.java can compile without any error? Choose 2 options

A. import static X;

B. import static com.foo.*;

C. import static com.foo.X.*;

D. import com.foo.*;

E. import com.foo.X.LOGICID;

A

C and D

42
Q

Given the following class, which of these are valid ways of referring to the class from outside of the package com.enthu?

package com.enthu;

public class Base{

// lot of code…

}

A. Base

B .By importing the package com.* and referring to the class as enthu.Base

C. importing com.* is illegal.

D. By importing com.enthu.* and referring to the class as Base.

E. By referring to the class as com.enthu.Base.

A

D and E are correct.

A class or interface can be referred to by using its fully qualified name or its simple name.
Using the fully qualified name will always work, but to use the simple name either the class must be in the same package or it has to be imported.
By importing com.enthu.\* all the classes from the package will be imported and can be referred to using simple names.
Importing com.\* will not import the subpackage enthu. It will only import the classes in package com.
43
Q

Given the following set of member declarations, which of the following is true?

int a; // (1)
 static int a; // (2)
 int f( ) { return a; } // (3)
 static int f( ) { return a; } // (4)

Choose 2 options:

A. Declarations (1) and (3) cannot occur in the same class definition.

B. Declarations (2) and (4) cannot occur in the same class definition.

C. Declarations (1) and (4) cannot occur in the same class definition.

D. Declarations (2) and (3) cannot occur in the same class definition.

E. Declarations (1) and (2) cannot occur in the same class definition.

A

C and E are true

Declarations (1) and (4) cannot occur in the same class definition :

static methods can’t access instance variables

Declarations (1) and (2) cannot occur in the same class definition:

variable names must be different

44
Q

What is a method?

A

Piece of behaviour that can be called again

45
Q

What are the key benefits of java?

A

Object Oriented

Encapsulation

Platform independent - The same class files run evrywhere

Robust - manages memory on its own and does garbage collection automatically

Simple

Secure

46
Q

What are the naming conevntions for variables in Java?

A
  1. names can start with a letter or $ and _
  2. Subsequent characters maybe letters, numbers, $ and _
  3. names can’t be the same as a reserved java keyword e.g public, if, return, extend
  4. names are case sensitive e.g public won’t compile but Public will.
  5. variables can have the same name as methods and classes e.g the following are perfectly legal: int Double = 7; String main = “hello”; String String = “wow”
47
Q

What are local variables?

A

This is where an object stores its temporary state. Temporary as these variables are only available within the scope of a method.

Once the method has completed executing, these variables are garbage collected

48
Q

What is a static variable?

A

This is a variable that belongs to the class not the instance.

49
Q

What does marking a variable as static do?

A

Marking a variable as static informs the compiler that only one copy of this variable exists regardless of how many times a class is instantiated.

50
Q

What are instance variables and why are they called this?

A

These are non-static fields where objects store their state.

They are known as instance variables cos their values are unique to each instance of a class

51
Q

Which feature of Java when used on its own, can execute a java application?

A

The JRE, you don’t need the JDK as development or compilation of java source code is not required to run an application.

52
Q

Will this code compile?

int i = 5;

int val;

if(i != 0)

val = 10;

else

System.out.println(val);

A

No the code will not compile.

As variable i isnt a compile time constant, the compiler thinks there is a possiblity that val will not get initialised in the else block at runtime e.g if the value of i changes

53
Q

What will the following code print when run?

public class TestClass {

public static long main(String[] args){

System.out.println(“Hello”);

return 10L;

}

}

A

It will throw an error at runtime.

When the program is run, the JVM looks for the main method as the first point of entry which returns void. In this case main returns long thus an error will be thrown at runtime

54
Q

What will the following code snippet print when compiled and run?

byte starting = 3;

short firstValue = 5;

int secondValue = 7;

int functionValue = (int) (starting/2 + firstValue/2 + (int) firstValue/3 ) + secondValue/2;

System.out.println(functionValue);

A

7

Remember that whenever both the operands of a mathematical operator (such as / and *) are integral types except long (i.e. byte, char, short, and int), the result is always the integer value that remains after truncating the fractional value. For example, 5/3 is 1.6666 but the result will be 1 after removing the fractional part. Observe that there is no “rounding off” here.

In the expression given in this question, starting, firstValue, and secondValue are of type byte, short, and int respectively. Thus, the above rule is applicable here. Therefore, starting/2 will result in 1, firstValue/2 will result in 2, firstValue/3 will result in 1, and secondValue/2 will result in 3. The expression will therefore be equivalent to:

(int) ( 1 + 2 + 1 ) + 3
=> (int)(4) + 3
=> 7

Although not important for this question, you should remember that the type of the result will be int even if both the operands are of a type that is smaller than an int. Thus, the following will not compile -
byte b1 = 1;
byte b2 = 2;
byte b = b1 + b2; //result is of type int, which cannot be assigned directly to a byte

You have to use a cast:
byte b = (byte) (b1 + b2); //OK now

Similarly, when one of the operands is of type long, float, or double and the other operand is of a smaller size, the result will be a long, float, or double respectively.

55
Q

The options below contain the complete contents of a file.

Which of these options can be run with the following command line once compiled? java main

  1. //in file main.java
class main {
 public void main(String[] args) {
 System.out.println("hello");
 }
}
  1. //in file main.java

public static void main(String[] args) {
System.out.println(“hello”);
}

  1. //in file main.java
public class anotherone{
}
class main {
 public static void main(String[] args) {
 System.out.println("hello");
 }
}
4. //in file main.java
class anothermain{
 public static void main(String[] args) {
 System.out.println("hello2");
 }
}
class main {
 public final static void main(String[] args) {
 System.out.println("hello");
 }
}
A

4 is correct.

Observe that there is no public class in file main.java. This is ok. It is not necessary for a java file to have a public class. The requirement is that if a class (or enum) is public then that class (or enum) must be defined in a file by the same name and that there can be only one public class (or enum) in a file.

class main’s main method will be executed. final is a valid modifier for the standard main method.

Note that final means a method cannot be overridden. Although static methods can never be overridden (they can be hidden), making a static method final prevents the subclass from implementing the same static method.

56
Q

Identify 2 correct options:

  1. Multiple inheritance of state includes ability to inherit instance methods from multiple classes.
  2. Multiple inheritance of state includes ability to inherit instance fields from multiple classes.
  3. Multiple inheritance of type includes ability to inherit instance fields as well as instance methods from multiple classes.
  4. Multiple inheritance of type includes ability to implement multiple interfaces and ability to inherit static or instance fields from interfaces and/or classes.
  5. Multiple inheritance of type includes ability to implement multiple interfaces and/or ability to extend from multiple clases.
A

2 and 5 are correct

Interfaces, classes, and enums are all "types". Java allows a class to implement multiple interfaces. In this way, Java supports multiple inheritance of types. 
"State", on the other hand, is represented by instance fields. Only a class can have instance fields and therefore, only a class can have a state.

(Fields defined in an interface are always implicitly static, even if you don’t specify the keyword static explicitly. Therefore, an interface does not have any state.)

Since a class is allowed to extend only from one class at the most, it can inherit only one state. Thus, Java does not support multiple inheritance of state.

57
Q

True or False:

Multiple inheritance of state includes ability to inherit instance methods from multiple classes.

A

False

Methods do not have state. Ability to inherit instance methods from multiple classes is called multiple inheritance of implementation.

Default methods introduce one form of multiple inheritance of implementation.

A class can implement more than one interface, which can contain default methods that have the same name. However, such a class cannot be compiled. In this case, the implementing class is required to provide its own implementation of the common method to avoid ambiguity

58
Q

You are writing a class named Bandwidth for an internet service provider that keeps track of number of bytes consumed by a user. The following code illustrates the expected usage of this class :

class User{

Bandwidth bw = new Bandwidth();

public void consume(int bytesUsed){

bw.addUsage(bytesUsed);

}

}

class Bandwidth{

private int totalUsage;

private double totalBill;

private double costPerByte;

//add your code here

}

Your goal is to implement a method addUsage (and other methods, if required) in Bandwidth class such that all the bandwidth used by a User is reflected by the totalUsage field and totalBill is always equal to totalUsage*costPerByte.

Further, that a User should not be able to tamper with the totalBill value and is also not able to reduce it.

Which of the following implementation(s) accomplishes the above?

A) public void addUsage(int bytesUsed){
if(bytesUsed>0){
totalUsage = totalUsage + bytesUsed;
totalBill = totalBill + bytesUsed*costPerByte;
}
}

B) protected void addUsage(int bytesUsed){
totalUsage += bytesUsed;
totalBill = totalBill + bytesUsed*costPerByte;
}

C) private void addUsage(int bytesUsed){
if(bytesUsed>0){
totalUsage = totalUsage + bytesUsed;
totalBill = totalUsage*costPerByte;
}
}

D) public void addUsage(int bytesUsed){
if(bytesUsed>0){
totalUsage = totalUsage + bytesUsed;
}
}
public void updateTotalBill(){
totalBill = totalUsage*costPerByte;
}

A

A is correct

59
Q

Given the following contents of two java source files:

package util.log4j;

public class Logger {

public void log(String msg){

System.out.println(msg);

}

}

and package util;

public class TestClass {

public static void main(String[] args) throws Exception {

Logger logger = new Logger();

logger.log(“hello”);

}

}

What changes, when made independently, will enable the code to compile and run?

  1. Replace Logger logger = new Logger(); with:
    log4j. Logger logger = new log4j.Logger();
  2. Replace package util.log4j; with
    package util;
  3. Replace Logger logger = new Logger(); with:
    util. log4j.Logger logger = new util.log4j.Logger();
  4. Remove package util.log4j; from Logger.
  5. Add import log4j; to TestClass.
A

2 and 3 are correct

2 will put both the classes in the same package and TestClass can then directly use Logger class without importing anything.

3) Using a fully qualified class name always works irrespective of whether you import the package or not. In this case, all classes of package util are available in TestClass without any import statement but Logger is in util.log4j. Therefore, the use of fully qualified class name for Logger, which is util.log4j.Logger, makes it work

60
Q

What will the following code print when compiled and run?

public class ATest {

String global = “111”;

public int parse(String arg){

int value = 0;

try{

String global = arg;

value = Integer.parseInt(global);

}

catch(Exception e){

System.out.println(e.getClass());

}

System.out.print(global+” “+value+” “);

return value;

}

public static void main(String[] args) {

ATest ct = new ATest();

System.out.print(ct.parse(“333”));

}

}

A

111 333 333

Observe that a new local variable named global is defined within a try block. It is accessible only within the try block. It also shadows the instance field of the same name global within the try block. It is this variable that is used in parseInt. Therefore, value is set to 333.

However, when you print global in parse method, the global defined in the try block is out of scope and the instance field named global is used. Therefore, it prints 111.

There is no exception because 333 can be parsed into an int. If you pass a string that cannot be parsed into an int to the parseInt method, it will throw a java.lang.NumberFormatException.