Write an object oriented program in Java to find area of circle.
import [Link];
class Circle{
double radius;
Circle(double radius){
[Link] = radius;
}
double area(){
return [Link] * (radius * radius);
}
}
public class Demo {
public static void main(String args[]){
Scanner s = new Scanner([Link]);
[Link]("Enter the radius: ");
double rad = [Link]();
Circle a = new Circle(rad);
[Link]("Area of circle is: " + [Link]());
}
}
Write a program in Java that reads line of text from keyboard and write to file. Also read the
content of the same file and display on monitor.
import [Link].*;
import [Link];
import [Link];
import [Link];
public class demo{
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
[Link]("Enter a line of text: ");
String text = [Link]();
try{
File file = new File("[Link]");
if([Link]()){
[Link]("File " + [Link]() + " is created successfully");
// writing the text in the file
FileWriter fwrite = new FileWriter("[Link]");
[Link](text);
[Link]();
[Link]("Text is written successfully in the file.");
// reading the text from the file
Scanner dataReader = new Scanner(file);
String fileData = [Link]();
[Link]("The file contains the following text: ");
[Link](fileData);
[Link]();
} else {
[Link]("File already exists.");
}
} catch(IOException exception){
[Link]("An unexpected error has occurred.");
}
[Link]();
}
}
How is thread is created? Make a thread using runnable interface to display number from 1 to 20;
each number should be displayed in the interval of 2 seconds.
class Demo implements Runnable{
public void run(){
[Link]("Thread is running ...");
for(int i = 1; i < 20; i++){
try{
[Link](2000);
} catch(InterruptedException e){
[Link](e);
}
[Link](i);
}
}
public static void main(String args[]){
Demo demo = new Demo();
Thread thread = new Thread(demo);
[Link]();
}
}
What is the difference between error and an exception?
Exception Vs. Error in Java
The general meaning of exception is a deliberate act of omission while the meaning of error is an action
that is inaccurate or incorrect. In Java, Exception, and Error both are subclasses of
the Java Throwable class that belongs to [Link] package. But there exist some significant differences
between them. So, in this section, we are going to discuss the key differences between exception and
error. Before moving ahead in this section let's have a look at the hierarchy of the Java Throwable class.
Exception
The term exception is shorthand for the phrase exception event. It is an event that occurs during the
execution of the program and interrupts the normal flow of program instructions. These are the errors that
occur at compile time and run time. It occurs in the code written by the developers. It can be recovered by
using the try-catch block and throws keyword. There are two types of exceptions
i.e. checked and unchecked.
There are some important points that should be kept in mind while dealing with the exception:
o When an error is detected, an exception is thrown.
o Any exception that is thrown must be caught by the exception handler.
o If the programmer has forgotten to provide an exception handler, the exception will be caught by the
catch-all exception handler provided by the system.
o Exception may be rethrown if exception handler is failure to handle it.
Advantages of Exceptions
o It separates error handling code from regular code.
o It has the ability to propagate error reporting up the call stack of methods.
o The grouping or categorizing of exceptions is a natural outcome of the class hierarchy.
Let's understand the exception through a Java program.
[Link]
import [Link];
public class ExcptionExample{
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
[Link]("You have entered: "+number);
}
}
Let's run the above program and enter a float value deliberately to generate an exception.
It shows the InputMismatchExaception. Because the program accepts an integer value. We observe that
the next statement is skipped and the program is terminated.
Error
Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It
indicates a serious problem. It occurs at run time. These are always unchecked. An example of errors
is OutOfMemoryError, LinkageError, AssertionError, etc. are the subclasses of the Error class.
Let's understand the error through a Java program.
[Link]
public class ErrorExample{
public static void main(String args[]){
//method calling
recursiveDemo(10);
}
public static void recursiveDemo(int i){
while(i!=0){
//increments the variable i by 1
i=i+1;
//recursive called method
recursiveDemo(i);
}
}
}
Output:
We observe that on running the program, we get the StackOverflowError, not an exception.
Let's discuss the key differences between exception and error.
In Java, Error, and Exception both are subclasses of the Java Throwable class that belongs to [Link]
package.
Basis of Exception Error
Comparison
Recoverabl Exception can be recovered by using the try-catch
e/ block. An error cannot be recovered.
Irrecoverab
le
Type It can be classified into two categories i.e. checked All errors in Java are unchecked.
and unchecked.
Occurrence It occurs at compile time or run time. It occurs at run time.
Package It belongs to [Link] package. It belongs to [Link]
package.
Known or Only checked exceptions are known to the compiler. Errors will not be known to the
unknown compiler.
Causes It is mainly caused by the application itself. It is mostly caused by the
environment in which the
application is running.
Example Checked Exceptions: SQLException, IOException [Link],
Unchecked [Link]
Exceptions: ArrayIndexOutOfBoundException,
NullPointerException, ArithmaticException
What are the swing components? Create Swing application that receive a number through a
JTextFields and display the squre of numbers in a JTextField when the SQUARE button is pressed.
import [Link].*;
import [Link].*;
public class Square implements ActionListener{
JTextField t1, t2;
JButton b;
Square(){
JFrame f = new JFrame("Find Square");
t1 = new JTextField("");
[Link](50, 100, 200, 30);
t2 = new JTextField("");
[Link](false);
[Link](50, 150, 200, 30);
JButton b = new JButton("Calculate");
[Link](50, 200, 200, 30);
[Link](this);
[Link](t1);
[Link](t2);
[Link](b);
[Link](400, 400);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e){
String s = [Link]();
int num = [Link](s);
int result = num * num;
[Link]([Link](result));
}
public static void main(String args[]){
new Square();
}
}
How an image can be loaded in applet? Give example.
Develop a java code to implement the interface concept for finding the sum and average of given
N number.
import [Link];
interface N{
void findSum();
void findAverage();
}
public class Demo implements N{
float sum = 0;
float average = 0;
float nums[];
Demo(float[] nums){
[Link] = nums;
}
public void findSum(){
for(float num: nums){
sum += num;
}
[Link]("The sum of entered nums are: " + sum);
}
public void findAverage(){
average = sum / [Link];
[Link]("The average of entered nums are: " + average);
}
public static void main(String args[]){
int userInput = 0;
float inputs[];
Scanner obj = new Scanner([Link]);
[Link]("How many numbers do you want to enter?");
userInput = [Link]();
inputs = new float[userInput];
[Link]("Enter %d numbers: ", userInput);
for(int i = 0; i < [Link]; i++){
inputs[i] = [Link]();
}
Demo d = new Demo(inputs);
[Link]();
[Link]();
}
}
Write a program using components to add and subtract two numbers.
import [Link].*;
import [Link].*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
[Link](50,50,150,20);
tf2=new JTextField();
[Link](50,100,150,20);
tf3=new JTextField();
[Link](50,150,150,20);
[Link](false);
b1=new JButton("+");
[Link](50,200,50,50);
b2=new JButton("-");
[Link](120,200,50,50);
[Link](this);
[Link](this);
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
[Link](300,300);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e) {
String s1=[Link]();
String s2=[Link]();
int a=[Link](s1);
int b=[Link](s2);
int c=0;
if([Link]()==b1){
c=a+b;
}else if([Link]()==b2){
c=a-b;
}
String result=[Link](c);
[Link](result);
}
public static void main(String[] args) {
new TextFieldExample();
} }
Write a program to create two threads in Java.
class MyThread1 extends Thread{
// run() method which is called as soon as thread is started
public void run(){
[Link]("Thread 1 is running");
}
}
class MyThread2 extends Thread{
public void run(){
[Link]("Thread 2 is running");
}
}
public class Demo{
public static void main(String args[]){
MyThread1 obj1 = new MyThread1();
MyThread2 obj2 = new MyThread2();
// This thread will transcend from runnable to run
// as start() method will look for run() and execute
// it
[Link]();
// This thread will also transcend from runnable to
// run as start() method will look for run() and
// execute it
[Link]();
}
}
Discuss border layout with suitable example.
Java BorderLayout - The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: [Link]
import [Link].*;
import [Link].*;
public class Border
{
JFrame f;
Border(){
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
[Link](b1, [Link]); // b1 will be placed in the North Direction
[Link](b2, [Link]); // b2 will be placed in the South Direction
[Link](b3, [Link]); // b2 will be placed in the East Direction
[Link](b4, [Link]); // b2 will be placed in the West Direction
[Link](b5, [Link]); // b2 will be placed in the Center
[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
Write a GUI program to calculate the sum and difference of two numbers input by the users as
shown as below window.
import [Link].*;
import [Link].*;
public class Calc implements ActionListener{
JTextField tf1, tf2, tf3;
JButton b1, b2;
JLabel l1, l2, l3, title;
Calc(){
JFrame f = new JFrame("Java Program Calculator");
title = new JLabel("Calculator");
[Link](50, 10, 100, 30);
tf1 = new JTextField();
[Link](150, 50, 150, 30);
l1 = new JLabel("First Number:");
[Link](50, 50, 100, 30);
tf2 = new JTextField();
[Link](150, 100, 150, 30);
l2 = new JLabel("Second Number:");
[Link](50, 100, 100, 30);
tf3 = new JTextField();
[Link](150, 150, 150, 30);
[Link](false);
l3 = new JLabel("Result: ");
[Link](50, 150, 100, 30);
b1 = new JButton("ADD");
[Link](80, 200, 100, 30);
b2 = new JButton("SUB");
[Link](200, 200, 100, 30);
[Link](this);
[Link](this);
[Link](title); [Link](tf1); [Link](tf2); [Link](tf3); [Link](l1); [Link](l2); [Link](l3);
[Link](b1); [Link](b2);
[Link](500, 500);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e){
String s1 = [Link]();
String s2 = [Link]();
int a = [Link](s1);
int b = [Link](s2);
int c = 0;
if([Link]() == b1){
c = a + b;
} else if([Link]() == b2){
c = a - b;
}
String result = [Link](c);
[Link](result);
}
public static void main(String[] args){
new Calc();
}
}
Describe the function of File class? Create a DataInputStream for a file name “[Link]”
and store “I am student of BIT VI semester” in that file.
What is swing? List out the features of swing. Create a swing application whose snapshot is as
shown in figure below.
You program should add integer numbers entered in first and second text field and display sum in
last field on clicking ok button.
import [Link].*;
import [Link].*;
public class Calc implements ActionListener{
JTextField tf1, tf2, tf3;
JButton b1, b2;
JLabel l1, l2, l3;
Calc(){
JFrame f = new JFrame("Java");
tf1 = new JTextField();
[Link](150, 50, 150, 30);
l1 = new JLabel("N1:");
[Link](50, 50, 100, 30);
tf2 = new JTextField();
[Link](150, 100, 150, 30);
l2 = new JLabel("N2:");
[Link](50, 100, 100, 30);
tf3 = new JTextField();
[Link](150, 150, 150, 30);
[Link](false);
l3 = new JLabel("Result: ");
[Link](50, 150, 100, 30);
b1 = new JButton("OK");
[Link](80, 200, 100, 30);
b2 = new JButton("Exit");
[Link](200, 200, 100, 30);
[Link](this);
[Link](this);
[Link](tf1); [Link](tf2); [Link](tf3); [Link](l1); [Link](l2); [Link](l3); [Link](b1);
[Link](b2);
[Link](500, 500);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e){
String s1 = [Link]();
String s2 = [Link]();
int a = [Link](s1);
int b = [Link](s2);
int c = 0;
if([Link]() == b1){
c = a + b;
} else if([Link]() == b2){
[Link](0);
}
String result = [Link](c);
[Link](result);
}
public static void main(String[] args){
new Calc();
}
}
How does interface support polymorphism?
Java interfaces are a way to achieve polymorphism. Polymorphism is a concept that takes some practice and
thought to master. Basically, polymorphism means that an instance of an class (an object) can be used as if it
were of different types. Here, a type means either a class or an interface.
Interfaces formalize polymorphism. Interfaces allow us to define polymorphism in a declarative way, unrelated
to implementation. Two elements are polymorphic with respect to a set of behaviors if they realize the same
interfaces. You always heard that polymorphism was this big benefit of object orientation, but without
interfaces there was no way to enforce it, verify it, or even express it, except in informal ways, or language-
specific ways. Formalization of interfaces strips away the mystery, and gives us a good way to describe, in
precise terms, what polymorphism was trying to do all along. Interfaces are testable, verifiable, and precise.
Interfaces are the key to the "plug-and-play" ability of an architecture. Classes that realize the same interface
may be substituted for one another in the system, thereby supporting the changing of implementations
without affecting clients.
interface Stack
{
public void push ( char item ); // inserts an item at the top
public char pop (); // removes an item from the top
public char peek (); // returns an item from the top
// without removing
public boolean isEmpty (); // determines if the Stack is empty
public boolean isFull (); // determines if the Stack is full
public String toString (); // returns a String representation of
// the Stack
}
class StackArray implements Stack
{
private char stackArray[]; // array that implements the Stack
private int top; // index of the top element in the Stack
// Constructor
public StackArray ( int n )
{
stackArray = new char [ n ];
top = -1;
}
// Implementation of the methods in the interface
public void push ( char item )
{ stackArray [ ++top ] = item; }
public char pop ()
{ return stackArray [ top-- ]; }
public char peek ()
{ return stackArray [ top ]; }
public boolean isEmpty ()
{ return ( top < 0 ); }
public boolean isFull ()
{ return ( top == [Link] - 1 ); }
public String toString ()
{ StringBuffer aBuffer = new StringBuffer();
for ( int i = top; i >= 0; i-- )
{
[Link] ( stackArray [ i ] + " " );
}
return [Link]();
}
}
public class TestStack
{
public static void main ( String args [] )
{
Stack theStack = new StackArray ( 10 );
char ch = ' ';
if ( ![Link]() )
[Link] ( 'a' );
if ( ![Link]() )
[Link] ( 'b' );
if ( ![Link]() )
[Link] ( 'c' );
if ( ![Link]() )
ch = [Link] ();
[Link] ( "The item on top of the stack is " + ch );
if ( ![Link]() )
ch = [Link] ();
[Link] ( "The item on top of the stack is " + ch );
[Link] ( [Link]() );
}
}
Real-life Example - The real-world example of interfaces is that we have multiple classes for different levels
of employees working in a particular company and the necessary property of the class is the salary of the
employees and this. We must be implemented in every class and. Also, it is different for every employee here.
The concept of the interface is used. We simply create an interface containing an abstract salary method and
implement it in all the classes and we can easily define different salaries of the employees.
interface Salary{
void insertSalary(int salary);
}
// implementing the salary in the class
class SDE1 implements Salary{
int salary;
public void insertSalary(int salary){
[Link] = salary;
}
void printSalary(){
[Link]([Link]);
}
}
class SDE2 implements Salary{
int salary;
public void insertSalary(int salary){
[Link] = salary;
}
void printSalary(){
[Link]([Link]);
}
}
public class Demo{
public static void main(String args[]){
SDE1 ob1 = new SDE1();
[Link](10000);
[Link]();
SDE2 ob2 = new SDE2();
[Link](20000);
[Link]();
}
}
Explain two ways of creating thread with example.
Thread can be referred to as a lightweight process. Thread uses fewer resources to create and exist in the
process; thread shares process resources. The main thread of Java is the thread that is started when the
program starts. The slave thread is created as a result of the main thread. This is the last thread to complete
execution. A thread can programmatically be created by:
1. Implementing the [Link] interface.
2. Extending the [Link] class.
You can create threads by implementing the runnable interface and overriding the run() method. Then, you
can create a thread object and call the start() method.
Thread Class: The Thread class provides constructors and methods for creating and operating on threads.
The thread extends the Object and implements the Runnable interface.
// start a newly created thread.
// Thread moves from new state to runnable state
// When it gets a chance, executes the target run() method
public void start()
Runnable interface: Any class with instances that are intended to be executed by a thread should
implement the Runnable interface. The Runnable interface has only one method, which is called run().
// Thread action is performed
public void run()
Benefits of creating threads :
When compared to processes, Java Threads are more lightweight; it takes less time and resources to
create a thread.
Threads share the data and code of their parent process.
Thread communication is simpler than process communication.
Context switching between threads is usually cheaper than switching between processes.
Example 1: By using Thread Class
Output: Welcome to GeeksforGeeks.
import [Link].*;
class GFG extends Thread {
public void run()
{
[Link]("Welcome to GeeksforGeeks.");
}
public static void main(String[] args)
{
GFG g = new GFG(); // creating thread
[Link](); // starting thread
}
}
Example 2: By implementing Runnable interface
import [Link].*;
class GFG implements Runnable {
public static void main(String args[])
{
// create an object of Runnable target
GFG gfg = new GFG();
// pass the runnable reference to Thread
Thread t = new Thread(gfg, "gfg");
// start the thread
[Link]();
// get the name of the thread
[Link]([Link]());
}
@Override public void run()
{
[Link]("Inside run method");
}
}
Output
gfg
Inside run method
Create Swing application that receive two numbers through a JTextFields and display the
multiplication of two numbers in a JTextField when the OK button is pressed and when Exit button
is pressed the program will terminate.
import [Link].*;
import [Link].*;
public class Calc implements ActionListener{
JTextField num1tf, num2tf, resulttf;
JButton okBtn, exitBtn;
JLabel num1l, num2l, resultl;
Calc(){
JFrame f = new JFrame();
num1l = new JLabel("Num 1: ");
[Link](50, 50, 100, 30);
num1tf = new JTextField();
[Link](150, 50, 100, 30);
num2l = new JLabel("Num 2: ");
[Link](50, 100, 100, 30);
num2tf = new JTextField();
[Link](150, 100, 100, 30);
resultl = new JLabel("Result: ");
[Link](50, 150, 100, 30);
resulttf = new JTextField();
[Link](150, 150, 100, 30);
[Link](false);
okBtn = new JButton("OK");
[Link](50, 200, 100, 30);
exitBtn = new JButton("Exit");
[Link](180, 200, 100, 30);
[Link](this);
[Link](this);
[Link](num1l); [Link](num2l); [Link](num1tf); [Link](num2tf); [Link](okBtn);
[Link](exitBtn); [Link](resultl); [Link](resulttf);
[Link](400, 400);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e){
String s1 = [Link]();
String s2 = [Link]();
int num1 = [Link](s1);
int num2 = [Link](s2);
int result = 0;
if([Link]() == okBtn){
result = num1 * num2;
} else if([Link]() == exitBtn){
[Link](0);
}
[Link]([Link](result));
}
public static void main(String[] args){
new Calc();
}
}
WAP which will display your name in one thread and your address in another thread in every 500
milliseconds. There should be 1000 iteration.
class Demo extends Thread{
String text;
Demo(String s){
[Link] = s;
}
public void run(){
for(int i = 1; i <= 10; i++){
try{
[Link](1000);
} catch(InterruptedException e){
[Link](e);
}
[Link](text);
}
}
public static void main(String args[]){
Demo thread1 = new Demo("Saroj");
Demo thread2 = new Demo("Kathmandu");
[Link]();
[Link]();
}
}
Difference between overloading and overriding method with example.
S. Method Overloading Method Overriding
N.
1. Method overloading is a compile-time Method overriding is a run-time polymorphism.
polymorphism.
2. It helps to increase the readability of the It is used to grant the specific implementation of
program. the method which is already provided by its parent
class or superclass.
3. It occurs within the class. It is performed in two classes with inheritance
relationships.
4. Method overloading may or may not require Method overriding always needs inheritance.
inheritance.
5. In method overloading, methods must have the In method overriding, methods must have the
same name and different signatures. same name and same signature.
6. In method overloading, the return type can or In method overriding, the return type must be the
cannot be the same, but we just have to change same or co-variant.
the parameter.
Method Overloading: Method Overloading is a Compile time polymorphism. In method overloading, more
than one method shares the same method name with a different signature in the class. In method overloading,
the return type can or cannot be the same, but we have to change the parameter because, in java, we cannot
achieve the method overloading by changing only the return type of the method.
Example of Method Overloading:
import [Link].*;
class MethodOverloadingEx {
static int add(int a, int b){
return a + b;
}
static int add(int a, int b, int c){
return a + b + c;
}
public static void main(String args[]){
[Link]("add() with 2 parameters");
[Link](add(4, 6));
[Link]("add() with 3 parameters");
[Link](add(4, 6, 7));
}
}
Output
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding: Method Overriding is a Run time polymorphism. In method overriding, the derived
class provides the specific implementation of the method that is already provided by the base class or parent
class. In method overriding, the return type must be the same or co-variant (return type may vary in the same
direction as the derived class).
Example of Method Overriding:
import [Link].*;
class Animal {
void eat(){
[Link]("eat() method of base class");
[Link]("eating.");
}
}
class Dog extends Animal {
void eat(){
[Link]("eat() method of derived class");
[Link]("Dog is eating.");
}
}
class MethodOverridingEx {
public static void main(String args[]){
Dog d1 = new Dog();
Animal a1 = new Animal();
[Link]();
[Link]();
Animal animal = new Dog();
// eat() method of animal class is overridden by
// base class eat()
[Link]();
}
}
Output
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.
Explanation: Here, we can see that a method eat() has overridden in the derived class name Dog that is
already provided by the base class name Animal.
When we create the instance of class Dog and call the eat() method, we see that only derived class eat()
method run instead of base class method eat(), and When we create the instance of class Animal and call the
eat() method, we see that only base class eat() method run instead of derived class method eat().
So, it’s clear that in method overriding, the method is bound to the instances on the run time, which is decided
by the JVM. That’s why it is called Run time polymorphism.
Explain the types of package and way of writing it.
A package is a collection of similar types of Java entities such as classes, interfaces, subclasses, exceptions,
errors, and enums. A package can also contain sub-packages.
There are several advantages of using Java Packages, some of them, are as follows:
Make easy searching or locating of classes and interfaces.
Avoid naming conflicts. For example, there can be two classes with the name Student in two packages,
[Link] and [Link]
Implement data encapsulation (or data-hiding).
Provide controlled access: The access specifiers protected and default have access control on package
level. A member declared as protected is accessible by classes within the same package and its
subclasses. A member without any access specifier that is default specifier is accessible only by classes in
the same package.
Reuse the classes contained in the packages of other programs.
Uniquely compare the classes in other packages.
Types of Packages in Java
1. Java API packages or built-in packages - Java provides a large number of classes grouped into different
packages based on a particular functionality.
Examples:
[Link]: It contains classes for primitive types, strings, math functions, threads, and exceptions.
[Link]: It contains classes such as vectors, hash tables, dates, Calendars, etc.
[Link]: It has stream classes for Input/Output.
[Link]: Classes for implementing Graphical User Interface – windows, buttons, menus, etc.
[Link]: Classes for networking
java. Applet: Classes for creating and implementing applets
2. User-defined packages - As the name suggests, these packages are defined by the user. We create a
directory whose name should be the same as the name of the package. Then we create a class inside the
directory.
Creating a Package in Java
To create a package, we choose a package name and to include the classes, interfaces, enumerations, etc,
inside the package, we write the package with its name at the top of every source file.
There can be only one package statement in each type of file. If we do not write class, interfaces, inside any
package, then they will be placed in the current default package.
Example of Java Package
We can create a Java class inside a package using a package keyword.
package [Link]; //package
class Example{
public static void main(String args[]){
[Link]("Welcome to Techvidvan’s Java Tutorial");
}
}
Output: Welcome to Techvidvan’s Java Tutorial
How to Create a Package in Java?
Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. All we need
to do is put related classes into packages. After that, we can simply write an import class from existing
packages and use it in our program. A package is a container of a group of related classes where some classes
are accessible are exposed and others are kept for internal purposes. We can reuse existing classes from the
packages as many times as we need them in our program. Package names and directory structure are closely
related
Ways: There are two types of packages in java:
1. User-defined Package (Create Your Own Package’s)
2. Built-in packages are packages from the java application programming interface that are the packages
from Java API for example such as swing, util, net, io, AWT, lang, javax, etc.
A package is a group of similar types of Classes, Interfaces, and sub-packages. We use Packages in order to
avoid name conflicts.
Syntax: To import a package
import [Link].*;
Example: To import a package
// Java Program to Import a package
// Importing java utility package
import [Link].*;
// Main Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Scanner to take input from the user object
Scanner myObj = new Scanner([Link]);
String userName;
// Display message
// Enter Your Name And Press Enter
[Link]("Enter You Name");
// Reading the integer age entered using
// nextInt() method
userName = [Link]();
// Print and display
[Link]("Your Name IS : " + userName);
}
}
Output
Enter You Name
Your Name IS : 0
Here In The Above Program, ‘[Link]’ package is imported and run for a simple program. These are called
as Inbuilt Packages.
Now in order to create a package in java follow the certain steps as described below:
1. First We Should Choose A Name For The Package We Are Going To Create And Include. The package
command In The first line in the java program source code.
2. Further inclusion of classes, interfaces, annotation types, etc that is required in the package can be made
in the package. For example, the below single statement creates a package name called “FirstPackage”.
Syntax: To declare the name of the package to be created. The package statement simply defines in which
package the classes defined belong.
package FirstPackage;
Implementation: To Create a Class Inside A Package
1. First Declare The Package Name As The First Statement Of Our Program.
2. Then We Can Include A Class As A Part Of The Package.
Example 1:
// Name of package to be created
package FirstPackage;
// Class in which the above created package belong to
class Welcome {
// main driver method
public static void main(String[] args)
{
// Print statement for the successful
// compilation and execution of the program
[Link]("This Is The First Program Geeks For Geeks..");
}
}
So Inorder to generate the above-desired output first do use the commands as specified use the following
specified commands
Procedure:
1. To generate the output from the above program
Command: javac [Link]
2. The Above Command Will Give Us [Link] File.
Command: javac -d . [Link]
3. So This Command Will Create a New Folder Called FirstPackage.
Command: java [Link]
Output: The Above Will Give The Final Output Of The Example Program
This Is The Output Of The Above Program
Example 2:
// Name of package to be created
package data;
// Class to which the above package belongs
public class Demo {
// Member functions of the class- 'Demo'
// Method 1 - To show()
public void show()
{
// Print message
[Link]("Hi Everyone");
}
// Method 2 - To show()
public void view()
{
// Print message
[Link]("Hello");
}
}
Again, in order to generate the above-desired output first do use the commands as specified use the following
specified commands
Procedure:
1. To generate the output from the above program
Command: javac [Link]
2. This Command Will Give Us a Class File
Command: javac -d . [Link]
3. So This Command Will Create a New Folder Called data.
Note: In data [Link] & [Link] File should be present
Example 3: Data will be tried to be accessed now from another program
// Name of the package
import data.*;
// Class to which the package belongs
class ncj {
// main driver method
public static void main(String arg[])
{
// Creating an object of Demo class
Demo d = new Demo();
// Calling the functions show() and view()
// using the object of Demo class
[Link]();
[Link]();
}
}
Again the following commands will be used in order to generate the output as first a file ill be created
‘[Link]’ outside the data directory.
Command: javac [Link]
The Above Command Will Give us a class file that is non-runnable so we do need a command further to make
it an executable run file.
Command: java ncj
// To Run This File
Output: Generated on the terminal after the above command Is executed
Hi Everyone
Hello