Skip to content

How can I create .JAR to Do a specific task , then use this JAR in another project?

e.g : i have a simple code that take an array list of numbers and computes Sum. I am created a .JAR of this code. now my question is how can I import this JAR in another project and pass array list to it , and JAR give me the result to reuse it ??



This is an example 1- in a directory commycompanymyproject create

package com.mycompany.myproject;

import java.util.*;

public interface Task{

  public int sum(List<Integer> list);


2- in a directory commycompanymyprojectsupport create


import java.util.*;
import com.mycompany.myproject.Task;

public class MyTask implements Task{

 public int sum(List<Integer> list){
  int variable = 0;
  for(int i: list){
       variable += i;
  return variable;


3- compile both .java with command $javac com/mycompany/myproject/ and command $javac com/mycompany/myproject/support/

4- create .jar file with command $jar -cvf task.jar com/mycompany/myproject/Task.class com/mycompany/myproject/support/MyTask.class (I decided to put “task” as name of my .jar file)

At this point you have created you .JAR and you can use it in another project. Let’s see how to do it.

5- take your task.jar file and put it where you have defined your CLASSPATH System Variable

6- create in any directory.

import java.util.*;
import com.mycompany.myproject.*;

public class Main{

  public static void main(String arg[]){
  //create the implementation you want  
  Task task = new MyTask();
  LinkedList<Integer> list = new LinkedList<Integer>();
  int result = task.sum(list);


7- comnpile with $javac

8- take Main.class(result of compilation of and put it where you have defined your CLASSPATH System Variable.

9- go to your CLASSPATH directory and execute command $java Main

User contributions licensed under: CC BY-SA
6 People found this is helpful