User Defined Packages In Java
This post will demonstrate the creation of user defined packages and use them. Basically we will use a Math class and an IO class. These two classes will be included in a package sample. Math class will perform all basic add, mul, sub, div operations. On the other side, the IO class will handle with input and output operations.
The Code Section
Firstly creating the Math.java file
Secondly creating the IO.java file
Finally creating the TestPack.java to import and test
Note:
To compile the package classes i.e. Math and IO you need to type the bellow code if using the console to compile.
Final Words:
Hope you enjoyed reading so Far.
Liked this post, please share it !
Got any comments, Drop them !
Screenshot[Final Output]
The Code Section
Firstly creating the Math.java file
package sample; public class Math { public int add(int a, int b) { return a+b; } public int mul(int a, int b) { return a*b; } public int sub(int a, int b) { return a-b; } public int div(int a, int b) { return a/b; } }
Secondly creating the IO.java file
package sample; import java.util.Scanner; public class IO { Scanner s; public IO() { s= new Scanner(System.in); } public int inputInt() { System.out.print("Enter: "); return s.nextInt(); } public String inputStr() { System.out.print("Enter: "); return s.next(); } public void print(int a) { System.out.println(a); } public void print(String a) { System.out.println(a); } }
Finally creating the TestPack.java to import and test
import sample.IO; import sample.Math; public class TestPack { public static void main(String as[]) { IO io=new IO(); Math m=new Math(); String s; int a,b; a=io.inputInt(); b=io.inputInt(); s=io.inputStr(); io.print("Add is "+m.add(a,b)); io.print("Mul is "+m.mul(a,b)); io.print("Sub is "+m.sub(a,b)); io.print("Div is "+m.div(a,b)); io.print("The String Entered is : "+s); } }
Note:
To compile the package classes i.e. Math and IO you need to type the bellow code if using the console to compile.
$ javac -d <filename>.javaFor this program, replace filename with Math and IO.
Final Words:
Hope you enjoyed reading so Far.
Liked this post, please share it !
Got any comments, Drop them !
Comments
Post a Comment