Java Programming Practical 10

Question 1
Write a program to implement user defined packages in terms of creating a new package and importing the same.
PkgClass.java
Java
				package pkg1;

public class PkgClass 
{
    public void show()
	{
        System.out.println("This is inside package");
    }

    public static int subtract(int a, int b) 
	{
        return a - b;
    }
}
			
Save this file as PkgClass.java inside folder pkg1
PkgMain.java
Java
				import pkg1.PkgClass;

public class PkgMain 
{
    public static void main(String[] args) 
	{
        PkgClass obj=new PkgClass();
		obj.show();
    }
}
			
Compile this file which will automatically compile class inside package pkg1. After that run this class.
Output
Question 2
Define a package named myInstitute include class named as department with one method to display the staff of that department. Develop a program to import this package in a java application and call the method defined in the package.
Department.java
Java
				package myInstitute;

public class Department 
{
    public void displayStaff() 
	{
        System.out.println("Staff of the department:");
        System.out.println("HOD: ABC");
        System.out.println("Lecturer: PQR");
        System.out.println("Lab Assistant: XYZ");
    }
}
			
Save this file as Department.java inside folder myInstitute.
PackageDemo.java
Java
				import myInstitute.Department;

public class PackageDemo 
{
    public static void main(String[] args) 
	{
        Department cs = new Department();
        cs.displayStaff();
    }
}
			
Compile this file which will automatically compile class inside package myInstitute. After that run this class.
Output
Question 3
Develop a program which consists of the package named let_me_calculate with a class named Calculator and a method named add to add two integer numbers. Import let_me_calculate package in another program (class named Demo) to add two numbers.
Calculator.java
Java
				package let_me_calculate;

public class Calculator 
{
    public void add(int a, int b) 
	{
        int sum = a + b;
		System.out.println("Addition is :"+sum);
    }
}
			
Save this file as Calculator.java inside folder let_me_calculate.
Demo.java
Java
				import let_me_calculate.Calculator;

public class Demo 
{
    public static void main(String[] args) 
	{
        Calculator c = new Calculator();
        c.add(20, 30);
    }
}
			
Compile this file which will automatically compile class inside package let_me_calculate. After that run this class.
Output

Leave a Comment

Your email address will not be published. Required fields are marked *