Java Packages & API-10 example

--help cse
5 min readMar 22, 2022

Java Packages & API mastery through program

Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:

  • Built-in Packages (packages from the Java API)
  • User-defined Packages (create your own packages)

The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package

Syntax

import package.name.Class; // Import a single class

import package.name.*; // Import the whole package

We will see example so it will clear.

Import a Class

If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package.

Program 1:Simple java.util.scanner program of taking input.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a complete line:

CODE:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println(“Enter username :”);

String userName = myObj.nextLine();

System.out.println(“Username is: “ + userName);

}

}

OUTPUT:

Enter username :

sachin

Username is: sachin

Note*:This is possible because java.util.scanner we are able to take input.

Program 2: To import a whole package, end the sentence with an asterisk sign (*). For.eg. java.util.*

There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package:

CODE:

import java.util.*; // import the java.util package

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

String userName;

// Enter username and press Enter

System.out.println(“Enter username”);

userName = myObj.nextLine();

System.out.println(“Username is: “ + userName);

}

}

OUTPUT:

Enter username :

sachin

Username is: sachin

Note *:This is same example only we have (*) sign so we can use all method inside in package availabl e easily.

User-defined Packages

To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:

Program 3:Creating package user defined.

CODE:

package MyPack;

public class mypackageclass {

public static void main(String[] args) {

System.out.println(“This is my package!”);

}

}

OUTPUT:

This is my package!

Note *:This package you can use at next program by using package MyPack.

Program 4:Used you have created in your program.

CODE:

Filename :: mypackageclass.java

package MyPack;

public class mypackageclass {

public void msg(){System.out.println(“Hello”);}

}

Filename::B.java

package MyPack;

//save by B.java

class B{

public static void main(String args[]){

mypackageclass obj = new mypackageclass();

obj.msg();

}

}

OUTPUT:

Hello

Note*:If I run B.java file it invoked method msg inside Mypack package and then it will print Hello

Program 5:Use one user defined package into pther classs package.

Here,I have Created tow package Mypackage and pack and am accssing Mypack class using MyPack.A in pack B class.

CODE:

FileName::A.java

package MyPack;

public class A{

public void msg(){System.out.println(“Hello”);}

}

FileName::B.java

//save by B.java

package pack;

import MyPack.A;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

}

}

OUTPUT:

Hello

Program 6:Create Addtion function in one [akage and use in second package.

CODE:

Filename :A.java

package MyPack;

public class A{

public void add(int a, int b) {

// TODO Auto-generated method stub

int d=a+b;

System.out.printf(“Addition :”);

System.out.println(d);

}

}

//save by B.java

package pack;

import java.util.Scanner;

import MyPack.A;

class B{

public static void main(String args[]){

A obj = new A();

Scanner sc= new Scanner(System.in); //System.in is a standard input stream

System.out.print(“Enter first number- “);

int a= sc.nextInt();

System.out.print(“Enter second number- “);

int b= sc.nextInt();

obj.add(a,b);

}

}

OUTPUT:

Enter first number- 5

Enter second number- 6

Addition :11

Note*:This is flexibility of java program

Program 7:use of java.util.*; for taking input of string.

CODE:

package MyPack;

import java.util.*;

class string

{

public static void main(String[] args)

{

Scanner sc= new Scanner(System.in); //System.in is a standard input stream

System.out.print(“Enter a string: “);

String str= sc.nextLine(); //reads string

System.out.print(“You have entered: “+str);

}

}

OUTPUT:

Enter a string: Cristiano ronaldo is best footballer

You have entered: Cristiano ronaldo is best footballer

Most Usefull Packages

java.lang: It contains classes for primitive types, strings, math functions, threads, and exceptions.

java.util: It contains classes such as vectors, hash tables, dates, Calendars, etc.

java.io: It has stream classes for Input/Output.

java.awt: Classes for implementing Graphical User Interface — windows, buttons, menus, etc.

java.net: Classes for networking

java. Applet: Classes for creating and implementing applets

Program 8: java.lang.Object example

Flexible nature of java.lang.Object

We all love the mechanism of python, where we don’t have to bother about data types of the variables (don’t we!)

Interestingly we have one class in Java too, which is pretty similar !

Yes, you guessed it right! It’s java.lang.Object

CODE:

package MyPack;

import java.lang.*;

public class CR

{

public static void main(String arr[])

{

Object y;

y = ‘A’;

System.out.println(y.getClass().getName());

y = 1;

System.out.println(y.getClass().getName());

y = “Hi”;

System.out.println(y.getClass().getName());

y = 1.222;

System.out.println(y.getClass().getName());

y = false;

System.out.println(y.getClass().getName());

}

}

OUTPUT:

java.lang.Character

java.lang.Integer

java.lang.String

java.lang.Double

java.lang.Boolean

Program 9:Java.io.* example..

CODE:

// Java code to illustrate print()

import java.io.*;

class Demo_print {

public static void main(String[] args)

{

// using print()

// all are printed in the

// same line

System.out.print(“GfG! “);

System.out.print(“GfG! “);

System.out.print(“GfG! “);

}

}

OUTPUT:

GfG! GfG! GfG!

Note *:println(): This method in Java is also used to display a text on the console. It prints the text on the console and the cursor moves to the start of the next line at the console. The next printing takes place from the next line

Program 10:Use jva.net package through in newtworking example.

CODE:

package MyPack;

//URLDemo.java

import java.net.*;

public class URLDemo{

public static void main(String[] args){

try{

URL url=new URL(“http://www.sinplesnippets.com/java-tutorial");

System.out.println(“Protocol: “+url.getProtocol());

System.out.println(“Host Name: “+url.getHost());

System.out.println(“Port Number: “+url.getPort());

System.out.println(“File Name: “+url.getFile());

}catch(Exception e){System.out.println(e);}

}

}

OUTPUT:

Protocol: http

Host Name: www.simplesnippets.com

Port Number: -1

File Name: /java-tutorial

This way you can use in networking java.net package.

Thank you java.awt and java.applet we wiil see in upcomming sheet it is more popular.

Till then keep practising all class method inside all main packages.

--

--