0
0
Javaprogramming~15 mins

Creating packages in Java - Practice Exercises

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
Package Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 code output
intermediate
2:00remaining
Output of Java package usage
What is the output of the following Java code when run?
Java
package com.example.utils;

public class Helper {
    public static String greet() {
        return "Hello from Helper!";
    }
}

// In another file:
package com.example.app;

import com.example.utils.Helper;

public class Main {
    public static void main(String[] args) {
        System.out.println(Helper.greet());
    }
}
AHello from Helper!
BCompilation error: cannot find symbol Helper
CRuntime error: NoClassDefFoundError
DHello from Main!
Attempts:
2 left
💻 code output
intermediate
2:00remaining
Effect of missing package declaration
What happens if you remove the package declaration from a Java file that is supposed to be in a package?
Java
package mypkg;

public class Test {
    public static void main(String[] args) {
        System.out.println("In package mypkg");
    }
}

// Now remove the line 'package mypkg;' and compile and run.
AThe program runs and prints 'In package mypkg'
BCompilation error: class not found in package
CRuntime error: ClassNotFoundException
DThe program runs but prints nothing
Attempts:
2 left
🔧 debug
advanced
2:00remaining
Identify the cause of compilation error with packages
Why does the following code cause a compilation error?
Java
package com.example;

public class A {
    public static void main(String[] args) {
        B b = new B();
        b.sayHi();
    }
}

// In file B.java:
package com.example.other;

public class B {
    public void sayHi() {
        System.out.println("Hi from B");
    }
}
AClass B's method sayHi is static but called on instance
BClass B is not public
CClass A does not import com.example.other.B
DClass A and B must be in the same package
Attempts:
2 left
📝 syntax
advanced
1:00remaining
Correct package declaration syntax
Which of the following is the correct way to declare a package in a Java file?
Apackage com.example.utils
Bpackage com.example.utils;
Cpackage com.example.utils()
Dpackage com.example.utils {}
Attempts:
2 left
🚀 application
expert
3:00remaining
Number of classes accessible without import
Given these two packages and classes, how many classes can class Main access directly without import statements?
Java
package alpha;
public class A {}
public class B {}

package beta;
public class C {}

package alpha;
public class Main {
    public static void main(String[] args) {
        // How many of A, B, C can be used here without import?
    }
}
A0 classes
B3 classes (A, B, and C)
C1 class (A only)
D2 classes (A and B)
Attempts:
2 left