39
JAVA PROGRAMMING SUBMITTED TO: SUBMITTED BY: LECT. ABHISHEK KUMAR MUSTKEEM ADD.NO.:14S121 BRANCH: 5 CS. DIGAMBER JAIN POLYTECHNIC BARAUT BAGHPAT

Java Practical File Diploma

Embed Size (px)

Citation preview

Page 1: Java Practical File Diploma

JAVA PROGRAMMING

SUBMITTED TO: SUBMITTED BY:

LECT. ABHISHEK KUMAR MUSTKEEMADD.NO.:14S121

BRANCH: 5 CS.

DIGAMBER JAIN POLYTECHNIC BARAUT BAGHPAT

Page 2: Java Practical File Diploma

Admission no.: 14S121

Page 1

INTRODUCTION OF JAVA:Java is a programming language originally developed by James Gosling at SunMicrosystems and released in 1995 as a core component of Sun Microsystems Javaplatform. The language derives much of its syntax from C and C++ but has a simplerobject model and fewer low level facilities. The development of Java languagestarted in 1990 when a letter is written to the CEO of Sun Microsystems. After muchresearch and testing, the result was a simple object oriented programming languagenamed Oak.The four characteristics to be object oriented language are:a) Inheritance: it is a process of creating the new classes and using thebehaviour of the existences classes by extending the just to reuse the existingcode and adding the additional features as needed.b) Encapsulation: it is the mechanism of combining the information andproviding the abstraction.c) Polymorphism: A the name suggest one name multiple form, it’s is the wayof providing the different functionality by the functions having the samename based on the signature of the methodsd) Abstraction: it is the set of representing without knowing its backgrounddetails.

REQUIREMENT OF JAVA:

Hardware Required:

IBM-compatible Pentium pc Minimum of 8 MB RAM A CD-ROM drive A Hard disk of 2GB or higher

Software Required:

Windows 95 software Java Development Kit

Page 3: Java Practical File Diploma

Admission no.: 14S121

Page 2

JAVA SETUP:

Step 1:

Download the java development environment JDK can be downloaded from url

“http://java.sun.com/j2se/1.4.2/download.html”. Download the SDK software by

clicking on the “Download J2SE SDK” link. You will be shown a licensing agreement. Click

Accept. Select your operating system and download the file to your download directory.

Step: 2

Page 4: Java Practical File Diploma

Admission no.: 14S121

Page 3

Step: 3

Step: 4

Page 5: Java Practical File Diploma

Admission no.: 14S121

Page 4

Step: 5

Step: 6

Page 6: Java Practical File Diploma

Admission no.: 14S121

Page 5

Step 7: Now you should be able to open another MS-DOS Window and type JAVAC. If

everything is set up properly, then you should see a two-line blob of text come out that

tells you how to use JAVAC. That means you are ready to go. If you see the message

“Bad command or File Name” it means you are not ready to go. Figure out what you did

wrong by rereading the installation instructions. Make sure the PATH is set properly and

working. Go back and reread the programmer’s creed above and be persistent until the

problem is resolved.

You are now the proud Owner of a machine that can compile Java programs. You are

ready to start writing software!

Program 1: WAP in Java to print “Hello World”.

public class Hello {

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("Hello World");

}

}

OUTPUT:

Page 7: Java Practical File Diploma

Admission no.14S121

Program 2: WAP to find the average, sum, min and max of the N numbers Using userInput.

Code:

import java.util.*;public class Average

{public static void main(String args[])

{int sum=0,i=3;int count=0,max,min,n;float avg;

i = args.length;if (args.length == 0)System.out.println("Argument is expected");else

{System.out.println("Number of arguments is"+i);

max = Integer.parseInt(args[0]);min = Integer.parseInt(args[0]);System.out.println("first argument is"+args[0]);System.out.println("second argument is"+args[1]);System.out.println("Third argument is"+args[2]);while(count < i)

{n = Integer.parseInt(args[count]);

sum += n;if(min > n)

min = n;if (max < n)

max = n;count += 1;}avg = sum/i;System.out.println("The sum is"+sum);

System.out.println("The average is"+avg);System.out.println("Maximum is"+max);System.out.println("Minimum is "+min);

}}}

Page 8: Java Practical File Diploma

Admission no.14S121

Output :

Page 9: Java Practical File Diploma

Admission no.14S121

Program 3: WAP to Demonstrate Type Casting.

Code:

class type_casting

{public static void main(String args[])

{byte h=127; int a=300;float a1=12.222f; float g;short b=200; long c=999999; float e=345.89F;double f=45645.78222222222222;g= (float)f;System.out.println("short b ="+g);System.out.println("short b ="+b);System.out.println("long c ="+c);System.out.println("float e="+e);System.out.println("double f="+f);System.out.println("short b="+b);System.out.println("short to byte "+(byte)b);System.out.println("int to byte "+(byte)a);System.out.println("int to float"+(float)a);System.out.println("long to byte "+(byte)c);System.out.println("double to long "+(long)f);System.out.println("double to int "+(int)f);System.out.println("double to byte "+(byte)f);System.out.println("double to short "+(short)f);System.out.println("double to float "+(float)f);System.out.println("float to int "+(int)e);System.out.println("float to byte "+(byte)e);System.out.println("float to short "+(short)e);System.out.println("float to long "+(long)e);System.out.println("float to double ="+(double)e);System.out.println("long to int"+(int)c);System.out.println("byte to int ="+(int)h);

}}

Page 10: Java Practical File Diploma

Admission no.14S121

Output :

Page 11: Java Practical File Diploma

Admission no.14S121

Program 4: WAP t find the number of arguments provide at runtime.

Code:package pack;import java.util.*;public class Add {

public static void main(String[] args) {int sum;Scanner sc=new Scanner(System.in);System.out.println("enter no. of args");

sum=sc.nextInt();for (int i = 0; i < args.length; i++) {

sum = sum + Integer.parseInt(args[i]);}System.out.println("The sum of the arguments passed is " +

sum);}

}

Output :

Page 12: Java Practical File Diploma

Admission no.14S121

Program 5: WAP to Test the Prime num.Code:class prime{public static void main(String args[]){int i,m=0,flag=0;int n=18;//it is the number to be checked

m=n/2;for(i=2;i<=m;i++){if(n%i==0){System.out.println("Number is prim");

flag=1;break;

}}if(flag==0)System.out.println("Number is not prime");

}}

Output :

Page 13: Java Practical File Diploma

Admission no.14S121

Program 6: WAP to calculate the Simple Interest and Input by the user.Code:import java.util.*;public class si{

public static void main(String args[]) {

//creating scanner to accept principle, rate and time inputform user

Scanner scanner = new Scanner(System.in);System.out.println("Welcome in Java program to calculate

Simple interest");System.err.println("Please enter principle amount :");float amount = scanner.nextFloat();System.err.println("Enter time in years : ");float time = scanner.nextFloat();System.out.println("Enter rate annually : ");float rate = scanner.nextFloat();float interest = simpleInterest(amount, rate, time);System.out.println("Simple interested calculate by program

is : " + interest);}

public static float simpleInterest(float principle, floatrate, float time){

float interest = (principle*rate*time)/100;return interest;

}}

Output :

Page 14: Java Practical File Diploma

Admission no.14S121

Program 7: WAP to create a Simple class to find out the Area and perimeter ofrectangle and box using super and this keyword.Code:class rect

{int l,b;public rect(int l,int b){ this.l=l;this.b=b;

}public int area()

{return l*b;

}}class box extends rect

{int d;public box(int l,int b,int d)

{super(l,b);this.d=d;

}public int volume()

{int vol = area()*d;return vol;

}public static void main(String args[]){ int vol ,area;System.out.println("derived object in derived reference");rect r= new rect(10,20);

area=r.area();System.out.println("area is "+area+"\n");System.out.println("base object in base reference");box b = new box(10,20,30);

vol=b.volume();area=b.area();System.out.println("area is "+area);System.out.println("volume is "+vol+"\n");System.out.println("derived object in base reference");rect b1= new box(10,90,70);

area = b1.area();System.out.println("area is "+area);

r=b;System.out.println(r.area());

Page 15: Java Practical File Diploma

Admission no.14S121

System.out.println(((box) r).volume());

}}

Output :

Page 16: Java Practical File Diploma

Admission no.14S121

Program 8: WAP to find G.C.D of the number.Code:package pack;import java.util.*;public class GCDExample {public static void main(String args[]){//Enter two number whose GCD needs to be calculated.Scanner scanner = new Scanner(System.in);System.out.println("Please enter first number to find GCD");int number1 = scanner.nextInt();System.out.println("Please enter second number to find GCD");int number2 = scanner.nextInt();System.out.println("GCD of two numbers " + number1 +" and " +number2 +" is :" + findGCD(number1,number2)); }/* * Java method to find GCD of two number using Euclid's method *@return GDC of two numbers in Java */private static int findGCD(int number1, int number2) {//base caseif(number2 == 0){return number1;

}return findGCD(number2, number1%number2);

}}

Output :

Page 17: Java Practical File Diploma

Admission no.14S121

Program 9: WAP to design a class account using the inheritance and static that showall function of bank ( withdrawal, deposit) and generate account number dynamically.Code:import java.util.*;class account {static int acc_no = 10001;float amt;public void display() {System.out.println("Account no :" + acc_no);System.out.println("Current Amount :" + amt);

}public account() {

amt = 1000;System.out.println("Ur account no is " + acc_no);

acc_no++;

}public void getamt() {System.out.println("Current balance :" + amt);

}public void withdraw(float x) {if (amt == 1000 || amt <= x) {System.out.println("Sorry u can't withdraw");

} else {

amt = amt - x;System.out.println("amount withdrawn :" + x);System.out.println("After withdrawl");

getamt();}

}public void deposit(float x) {if (x == 0.0)System.out.println("OOPS 0 can't be deposited");

else {

amt += x;System.out.println("After deposition");

getamt();}

}public static void main(String args[]) {Scanner sc = new Scanner(System.in);account b1 = new account();

b1.deposit(0);b1.withdraw(120.5f);b1.display();System.out.println("\n");account b2 = new account();

Page 18: Java Practical File Diploma

Admission no.14S121

b2.deposit(1000.0f);b2.withdraw(150.5f);

}}

Output :

Page 19: Java Practical File Diploma

Admission no.14S121

Program 10: WAP to find the factorial of a given number using Recursion.Code:package pack;import java.util.Scanner;class FactorialDEmo{

public static void main(String args[]){//Scanner object for capturing the user inputScanner scanner = new Scanner(System.in);System.out.println("Enter the number:");//Stored the entered value in variableint num = scanner.nextInt();//Called the user defined function factint factorial = fact(num);System.out.println("Factorial of entered number is:

"+factorial);}static int fact(int n){

int output;if(n==1){

return 1;}//Recursion: Function calling itself!!output = fact(n-1)* n;return output;

}}

Output :

Page 20: Java Practical File Diploma

Admission no.14S121

Program 11: WAP to design a class using abstract Methods and Classes.Code:package pack;abstract class A{abstract void callme();public void normal(){System.out.println("this is concrete method");

}}class B extends A{void callme(){System.out.println("this is callme.");

}public static void main(String[] args){B b = new B();b.callme();b.normal();

}}

Output :

Page 21: Java Practical File Diploma

Admission no.14S121

Program 12: WAP to design a String class that perform String Method(Equal, Reversethe string, change case, trim etc. )Code:public class stringdemo

{public static void main(String args[])

{String str = "This is some sample String with some words that havebeen repeated some times";System.out.println("Total no. of characters : " + str.length());System.out.println("To Upper Case : " + str.toUpperCase());System.out.println("To Lower Case : " + str.toLowerCase());System.out.println("Original String : " + str);System.out.println(str.substring(8));System.out.println(str.substring(8,19));System.out.println(str.indexOf("some"));

String s = " " + str + " ";System.out.println(s);System.out.println("[" + s.trim() + "]");System.out.println(str.replace("s","$$##"));

String sh = "parth is a good boy";System.out.println(sh + " -> " + new StringBuffer(sh).reverse());

}}

Output :

Page 22: Java Practical File Diploma

Admission no.14S121

Program 13: WAP to handle the Exception using try and multiple catch block.

Code:

public class exceptiondemo{public static void main(String args[]){try{int a[]=new int[5];

a[5]=30/0;}catch(ArithmeticException e){

System.out.println("task1 is completed");}catch(ArrayIndexOutOfBoundsException e){

System.out.println("task 2 completed");}catch(Exception e){

System.out.println("common task completed");}System.out.println("rest of the code...");

}}

Output :

Page 23: Java Practical File Diploma

Admission no.14S121

Program 14: WAP that Implement the Nested try Statements Program.

Code:

class nestedtry{public static void main(String args[]){try{

try{System.out.println("going to divide");

// int b =39/0;}catch(ArithmeticException e){System.out.println(e);}try{int a[]=new int[5];

a[5]=4;}catch(ArrayIndexOutOfBoundsException

e){System.out.println(e);}System.out.println("other statement");

}catch(Exception e){System.out.println("handeled");}System.out.println("normal flow..");

}

}

Output :

Page 24: Java Practical File Diploma

Admission no.14S121

Program 15: WAP to create a package that access the member of external class aswell as same package.Code:package pack;class base

{public static void main(String arg[])

{System.out.println("Base class(p1)");p1 w=new p1();

//w.f1();System.out.println("Derived class(p2)");p2 x=new p2();

// x.f2();System.out.println("Simple class(p3)");p3 y=new p3();

// y.f3();}}package pack;public class p1

{int a=1;public int b=2;private int c=3;protected int d=4;public p1()

{System.out.println("Value of a="+a);System.out.println("Value of b="+b);System.out.println("Value of c="+c);System.out.println("Value of d="+d);}}package pack;class p2 extends p1

{p2(){System.out.println("Value of a="+a);System.out.println("Value of b="+b);//System.out.println("Value of c="+c);System.out.println("Value of d="+d);}}package pack;

Page 25: Java Practical File Diploma

Admission no.14S121

class p3

{p1 p=new p1();

p3(){System.out.println("Value of a="+(p.a));System.out.println("Value of b="+(p.b));//System.out.println("Value of c="+(p.c));System.out.println("Value of d="+(p.d));}}

Output :

Page 26: Java Practical File Diploma

Admission no.14S121

Program 16: WAP that import the user define package and access the Membervariable of classes that Contained by Package.Code:package pack;class Book{String bookname;String author;Book(String b, String c){this.bookname = b;this.author = c;

}public void show(){System.out.println(bookname+" "+ author);

}}class test{public static void main(String[] args){Book bk = new Book("java","Herbert");bk.show();

}}

Output :

Page 27: Java Practical File Diploma

Admission no.14S121

Program17: WAP that show the partial implementation of Interface.

Code:

package pack;interface MyInterface{

public void method1();public void method2();

}class XYZ implements MyInterface{

public void method1(){

System.out.println("implementation of method1");}public void method2(){

System.out.println("implementation of method2");}public static void main(String arg[]){

MyInterface obj = new XYZ();obj. method1();

}}

Output :

Page 28: Java Practical File Diploma

Admission no.14S121

Program 18: WAP to handle the user defined Exception using throw keyword.Code:package pack;class MyOwnException extends Exception {

public MyOwnException(String msg){super(msg);

}}

class EmployeeTest {static void employeeAge(int age) throws MyOwnException{

if(age < 0)throw new MyOwnException("Age can't be less than

zero");else

System.out.println("Input is valid!!");}public static void main(String[] args) {

try {employeeAge(0);

}catch (MyOwnException e) {

e.printStackTrace();}

}

}

Output :

Page 29: Java Practical File Diploma

Admission no.14S121

Program 19: WAP to create a thread that Implement the Runnable interface.Code:package pack;public class CreateThreadRunnableExample implements Runnable{

public void run(){for(int i=0; i < 5; i++){

System.out.println("Child Thread : " + i);try{

Thread.sleep(50);}catch(InterruptedException ie){

System.out.println("Child threadinterrupted! " + ie);

}}

System.out.println("Child thread finished!");}

public static void main(String[] args) {Thread t = new Thread(new CreateThreadRunnableExample(), "My

Thread");t.start();

for(int i=0; i < 5; i++){System.out.println("Main thread : " + i);try{

Thread.sleep(100);}catch(InterruptedException ie){

System.out.println("Child thread interrupted!" + ie);

}}System.out.println("Main thread finished!");}

}

Output :

Page 30: Java Practical File Diploma

Admission no.14S121

Program 20: WAP to Implement interthread communication.Code:package pack;class Customer{int amount=10000;synchronized void withdraw(int amount){System.out.println("going to withdraw...");if(this.amount<amount){System.out.println("Less balance; waiting for deposit...");try{wait();}catch(Exception e){}}this.amount-=amount;System.out.println("withdraw completed...");}synchronized void deposit(int amount){System.out.println("going to deposit...");this.amount+=amount;System.out.println("deposit completed... ");notify();}}class test1{public static void main(String args[]){final Customer c=new Customer();new Thread(){public void run(){c.withdraw(15000);}}.start();new Thread(){public void run(){c.deposit(10000);}}.start();}

}

Output :

Page 31: Java Practical File Diploma

Admission no.14S121

Program 21: WAP to create a class component that show controls and eventhandling on that controls.(math calc).Code:package pack;

import java.awt.*;import java.awt.event.*;

class Calculator implements ActionListener{

//Declaring ObjectsFrame f=new Frame();Label l1=new Label("First Number");Label l2=new Label("Second Number");Label l3=new Label("Result");

TextField t1=new TextField();TextField t2=new TextField();TextField t3=new TextField();

Button b1=new Button("Add");Button b2=new Button("Sub");Button b3=new Button("Mul");Button b4=new Button("Div");Button b5=new Button("Cancel");

Calculator(){

//Giving Coordinatesl1.setBounds(50,100,100,20);l2.setBounds(50,140,100,20);l3.setBounds(50,180,100,20);

t1.setBounds(200,100,100,20);t2.setBounds(200,140,100,20);t3.setBounds(200,180,100,20);

b1.setBounds(50,250,50,20);b2.setBounds(110,250,50,20);b3.setBounds(170,250,50,20);b4.setBounds(230,250,50,20);b5.setBounds(290,250,50,20);

//Adding components to the framef.add(l1);f.add(l2);f.add(l3);

f.add(t1);f.add(t2);f.add(t3);

Page 32: Java Practical File Diploma

Admission no.14S121

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);

f.setLayout(null);f.setVisible(true);f.setSize(400,350);

}

public void actionPerformed(ActionEvent e){

int n1=Integer.parseInt(t1.getText());int n2=Integer.parseInt(t2.getText());

if(e.getSource()==b1){

t3.setText(String.valueOf(n1+n2));}

if(e.getSource()==b2){

t3.setText(String.valueOf(n1-n2));}

if(e.getSource()==b3){

t3.setText(String.valueOf(n1*n2));}

if(e.getSource()==b4){

t3.setText(String.valueOf(n1/n2));}

if(e.getSource()==b5){

System.exit(0);}

}

public static void main(String...s){

new Calculator();}

}

Page 33: Java Practical File Diploma

Admission no.14S121

Output :

Page 34: Java Practical File Diploma

Admission no.14S121

Program 22: WAP to Draw the line, Rectangle, oval, text etc. using the graphicsmethod.Code:import java.applet.Applet;import java.awt.*;public class appletdemo extends Applet

{public void init(){setBackground(Color.cyan);

}public void paint(Graphics g)

{Font f=new Font("TIMES NEW ROMAN ",Font.ITALIC,32);g.setFont(f); g.setColor(Color.orange);

g.drawString("WELCOME TO APPLET ",30,30);g.fillOval(60,60,150,150);g.setColor(Color.black);

g.fillOval(90,100,20,20);g.fillOval(160,100,20,20);g.setColor(Color.RED);

g.drawLine(120,150,150,150);g.drawLine(120,150,140,130);g.drawArc(90,130,90,60,0,-180);}

}

Output :

Page 35: Java Practical File Diploma

Admission no.14S121

Program 23: WAP to create a menu Using Frame.Code:package pack;import java.awt.*;import java.awt.event.*;

public class SimpleMenuExample extends Frame implementsActionListener{

Menu states, cities;public SimpleMenuExample(){

MenuBar mb = new MenuBar(); // begin withcreating menu bar

setMenuBar(mb); // add menu bar to frame

states = new Menu("Indian States"); // create menuscities = new Menu("Indian Cities");

mb.add(states); // add menus to menu barmb.add(cities);

states.addActionListener(this); // link withActionListener for event handling

cities.addActionListener(this);

states.add(new MenuItem("Himachal Pradesh"));states.add(new MenuItem("Rajasthan"));states.add(new MenuItem("West Bengal"));states.addSeparator(); // separates from north

Indian states from south Indianstates.add(new MenuItem("Andhra Pradesh"));states.add(new MenuItem("Tamilnadu"));states.add(new MenuItem("Karnataka"));

cities.add(new MenuItem("Delhi"));cities.add(new MenuItem("Jaipur"));cities.add(new MenuItem("Kolkata"));cities.addSeparator(); // separates north Indian

cities from south Indiancities.add(new MenuItem("Hyderabad"));cities.add(new MenuItem("Chennai"));cities.add(new MenuItem("Bengaluru"));

setTitle("Simple Menu Program"); // frame creationmethods

setSize(300, 300);setVisible(true);

}public void actionPerformed(ActionEvent e){

String str = e.getActionCommand(); // know the menu itemselected by the user

Page 36: Java Practical File Diploma

Admission no.14S121

System.out.println("You selected " + str);}public static void main(String args[]){

new SimpleMenuExample();}

}

Output :

Page 37: Java Practical File Diploma

Admission no.14S121

Program 24: WAP to implement Dialog box.Code:import javax.swing.*;import java.awt.*;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;

public class MessageDilogBox extends JFrame {public MessageDilogBox() throws HeadlessException {

initialize();}private void initialize() {

setSize(200, 200);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button1 = new JButton("Click Me!");button1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

//// Show a message dialog with a text message of

course!//JOptionPane.showMessageDialog((Component)

e.getSource(),"Thank you!");

}});

JButton button2 = new JButton("What is your name?");button2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

//// Show an input dialog that will ask you to input

some text//String text =

JOptionPane.showInputDialog((Component) e.getSource(),"What is your name?");

if (text != null && !text.equals("")) {

JOptionPane.showMessageDialog((Component)e.getSource(),

"Hello " + text);}

}});

JButton button3 = new JButton("Close Application");button3.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

Page 38: Java Practical File Diploma

Admission no.14S121

//// Show a confirmation dialog which will ask to for

a YES or NO// button.//int result =

JOptionPane.showConfirmDialog((Component) e.getSource(),"Are you sure want to close this

application?");if (result == JOptionPane.YES_OPTION) {

System.exit(0);} else if (result == JOptionPane.NO_OPTION) {

// Do nothing, continue to run the application}

}});

setLayout(new FlowLayout(FlowLayout.CENTER));

getContentPane().add(button1);getContentPane().add(button2);getContentPane().add(button3);

}public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {public void run() {

new MessageDilogBox().setVisible(true);

}});

}

}

Output :

Page 39: Java Practical File Diploma

Admission no.14S121

Program 25: WAP to Implement the flow layout And Border Layout.Code:import java.awt.*;import javax.swing.*;public class Border {JFrame f;Border(){

f=new JFrame();

JButton b1=new JButton("NORTH");;JButton b2=new JButton("SOUTH");;JButton b3=new JButton("EAST");;JButton b4=new JButton("WEST");;JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);f.add(b2,BorderLayout.SOUTH);f.add(b3,BorderLayout.EAST);f.add(b4,BorderLayout.WEST);f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);f.setVisible(true);

}public static void main(String[] args) {

new Border();}

}

Output :