Welcome to Java Examples

Take a cup of tea and Let's Start programming

Create package



create folder and gave it your package name...

package jaimin; /** * * @author Jaimin Shah */ public class package_example { //create your own method... 
//note:- make all method public..
//here i'm creating the method to show package created.. public void show() { System.out.println("Package created"); } //save this file in your package folder and compile this file }





now create second file in which you want to use your package

import jaimin.package_example; /** * * @author Jaimin Shah */ class package_demo extends package_example { public static void main(String [] args) { //create object of package_example class package_example j = new package_example(); //call method j.show(); } }
output
package created

FileOutputStream in java

FileOutputStream  in java


import java.io.*; class fileoutputstrm { public static void main(String[] args) throws Exception { byte data[]="hi... this is a program of fileoutputstream class".getBytes(); //method to write using loop FileOutputStream fileoutputstrm1 = new FileOutputStream("file1.txt"); for(int index_loop=0;index_loop<data.length;index_loop++) { fileoutputstrm1.write(data[index_loop]); } //method to write using write() method FileOutputStream fileoutputstrm2 = new FileOutputStream("file2.txt"); fileoutputstrm2.write(data); //method to write from specific byte to specific point FileOutputStream fileoutputstrm3 = new FileOutputStream("file3.txt"); fileoutputstrm3.write(data,5,15); //close all files fileoutputstrm1.close(); fileoutputstrm2.close(); fileoutputstrm3.close(); } }




















output

it will create 3 .txt file


fileinputstream class

read and skip number of bytes in java using FileInputStream


import java.io.*; class inputstrm { public static void main(String [] args) throws Exception { int size; FileInputStream inputstrm = new FileInputStream("inputstrm.java"); //to get size in bytes System.out.println("available bytes" +(size = inputstrm.available())); //to read first 50 bytes System.out.println("reading 50 bytes"); byte bytearray[] = new byte[50]; if(inputstrm.read(bytearray) !=50) { System.out.println("could not get 50 bytes"); } System.out.println(new String(bytearray,0,50)); //skip 50 bytes System.out.println("skipped 50 bytes"); inputstrm.skip(50); //read after skipping 50 bytes System.out.println("reading 50 bytes"); if(inputstrm.read(bytearray) !=50) { System.out.println("could not get 50 byte"); } System.out.println(new String(bytearray,0,50)); //close file inputstrm.close(); } }





















output


create frame using WindowAdapter, MouseListener, MouseMotionListener...

Write a program to create a frame with exit capabilities.
Handle events for mouse pressed, mouse released, mouse clicked
and mouse dragged by displaying appropriate message describing
the event at the coordinates where the event has taken place..



output

create smiley using thread and different drawing methods of paint



output







create stack using applet and ActionListener interface

Write a complete program to create a frame for providing GUI to implement a stack for storing integer numbers. There are two buttons called PUSH & POP and a text field. Clicking of button PUSH pushes the number entered in the text field onto the stack. The click of button POP pops an element from the stack and displays that in the text field.


import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import java.lang.*;



public class stack extends Applet implements ActionListener
{
int j;

TextField txtData = new TextField("",20);
Button btnPush = new Button("PUSH");
Button btnPop = new Button("POP");
Label lbl1 = new Label("");
Label lbl2 = new Label("");
Label lbl3 = new Label("");
Label lbl4 = new Label("");
Label lbl5 = new Label("");
Label lblError = new Label("hi");
Label lblTop = new Label("<-- br="" top=""> boolean push,pop,txtNull;
String txtValue;

public void init()
{
j=0;

setLayout(null);
add(txtData);
add(btnPush);
add(btnPop);

txtData.setBounds(10,10,200,25);
btnPush.setBounds(220,10,50,25);
btnPop.setBounds(290,10,50,25);



add(lbl1);
add(lbl2);
add(lbl3);
add(lbl4);
add(lbl5);
add(lblError);
add(lblTop);

lbl1.setVisible(false);
lbl2.setVisible(false);
lbl3.setVisible(false);
lbl4.setVisible(false);
lbl5.setVisible(false);
lblError.setVisible(false);
lblTop.setVisible(true);


txtData.setBounds(10,10,50,20);
btnPush.setBounds(70,10,50,20);
btnPop.setBounds(140,10,50,20);
lbl1.setBounds(50,150,50,20);
lbl2.setBounds(50,130,50,20);
lbl3.setBounds(50,110,50,20);
lbl4.setBounds(50,90,50,20);
lbl5.setBounds(50,70,50,20);
lblError.setBounds(50,170,200,20);
lblTop.setBounds(70,150,50,20);



btnPush.addActionListener(this);
btnPop.addActionListener(this);
}

public void paint(Graphics g)
{
if(txtNull)
{
lblError.setVisible(true);
lblError.setText("enter integer values");
j--;
txtNull=false;
}

else
{
if(j==-1)
{
lblError.setVisible(true);

if(pop)
{
lblError.setText("Stack Underflow");
}
j++;
}


if(j==0)
{
lbl1.setVisible(false);
lbl2.setVisible(false);
lbl3.setVisible(false);
lbl4.setVisible(false);
lbl5.setVisible(false);
lblError.setVisible(false);
lblTop.setBounds(90,170,50,20);
}
if(j==1)
{
lbl1.setVisible(true);
lbl2.setVisible(false);
lbl3.setVisible(false);
lbl4.setVisible(false);
lbl5.setVisible(false);
lblError.setVisible(false);
lblTop.setBounds(100,150,50,20);
}
if(j==2)
{
lbl1.setVisible(true);
lbl2.setVisible(true);
lbl3.setVisible(false);
lbl4.setVisible(false);
lbl5.setVisible(false);
lblError.setVisible(false);
lblTop.setBounds(100,130,50,20);
}
if(j==3)
{
lbl1.setVisible(true);
lbl2.setVisible(true);
lbl3.setVisible(true);
lbl4.setVisible(false);
lbl5.setVisible(false);
lblError.setVisible(false);
lblTop.setBounds(100,110,50,20);
}
if(j==4)
{
lbl1.setVisible(true);
lbl2.setVisible(true);
lbl3.setVisible(true);
lbl4.setVisible(true);
lbl5.setVisible(false);
lblError.setVisible(false);
lblTop.setBounds(100,90,50,20);
}
if(j==5)
{
lbl1.setVisible(true);
lbl2.setVisible(true);
lbl3.setVisible(true);
lbl4.setVisible(true);
lbl5.setVisible(true);
lblError.setVisible(false);
lblTop.setBounds(100,70,50,20);
}

if(j==6)
{
lblError.setVisible(true);
if(push)
{
lblError.setText("Stack Overflow");
}

j--;
}
}


}

public void actionPerformed(ActionEvent ae)
{

if(ae.getSource() == btnPush)
{

push = true;
pop = false;
txtValue = txtData.getText();

j++;

if(txtValue.equals(""))
{
txtNull = true;
repaint();

}

else
{
try
{
int intValue =Integer.parseInt(txtValue);
}
catch(NumberFormatException nfe)
{
txtNull = true;
repaint();
}
}

if(j==6)
{
repaint();
}
else
{

if(j==1)
{
lbl1.setText(txtData.getText());
}
if(j==2)
{
lbl2.setText(txtData.getText());
}
if(j==3)
{
lbl3.setText(txtData.getText());
}
if(j==4)
{
lbl4.setText(txtData.getText());
}
if(j==5)
{
lbl5.setText(txtData.getText());
}
repaint();
}
}

if(ae.getSource() == btnPop)
{
if(j==0)
{
lblError.setVisible(true);
lblError.setText("Stack Underflow");
}
else
{
pop = true;
push = false;


j--;
repaint();
}
}


}

}

output

interface inheritance


The Transport interface declares a deliver() method. The abstract class Animal is the super class of
the Tiger, Camel, Deer and Donkey classes.
The Transport interface is implemented by the Camel and Donkey classes. Write a test program that initialize an array of four Animal objects. If the object implements the Transport interface, the deliver() method is invoked.
interface Transport { void deliver(); } abstract class Animal { abstract void disp(); } class Tiger extends Animal { void disp() { System.out.println("Animal --> Tiger\n"); } } class Camel extends Animal implements Transport { void disp() { System.out.println("Animal --> Camel\n"); } Camel() { disp(); deliver(); } public void deliver() { System.out.println("Camel is Delivered...\n"); } } class Deer extends Animal { void disp() { System.out.println("Animal --> Deer\n"); } } class Donkey extends Animal implements Transport { void disp() { System.out.println("Animal --> Donkey \n"); } Donkey() { disp(); deliver(); } public void deliver() { System.out.println("Donkey is on the way...\n"); } } class Animal1 { public static void main(String [] args) { Tiger tig = new Tiger(); Camel cam = new Camel(); Deer dee = new Deer(); Donkey don = new Donkey(); tig.disp(); dee.disp(); } }



output



abstract class

Describe abstract class called Shape which has three subclasses say Triangle,Rectangle,Circle. Define one method area() in the abstract class and override this area() in these three subclasses to calculate for specific object i.e.area() of Triangle subclass should calculate area of triangle etc. Same for Rectangle and Circle.

import java.lang.Math;

abstract class Shape
{
abstract void area();
double area;
}

class Triangle extends Shape
{
double b=50,h=15;
void area()
{
area = (b*h)/2;
System.out.println("area of Triangle -->"+area);
}
}

class Rectangle extends Shape
{
double w=70,h=20;
void area()
{
area = w*h;
System.out.println("area of Rectangle -->"+area);
}
}

class Circle extends Shape
{
double r=5;
void area()
{
area = Math.PI * r * r;
System.out.println("area of Circle -->"+area);
}
}

class Area
{
public static void main(String [] args)
{
Triangle t= new Triangle();
Rectangle r =new Rectangle();
Circle c =new Circle();

t.area();
r.area();
c.area();
}
}


output


overriding toString() method...

The abstract Vegetable class has three subclasses named Potato, Brinjal and Tomato. Write an application that demonstrates how to establish this class hierarchy. Declare one instance variable of type String that indicates the color of a vegetable. Create and display instances of these objects. Override the toString() method of Object to return a string with the name of the vegetable and its color.

abstract class Vegetable
{
public String color;
}

class Potato extends Vegetable
{
public String toString()
{
color = "Brown -skinned Color";
return "potato -->"+color;
}
}

class Brinjal extends Vegetable
{
public String toString()
{
color = "purple color";
return "Brinjal -->"+this.color;
}
}

class Tomato extends Vegetable
{
public String toString()
{
color="red color";
return "Tomato -->"+color;
}
}

class veg_dis
{
public static void main(String [] args)
{
Potato p = new Potato();
Brinjal b = new Brinjal();
Tomato t = new Tomato();
System.out.println(p);
System.out.println(b);
System.out.println(t);
}
}

output



display book or publication of given author

Declare a class called book having author_name as private data member. Extend book class to have two sub classes called book_publication & paper_publication.
Each of these classes have private member called title. Write a complete program to show usage of dynamic method dispatch (dynamic polymorphism) to display book or paper publications of given author. Use command line arguments for inputting data.


import java.util.Scanner;

class book
{
private String[] author_name = {"jaimin","naitik"};

void display()
{
for(int i=0;i<author_name.length;i++)
{
System.out.println("Author names --> \t"+author_name[i]);
}
}
}

class book_publication extends book
{
private String[][] title = {{"java","c lang","oopc"},{"os","micro processor 8085","microprocessor 8086"}};

void display(int j)
{
System.out.println("Books name of given author are....");
System.out.println("------------------------------------------------");
for(int i=0;i<3;i++)
{
System.out.println(title[j][i]);
}
}
}

class paper_publication extends book
{
private String[][] title ={{"Atul","Easy paper Solution"},{"Gala paper Solution","alpha paper Solution"}};

void display(int j)
{
System.out.println("paper publication name of given author are....");
System.out.println("------------------------------------------------");

for(int i=0;i<2;i++)
{
System.out.println(title[j][i]);
}
}
}

class publication
{
public static void main(String [] args)
{
Scanner jaimin = new Scanner(System.in);
book o=new book();
book_publication b_o=new book_publication();
paper_publication p_o=new paper_publication();


int length=args.length;
int author=0,choice;
if(length==0)
{
System.out.println("please enter author name");
}

if(length>=2)
{
System.out.println("Add only one name to search names");
}

if(args[0].equals("jaimin"))
{
author=0;
}
else if(args[0].equals("naitik"))
{
author=1;
}
else
{
System.out.println("You have added wrong name of author");
System.exit(-1);
}


System.out.println("press \"1\" to display book author names\npress \"2\" to display book title names\npress \"3\" to display paper publication names ");
choice=jaimin.nextInt();

switch(choice)
{
case 1:
o.display();
break;

case 2:
b_o.display(author);
break;

case 3:
p_o.display(author);
break;

default:
System.out.println("wrong choice....");
System.exit(-2);
break;

}

}
}

output



program to display employee who have salary more than 20000

Declare a class called employee having employee_id and employee_name as members. Extend class employee to have a subclass called salary having designation and monthly_salary as members. Define following:
- Required constructors
- A method to find and display all details of employees drawing salary more than Rs. 20000/-.
- Method main for creating an array for storing these details given as command line arguments and showing usage of above methods.



import java.util.Scanner;
class Employee
{
String[] employee_id;
String[] employee_name;
}

class Salary extends Employee
{
String[] Designation;
double[] monthly_salary;

Salary(int j)
{
/*initialization of array */

employee_name=new String[j];
employee_id=new String[j];
Designation=new String[j];
monthly_salary= new double[j];

}

void display(int j)
{


System.out.println("---------------------------------------------------------------");
System.out.println("---------------------------------------------------------------");
System.out.println("\t Details of employee who have salary above 20000");
System.out.println("---------------------------------------------------------------");
System.out.println("---------------------------------------------------------------\n \n");


System.out.format("%-15s %-15s %-25s %-10s %n","employee id","employee name","employee Designation","Monthly Salary");
System.out.println("----------------------------------------------------------------------------");
for(int i=0;i<j;i++)
{

if(monthly_salary[i]>=20000)
{
System.out.format("%-15s %-15s %-25s %-10s %n",employee_id[i],employee_name[i],Designation[i],monthly_salary[i]);

}
}
}


public static void main(String [] args)
{
Scanner jaimin=new Scanner(System.in);
int length=args.length;

Salary obj = new Salary(length);


if(length==0)
{
System.out.println("please enter employee id");
}

for(int i=0;i<length;i++)
{
obj.employee_id[i]=args[i];

System.out.println("\n\n enter the details of \""+args[i]+"\" employee id");

System.out.print("\n name of employee -->");
obj.employee_name[i]=jaimin.next();

System.out.print("\n Designation of employee -->");
obj.Designation[i]=jaimin.next();

System.out.print("\nMonthly salary of employee -->");
obj.monthly_salary[i]=jaimin.nextDouble();


}

obj.display(length);
}
}

output




calculate spi for any number of students...

It is required to compute SPI (semester performance index) of n students of your college for their registered subjects in a semester. Declare a class called student having following data members:
id_no , no_of_subjects_registered, subject_code , subject_credits, grade_obtained and spi.
- Define constructor and calculate_spi methods.
- Define main to instantiate an array for objects of class student to process data of n students to be given as command line arguments.

import java.util.Scanner;

class Student
{
int id_no,no_of_sub_registered;
int[] sub_code=new int[7];
int[] sub_credit=new int[7];
String[] grade_obtain=new String[10];
int[] grade_point=new int[10];
double spi;
int sum=0,sum1=0;

Student()
{
no_of_sub_registered=7;
sub_code[0]=150001;
sub_credit[0]=2;
sub_code[1]=150701;
sub_credit[1]=5;
sub_code[2]=150702;
sub_credit[2]=6;
sub_code[3]=150703;
sub_credit[3]=6;
sub_code[4]=150704;
sub_credit[4]=4;
sub_code[5]=150705;
sub_credit[5]=1;
sub_code[6]=150606;
sub_credit[6]=6;
}

void calculate_spi()
{

for(int i=0;i<=6;i++)
{




if(grade_obtain[i].equals("AA"))
grade_point[i]=10;
else if(grade_obtain[i].equals("AB"))
grade_point[i]=9;
else if(grade_obtain[i].equals("BB"))
grade_point[i]=8;
else if(grade_obtain[i].equals("BC"))
grade_point[i]=7;
else if(grade_obtain[i].equals("CC"))
grade_point[i]=6;
else if(grade_obtain[i].equals("CD"))
grade_point[i]=5;
else if(grade_obtain[i].equals("DD"))
grade_point[i]=4;
else if(grade_obtain[i].equals("FF"))
grade_point[i]=0;


this.sum = sum+(sub_credit[i]*grade_point[i]);
this.sum1 = sum1+sub_credit[i];

}

spi = sum/sum1;
System.out.println("your spi is = "+spi);
}


public static void main(String [] args)
{
Scanner jaimin=new Scanner(System.in);
Student obj=new Student();
int length =args.length;

if(length <= 0)
{
System.out.println("enter enrollment no list");
}



for(int k=0;k < length ; k++)
{
System.out.println("Enter details about grade obtain for each subject \n \n");
System.out.println("subject code \t subject credit \t obtain grade \n");
System.out.println("------------------------------------------------ \n");

for(int i=0;i<=6;i++)
{
System.out.print(obj.sub_code[i]+"\t \t \t"+ obj.sub_credit[i] +"\t \t \t");
String r=jaimin.nextLine();
obj.grade_obtain[i]=r;

}

obj.calculate_spi();
}
}
}

OUTPUT