Skip to main content

ProwessApps

Learn · Practice · Excel

Create a package by name logicgate which consist of classes for AND, OR, NOT gate, and all classes has method with signature int doOperation(arg_list), import this package in to java source file and simulate the behavior of all gates.

Java Code Example — Package Programs

ADVERTISEMENT

Create a package by name logicgate which consist of classes for AND, OR, NOT gate, and all classes has method with signature int doOperation(arg_list), import this package in to java source file and simulate the behavior of all gates.

Objective

Write a Java program to simulate Logic Gates by creating a custom package and importing it into another file.

Algorithm / Approach

  1. Create three distinct classes: Add, Not, and Or.
  2. At the very top of each of these three files, declare the package: package com.logigate;.
  3. Inside each class, write a method that performs the respective bitwise operation (&, ~, |) and returns the result.
  4. Create a main testing class in a separate package: package com.alok;.
  5. Import the logic gate package using: import com.logigate.*;.
  6. In the main method, instantiate the gate classes and call their methods.
Add.java
//File 1 : Add.java
package com.logigate;
public class Add {
 public int add(int a, int b){
  return a&b;
 }
}

//File 2 : Not.java
package com.logigate;
public class Not {
 public int not(int a){
  return ~a;
 }
}

//File 3 : Or.java
package com.logigate;
public class Or {
 public int or(int a, int b) {
  return a|b;
 }
}

// File 4: Test.java
package com.alok;
import com.logigate.*;
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Add ar = new Add();
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Num1: ");
  int num1 = s.nextInt();
  System.out.print("Enter Num2: ");
  int num2 = s.nextInt();
  int x = ar.add(num1,num2);
  System.out.println("Add Result= "+x);
  Or o = new Or();
  int y = o.or(num1,num2);
  System.out.println("Or Result= "+y);
  Not n = new Not();
  int z = n.not(num1);
  System.out.print("Not Result= "+z);
 }
}

Expected Output

Enter Num1: 5
Enter Num2: 6
Add Result= 4
Or Result= 7
Not Result= -6

Explanation of the Program

  • A Java package is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. It helps organize code and prevent naming conflicts.
  • In this program, we group three related classes into a package called com.logigate.
  • Because the Test class belongs to a completely different package (com.alok), it cannot see the gate classes natively. We must explicitly pull them in using the import statement.
  • Note: For this program to compile correctly in a real terminal, the directory structure must perfectly match the package names (e.g., com/logigate/Add.java).

Complexity

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