Java OCA OCP Practice Question 389

Question

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 Main  { 
    public static void main (String [] args) throws Exception  { 
        Logger logger = new Logger (); 
        logger.log ("hello"); 
     } 
} 

What changes will enable the code to compile and run?

Select 2 options

  • A. Replace Logger logger = new Logger (); with: log4j.Logger logger = new log4j.Logger ();
  • B. Replace package util.log4j; with package util;
  • C. Replace Logger logger = new Logger (); with: util.log4j.Logger logger = new util.log4j.Logger (); D. Remove package util.log4j; from Logger.
  • E. Add import log4j; to Main.


Correct Options are  : B C

Note

If you are not importing a class or the package of the class, you need to use the class's fully qualified name while using it.

Here, you need to use util.log4j.Logger instead of just log4j.Logger: util.log4j.Logger logger = new util.log4j.Logger ();

Using a fully qualified class name always works irrespective of whether you import the package or not.

Remember that you can never access a class that is defined in the default package (i.e. the package with no name) from a class in any other package.




PreviousNext

Related