We can go to intellij and create a new java project. Choose a location where we want to save our project.
Then we go to our project in intellij and create a new package named com.mypackage.myexamples under src folder and under that package we create a class named Serial and in that we write code like this.
package com,nypackage.myexamples;
public class Serial {
public static long nSum(int n){
return (n*(n+1))/2;
}
public static long factorial(int n){
if(n==0){
return 1;
}
long fact = 1;
for(int i=1;i<=n;i++){
fact *=i;
}
return fact;
}
Then we go to File->Project Structure->Artifacts ->click + then -> jars ->from modules with dependencies. Then since we don’t have any main file for our project so we don’t choose any and so don’t browse and choose anything and then press ok . we will then get the location where our jar file will be created.
C:\myprojects\packagetesting1\out\artifacts\packagetesting1_jar
Then we click apply and then ok.
We then go to build -> build artifacts -> build to build everything
Then we go to this folder to make sure our artifacts are indeed generated.
C:\web-tests\packagetesting1\out\artifacts
Over here we have a folder named packagetesting1_jar and in that we have a jar file which we created and which we can import in other projects.
We then go intellij and create a new java project named SerialTesting
Then after the project is created we go to File ->Project Structure ->Libraries ->click the + sign . Then click java then go to the same artifacts folder(C:\myprojects\packagetesting1\out\artifacts) as above and choose the jar file.
Then if we go to the external libraries of our project we see that the jar file with entire package packagetesting1 is added.
Then in our project in src folder we create a main class called Main .
Then in main class we can import the Serial
import com.harsimran.myexamples.Serial;
And then in main class we can use all static methods of this Serial class like this Serial.nSum(i),Serial.factorial(i) etc
Complete example is below
public class Main {
public static void main(String[]args){
Serial s = new Serial();
for(int i=0;i<=10;i++){
System.out.println(Serial.nSum(i));
}
System.out.println("********************************************************************");
for(int i=0;i<=10;i++){
System.out.println(Serial.factorial(i));
}
}
}