Skip to main content

ProwessApps

Learn · Practice · Excel

Define a package named temperature and create a class named Conversion that has a method which converts the temperature from Fahrenheit to Celsius. Define a package named mypack and create a class that has method which calls methods of Conversion class of temperature package.

Java Code Example — Package Programs

ADVERTISEMENT

Define a package named temperature and create a class named Conversion that has a method which converts the temperature from Fahrenheit to Celsius. Define a package named mypack and create a class that has method which calls methods of Conversion class of temperature package.

Objective

Write a Java program to define a custom temperature conversion package and call it from another package.

Algorithm / Approach

  1. Create a class named Conversion.
  2. Declare its package as package temperature;.
  3. Add a public method to convert Fahrenheit to Celsius.
  4. Create a Test class and declare its package as package mypack;.
  5. Import the temperature package: import temperature.*;.
  6. In the main method, instantiate the Conversion class and execute the conversion.
Conversion.java
// File 1 - Conversion.java
package temperature;
public class Conversion {
 public double convert(int f) {
  double c = 5.0/9*(f-32);
  return c;
 }
}
                    
// File 2: Test.java
package mypack;
import temperature.*;
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Conversion c=new Conversion();
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Temp in (F): ");
  int f = s.nextInt();
  double res = c.convert(f);
  System.out.print("Temp in Cel. = "+res);
 }
}

Expected Output

Enter Temp in (F): 50
Temp in Cel. = 10.0

Explanation of the Program

  • This program reinforces how packages act as namespaces. The temperature package houses our mathematical utility.
  • Crucially, the convert() method inside the Conversion class MUST be marked as public.
  • If you omit the public access modifier, the method will default to "package-private", meaning it can only be accessed by other classes inside the temperature package, and the Test class in mypack would throw an error.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT