Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

Sowji Java Lab

The document contains 14 Java programs demonstrating various Java concepts like: 1. Defining classes and methods for arithmetic operations 2. Overloading constructors and instantiating objects 3. Setting and retrieving instance variable values 4. Overloading instance methods and dynamic method invocation 5. Inheritance and subclass usage 6. Nested classes 7. Array of objects 8. String and StringBuffer/StringBuilder class methods 9. Vector class and methods 10. Wrapper classes and methods 11. Inheritance and method overriding 12. Implementing interfaces 13. Extending interfaces

Uploaded by

pagoti mohanrao
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Sowji Java Lab

The document contains 14 Java programs demonstrating various Java concepts like: 1. Defining classes and methods for arithmetic operations 2. Overloading constructors and instantiating objects 3. Setting and retrieving instance variable values 4. Overloading instance methods and dynamic method invocation 5. Inheritance and subclass usage 6. Nested classes 7. Array of objects 8. String and StringBuffer/StringBuilder class methods 9. Vector class and methods 10. Wrapper classes and methods 11. Inheritance and method overriding 12. Implementing interfaces 13. Extending interfaces

Uploaded by

pagoti mohanrao
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

PROGRAM 1

Write a Java Program to define a class, Arthematic operations

class Arthemetic

public static void main(String args[])

int a=10,b=20,add=0,sub=0,mul=0,div=0;

add=a+b;

sub=a-b;

mul=a*b;

div=a/b;

System.out.print("%d\n",add);

System.out.print("%d\n",sub);

System.out.print("%d\n",mul);

System.out.print("%d\n",div);

}
PROGRAM 2

Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object */

import java.lang.*;
class student
{
String name;
int regno;
int marks1,marks2,marks3;
// null constructor
student()
{
name="raju";
regno=12345;
marks1=56;
marks2=47;
marks3=78;
}
// parameterized constructor
student(String n,int r,int m1,int m2,int m3)
{
name=n;
regno=r;
marks1=m1;
marks2=m2;
marks3=m3;
}
// copy constructor
student(student s)
{
name=s.name;
regno=s.regno;
marks1=s.marks1;
marks2=s.marks2;
marks3=s.marks3;
}
void display()
{
System.out.println(name + "\t" +regno+ "\t" +marks1+ "\t" +marks2+ "\t" + marks3);
}
}
class studentdemo
{
public static void main(String arg[])
{
student s1=new student();

student s2=new student("john",34266,58,96,84);


student s3=new student(s1);
s1.display();
s2.display();
s3.display();
}
}
PROGRAM 3

Write a Java Program to define a class, define instance methods for setting and
Retrieving values of instance variables and instantiate its object.*/

import java.lang.*;
class emp
{
String name;
int id;
String address;
void getdata(String name,int id,String address)
{
this.name=name;
this.id=id;
this.address=address;
}
void putdata()
{
System.out.println("Employee details are :");
System.out.println("Name :" +name);
System.out.println("ID :" +id);
System.out.println("Address :" +address);
}
}
class empdemo
{
public static void main(String arg[])
{
emp e=new emp();
e.getdata("smith",76859,"gulbarga");
e.putdata();
}
}
PROGRAM 4

/* Write a Java Program to define a class, define instance methods and overload them
and use them for dynamic method invocation.*/

import java.lang.*;
class add
{
void display(int a,int b)
{
int c=a+b;
System.out.println("The sum of " + a + " & " + b + " is " + c);
}
void display(double a,double b)
{ double c=a+b;
System.out.println("The sum of " + a + " & " + b + " is " + c);
}
}
class add_demo
{
public static void main(String arg[])
{
add obj=new add();
obj.display(10,20);
obj.display(10.2,20.2);
}
}
PROGRAM 5

/* Write a Java Program to demonstrate use of sub class */

import java.lang.*;
class parent
{
int m;
void get_m(int m)
{
this.m=m;
}
void display_m()
{
System.out.println("This is from parent : m = " +m);
}
}
class child extends parent
{
int n;
void get_n(int n)
{
this.n=n;
}
void display_n()
{
System.out.println("This is from child : n = " +n);
}
}
class childdemo
{
public static void main(String arg[])
{
child c=new child();
c.get_m(10);
c.get_n(20);
c.display_m();
c.display_n();
}
PROGRAM 6

/*Write a Java Program to demonstrate use of nested class.*/

import java.lang.*;
class outer
{
int m=10;
class inner
{
int n=20;
void display()
{
System.out.println("m = "+m);
System.out.println("n = "+n);
}
}
}
class nesteddemo
{
public static void main(String arg[])
{
outer outobj=new outer();
outer.inner inobj=outobj.new inner();
inobj.display();
}
}
PROGRAM 7

/* Write a Java Program to implement array of objects. */

import java.lang.*;
public class EmployeeTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 3500);
staff[1] = new Employee("Carl Cracker", 7500);
staff[2] = new Employee("Tony Tester", 3800);
for (int i = 0; i < 3; i++)
staff[i].print();
}
}
class Employee
{
private String name;
private double salary;
public Employee(String n, double s)
{
name = n;
salary = s;
}
public void print()
{
System.out.println(name + " " + salary);
}
}
PROGRAM 8

/* Write a Java program to practice using String class and its methods*/

import java.lang.String;
class stringdemo
{
public static void main(String arg[])
{
String s1=new String("gpt gulbarga");
String s2="GPT GULBARGA";
System.out.println(" The string s1 is : " +s1);
System.out.println(" The string s1 is : " +s2);
System.out.println(" Length of the string s1 is : " +s1.length());
System.out.println(" The first accurence of r is at the position : " +s1.indexOf('r'));
System.out.println(" The String in Upper Case : " +s1.toUpperCase());
System.out.println(" The String in Lower Case : " +s1.toLowerCase());
System.out.println(" s1 equals to s2 : " +s1.equals(s2));
System.out.println(" s1 equals ignore case to s2 : " +s1.equalsIgnoreCase(s2));
int result=s1.compareTo(s2);
System.out.println("After compareTo()");
if(result==0)
System.out.println( s1 + " is equal to "+s2);
else if(result>0)
System.out.println( s1 + " is greather than to "+s2);
else
System.out.println( s1 + " is smaller than to "+s2);
System.out.println(" Character at an index of 6 is :" +s1.charAt(6));
String s3=s1.substring(4,12);
System.out.println(" Extracted substring is :"+s3);
System.out.println(" After Replacing g with a in s1 : " + s1.replace('g','a'));
String s4=" This is a book ";
System.out.println(" The string s4 is :"+s4);
System.out.println(" After trim() :"+s4.trim());

}
PROGRAM 9

/*Write a Java program to practice using String Buffer class and its methods*/

import java.lang.String;
class stringbufferdemo
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("This is my college");
System.out.println("This string sb is : " +sb);
System.out.println("The length of the string sb is : " +sb.length());
System.out.println("The capacity of the string sb is : " +sb.capacity());
System.out.println("The character at an index of 6 is : " +sb.charAt(6));
sb.setCharAt(3,'x');
System.out.println("After setting char x at position 3 : " +sb);
System.out.println("After appending : " +sb.append(" in gulbarga "));
System.out.println("After inserting : " +sb.insert(19,"gpt "));
System.out.println("After deleting : " +sb.delete(19,22));
}
}
PROGRAM 10

/*Write a Java Program to implement Vector class and its methods*/.

import java.lang.*;
import java.util.Vector;
import java.util.Enumeration;
class vectordemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("zero",0);
v.insertElementAt("oops",3);
v.insertElementAt("four",5);
System.out.println("Vector Size :"+v.size());
System.out.println("Vector apacity :"+v.capacity());
System.out.println(" The elements of a vector are :");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement() +" ");
System.out.println();
System.out.println("The first element is : " +v.firstElement());
System.out.println("The last element is : " +v.lastElement());
System.out.println("The object oops is found at position : "+v.indexOf("oops"));
v.removeElement("oops");
v.removeElementAt(1);
System.out.println("After removing 2 elements ");
System.out.println("Vector Size :"+v.size());
System.out.println("The elements of vector are :");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i)+" ");
}
PROGRAM 11

/*Write a Java Program to implement Wrapper classes and their methods*/.

import java.io.*;
class wrapperdemo
{
public static void main(String args[])
{
Float P=new Float(0);
Float I=new Float(0);
int y=0;
try
{
DataInputStream ds=new DataInputStream(System.in);
System.out.println("ENTER THE PRINCIPAL AMOUNT");
System.out.flush();
String sp=ds.readLine();
P=Float.valueOf(sp);
System.out.println("ENTER THE INTEREST RATE");
System.out.flush();
String SI=ds.readLine();
I=Float.valueOf(SI);
System.out.println("ENTER THE NUMBER OF YEARS");
System.out.flush();
String sy=ds.readLine();
y=Integer.parseInt(sy);
}
catch(Exception e)
{
System.out.println("INPUT OUTPUT ERROR");
System.exit(1);
}
float value=loan(P.floatValue(),I.floatValue(),y);
System.out.println("FINAL VALUE IS:"+value);
}
static float loan(float P,float I,int y)
{
int year=1;
float sum=P;
while(year<=y)
{
sum=sum+(P*I)/100;
year++;
}
return sum;
}
}
PROGRAM 12

/*Write a Java Program to implement inheritance and demonstrate use of method


overriding*/

import java.lang.*;
class A
{
void display()
{
System.out.println("This is from class A ");
}
}
class B extends A
{
void display()
{
System.out.println("This is from class B ");
}
}
class AB

public static void main(String arg[])

{
B obj=new B();
obj.display();
}
}
PROGRAM 13

/*Write a program to demonstrate use of implementing interfaces*/.

import java.lang.*;
interface Area
{
final static float pi=3.14F;
float compute(float x,float y);
}
class rectangle implements Area
{
public float compute(float x,float y)
{
return(pi*x*y);
}
}
class circle implements Area
{
public float compute(float x,float x)
{
return(pi*x*x);
}
}
class interfacedemo
{
public static void main(String a[])
{
rectangle rect=new rectangle();
circle cir=new circle();
Area A;
A=rect;
System.out.println("Area of rectangle="+A.compute(10,20));
A=cir;
System.out.println("Area of circle="+A.compute(30,0));

}}
PROGRAM 14

/*Write a program to demonstrate use of extending interfaces*/.

import java.lang.*;
interface Area
{
final static float pi=3.14F;
double compute(double x,double y);
}
interface display extends Area
{
void display_result(double result);
}
class rectangle implements display
{
public double compute(double x,double y)
{
return(pi*x*y);
}
public void display_result(double result)
{
System.out.println("The Area is :" +result);
}
}
class InterfaceExtendsDemo
{
public static void main(String a[])
{
rectangle rect=new rectangle();
double result=rect.compute(10.2,12.3);
rect.display_result(result);

}
PROGRAM 15

/*Write a Java program to implement the concept of importing classes from user
defined package and creating packages*/

/*Source code of package p1 under the directory C:\jdk1.6.0_26\bin>p1\edit Student.java */

package p1;
public class Student
{
int regno;
String name;
public void getdata(int r,String s)
{
regno=r;
name=s;
}
public void putdata()
{
System.out.println("regno = " +regno);
System.out.println("name = " + name);
}
}
/* Source code of the main function under C:\jdk1.6.0_26\bin>edit StudentTest.java */
import p1.*;
class StudentTest
{
public static void main(String arg[])
{

student s=new student();

s.getdata(123,"xyz");
s.putdata();
}
}
PROGRAM 16

/*Write a program to implement the concept of threading by extending Thread Class*/

import java.lang.Thread;
class A extends Thread
{
public void run()
{
System.out.println("thread A is sterted:");
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread A:i="+i);
}
System.out.println("exit from thread A:");
}
}
class B extends Thread
{
public void run()
{
System.out.println("thread B is sterted:");
for(int j=1;j<=5;j++)
{
System.out.println("\t from thread B:j="+j);
}
System.out.println("exit from thread B:");
}
}
class C extends Thread
{
public void run()
{
System.out.println("thread C is sterted:");
for(int k=1;k<=5;k++)
{
System.out.println("\t from thread C:k="+k);
}
System.out.println("exit from thread C:");
}
}
class Threadtest
{
public static void main(String arg[])
{
new A().start();
new B().start();

new C().start()

}
}
PROGRAM 17

/*Write a program to implement the concept of threading by implementing Runnable


Interface*/

import java.lang.Runnable;
class X implements Runnable
{
public void run()
{
for(int i=1;i<10;i++)
{
System.out.println("\t Thread X:"+i);
}
System.out.println("End of Thread X");
}
}
class Runnabletest
{
public static void main(String arg[])
{
X R=new X();
Thread T=new Thread(R);
T.start();

}
PROGRAM 18

/*Write a program using Applet For configuring Applets by passing parameters.*/

import java.applet.*;
import java.awt.Graphics;
/* <applet code="AppletParamDemo.class" width=300 height=100>
<param name=place value="Gulbarga"> <param name=college value="Govt Polytechnic">
</applet> */
public class AppletParamDemo extends Applet
{
String p,c;
public void init()
{
p=getParameter("place");
c=getParameter("college");
}
public void paint(Graphics g)
{
g.drawString(c,80,20);
g.drawString(p,100,40);

}
********************************OUTPUT*********************************

C:\jdk1.6.0_26\bin>javac AppletParamDemo.java
C:\jdk1.6.0_26\bin>appletviewer AppletParamDemo.java
PROGRAM 19

Write programs for using Graphics class


- to display basic shapes and fill them
- draw different items using basic shapes
- set background and foreground colors.

import java.applet.*;
import java.awt.*;
/* <applet code=”Shapes.class” width=800 height-800> </applet>*/
public class Shapes extends Applet
{
public void paint(Graphics g)
{
setForefround(Color.red);
setBackGround(Color.blue);
//drawing squares
g.drawLine(10,10,100,10);
g.drawLine(10,10,10,10);
g.drawLine(10,100,100,100);
g.drawLine(100,100,100,10);
// Drawing triangle
g.drawLine(10,120,100,120);
g.drawLine(10,120,50,200);
g.drawLine(50,200,100,120);
//drawing Rectangle
g.drawRect(120,10,220,120);
g.fillRect(120,120,220,120);
//drawing ellipse and circle
g.drawOval(10,220,100,220);
g.setColor(Cplor.yellow);
g.fillOval(120,250,250,250);
//draw a filled arc
g.fillArc(350,50,400,100,0,90);
//draw a polygon
int x[]={400,500,400,500);
int y[]={240,240,340,340};
g.drawPolygon(x,y,4);
}
}
*******************************OUTPUT*********************************
PROGRAM 20

/*Write a programme for matrix multiplication import java.io.*/

class Matrixmultiplication

public static void main(String args[])

int a[][]={{3,4},{5,6}},b[][]={{7,8},{9,2}},c[][]={{0,0},{0,0}},i,j,k;

System.out.println("A matrix is:");

for(i=0;i<2;i++)

for(j=0;j<2;j++)

System.out.print(a[i][j]+"\t");

System.out.println("\n");

System.out.println("B matrix is:");

for(i=0;i<2;i++)

for(j=0;j<2;j++)
{

System.out.print(b[i][j]+"\t");

System.out.println("\n");

//logic for Matrixmultiplicatoin

for(i=0;i<2;i++)

for(j=0;j<2;j++)

c[i][j]=0;

for(k=0;k<2;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

//System.out.println("matrix multiplication of A and B is:");

for( i=0;i<2;i++)

for( j=0;j<2;j++)
{

System.out.print(c[i][j]+"\t");

System.out.println("\n");

}
PROGRAM 21

/*Write a java programme for stack implementation*/

Public class StackDemo 

{  

 private static final int capacity = 3;  

 int arr[] = new int[capacity];  

 int top = -1;  

  public void push(int pushedElement)

 {  

  if (top < capacity - 1)

 {  

   top++;  

   arr[top] = pushedElement;  

   System.out.println("Element " + pushedElement  

     + " is pushed to Stack !");  

   printElements();  

  } 

else 

{  
   System.out.println("Stack Overflow !");  

  }  

 }  

  public void pop() 

{  

  if (top >= 0) 

{  

   top--;  

   System.out.println("Pop operation done !");  

  } 

Else

 {  

   System.out.println("Stack Underflow !");  

  }  

 }  

 public void printElements() 

{  

  if (top >= 0) 

{  

   System.out.println("Elements in stack :");  
   for (int i = 0; i <= top; i++) 

{  

    System.out.println(arr[i]);  

   }  

  }  

 }  

  public static void main(String[] args)

 {  

  StackDemo stackDemo = new StackDemo();  

  stackDemo.pop();  

  stackDemo.push(23);  

  stackDemo.push(2);  

  stackDemo.push(73);  

  stackDemo.push(21);  

  stackDemo.pop();  

  stackDemo.pop();  

  stackDemo.pop();  

  stackDemo.pop();  

 }  }  
****************************OUTPUT*************************************
PROGRAM 22

/*Write a java programme for queue implementation*/

public class QueueDemo 

{  

 private static final int capacity = 3;  

 int arr[] = new int[capacity];  

 int size = 0;  

 int top = -1;  

 int rear = 0;  

  

 public void push(int pushedElement) 

{  

  if (top < capacity - 1) 

{  

   top++;  

   arr[top] = pushedElement;  

   System.out.println("Element " + pushedElement  

     + " is pushed to Queue !");  

   display();  

  } 
Else

 {  

   System.out.println("Overflow !"); 

}  

   }  

  public void pop() 

{  

  if (top >= rear)

 {  

   rear++;  

   System.out.println("Pop operation done !");  

   display();  

  } else 

{  

   System.out.println("Underflow !");  

  }  

 }  

   public void display() 

{  

  if (top >= rear)
 {  

   System.out.println("Elements in Queue : ");  

   for (int i = rear; i <= top; i++) 

{  

    System.out.println(arr[i]);  

   }  

  }  

 }  

 public static void main(String[] args) 

{  

  QueueDemo queueDemo = new QueueDemo();  

  queueDemo.pop();  

  queueDemo.push(23);  

  queueDemo.push(2);  

  queueDemo.push(73);  

  queueDemo.push(21);  

  queueDemo.pop();  

  queueDemo.pop();  

  queueDemo.pop();  

  queueDemo.pop();  }    }  
****************************OUTPUT*************************************
PROGRAM 23

/*Write a java programme for implement the linked list*/


import java.util.*;

public class LinkedListDemo


{

public static void main(String args[])


{
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);

// remove elements from the linked list


ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);

// remove first and last elements


ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);

// get and set a value


Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
****************************OUTPUT*************************************
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
PROGRAM 24

/*Write a java programme for implement the bubbolesort*/


public class MyBubbleSort {
 
    // logic to sort the elements
    public static void bubble_srt(int array[]) {
        int n = array.length;
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) {
                k = i + 1;
                if (array[i] > array[k]) {
                    swapNumbers(i, k, array);
                }
            }
            printNumbers(array);
        }
    }
 
    private static void swapNumbers(int i, int j, int[] array) {
 
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
 
    private static void printNumbers(int[] input) {
         
        for (int i = 0; i < input.length; i++) {
            System.out.print(input[i] + ", ");
        }
        System.out.println("\n");
    }
 
    public static void main(String[] args) {
        int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
        bubble_srt(input);
 
    }
}
Output:

2, 4, 6, 9, 12, 23, 0, 1, 34,

2, 4, 6, 9, 12, 0, 1, 23, 34,

2, 4, 6, 9, 0, 1, 12, 23, 34,

2, 4, 6, 0, 1, 9, 12, 23, 34,

2, 4, 0, 1, 6, 9, 12, 23, 34,

2, 0, 1, 4, 6, 9, 12, 23, 34,

0, 1, 2, 4, 6, 9, 12, 23, 34,

0, 1, 2, 4, 6, 9, 12, 23, 34,

0, 1, 2, 4, 6, 9, 12, 23, 34,


PROGRAM 25

/*Write a java programme for implement insertion sort*/


package com.java2novice.algos;
 
public class MyInsertionSort
{
 
    public static void main(String[] args)
{
         
        int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
        insertionSort(input);
    }
     
    private static void printNumbers(int[] input)
{
         
        for (int i = 0; i < input.length; i++)
{
            System.out.print(input[i] + ", ");
        }
        System.out.println("\n");
    }
 
    public static void insertionSort(int array[])
{
        int n = array.length;
        for (int j = 1; j < n; j++)
{
            int key = array[j];
            int i = j-1;
            while ( (i > -1) && ( array [i] > key ) )
{
                array [i+1] = array [i];
                i--;
            }
            array[i+1] = key;
            printNumbers(array);
        }
    }
}
Output:
2, 4, 9, 6, 23, 12, 34, 0, 1,

2, 4, 9, 6, 23, 12, 34, 0, 1,

2, 4, 6, 9, 23, 12, 34, 0, 1,

2, 4, 6, 9, 23, 12, 34, 0, 1,

2, 4, 6, 9, 12, 23, 34, 0, 1,

2, 4, 6, 9, 12, 23, 34, 0, 1,

0, 2, 4, 6, 9, 12, 23, 34, 1,

0, 1, 2, 4, 6, 9, 12, 23, 34,


PROGRAM 26

/*Write a java programme for implement selection sort*/


package com.java2novice.algos;
 
public class MySelectionSort
{
 
    public static int[] doSelectionSort(int[] arr)
{
         
        for (int i = 0; i < arr.length - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j] < arr[index])
                    index = j;
      
            int smallerNumber = arr[index]; 
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }
        return arr;
    }
     
    public static void main(String a[])
{
         
        int[] arr1 = {10,34,2,56,7,67,88,42};
        int[] arr2 = doSelectionSort(arr1);
        for(int i:arr2){
            System.out.print(i);
            System.out.print(", ");
        }
    }
}
Output:
2, 7, 10, 34, 42, 56, 67, 88,

You might also like