✏️ Explanatory Question

[Packages]

Question:

Given the following code snippet:

package mine;

public class Greetings
{
    public static void greet(String name)
    {
        System.out.println("Hello " + name + 
        ", welcome to the world of programming");
    }
}
import java.util.*;
import mine.*;

public class Trial
{
    public static void main()
    {
        Scanner sc = new Scanner(System.in);

        System.out.println("Give your name");

        String n = sc.next();

        Greetings.greet(n);
    }
}

(a) Predict the output for n = "Abhay".

(b) Explain the difference between:

import java.util.*;

and

import mine.*;

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Answer:

(a) Output:

Give your name
Abhay
Hello Abhay, welcome to the world of programming

Explanation:

  • The Scanner object takes input from the user
  • The input entered is:
    Abhay
  • The method:
    Greetings.greet(n);
    is called
  • The greet() method prints the welcome message

(b) Difference between the two import statements:

import java.util.*;
  • Imports all classes from the predefined package: java.util
  • Used to access utility classes like:
    Scanner
    ArrayList
    Date
    Random
  • It is a built-in Java package
import mine.*;
  • Imports all classes from the user-defined package: mine
  • Used to access the class:
    Greetings
  • It is a custom package created by the programmer

Conclusion:

  • java.util.* → imports predefined utility classes
  • mine.* → imports user-defined package classes
  • Output message is generated through the greet() method