OOP JAVA Lab

OOP-Java Lab Programs:

1) a)Write a simple Java Program to perform addition operation?


Program:
class SimplePrg
     {
            public static void main(String   arg[  ])
                 {
                       int    a,b,c;
                       a = 5;
                       b = 3;
                       c = a + b;
                       System.out.println ("Sum is:  C = " + c);
                 }
       }
------------------------------------------
Compilation:
D:\Prog>javac SimplePrg.java
Execution: 
D:\Prog>java SimplePrg
Output: 
Sum is:  C = 8
------------------------------------------ 
1) b) Write a java program to read the values from the keyboard with readLine( ) method?
 Program:

import java.io.*;

class reading

{

       public static void main(String args[ ])

         {

            DataInputStream in=new DataInputStream(System.in);

            int a,b;

            System.out.println(“Enter ‘a’ value:”);

            a=Integer.parseInt(in.readLine( ));

            System.out.println(“Enter ‘b’ value:”);

            b=Integer.parseInt(in.readLine( ));

            int c=a+b;

            System.out.println(“result c is:”+c);

         }

}

Output: 

Enter ‘a’ value:4

Enter ‘b’ value:8

result c is:12
 
2) Write a java program to find the big number from the given?
Program:
class FindTheBig
 {
  public static void main(String  args[ ])
   {
    int a=10,b=5,c=15,big;
    if(a > b)
     if(a > c)
      big = a;
     else
      big = c;
    else if(b > c)
     big = b;
    else
     big = c;
    System.out.println("\n Big = "+big);
   }
 }

----------------------------------------

Output: 
Big = 15
---------------------------------------- 

3) Write a program to perform various String Operations?
Program:
class StringOperations
{
    public static void main(String  args
[ ] )
    {
        //create strings in 3 ways
        String  s1 = "A book on Java";
        String  s2 = new String(" I like this Book");
        char  arr[ ]={'D','r','e','a','m',' ','T','e','c','h'};
        String  s3 = new  String(arr);

        //displaying all the 3 strings
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);

        //find the length of 1st string
        System.out.println("Length of s1="+s1.length());

        //concat of two strings
        System.out.println("s1 and s2 joined="+s1.concat(s2));

        //concat of three strings
        System.out.println(s1+" from "+s3);
        //extract substring from s2, starting from 0th char to 6th char
        String  p = s2.substring(0,7);
        System.out.println("substring
 0th char to 6th char = "+p);
        //convert s1 into uppercase and lowercase
        System.out.println("Upper Case: s1 = "+s1.toUpperCase( ));
        System.out.println("Lower Case: s1 = "+s1.toLowerCase( ));

    }
}

-------------------------------------------------------------
D:\Lab>javac  StringOperations.java 
D:\Lab>java  StringOperations
Output: 
A book on Java
 I like this Book
Dream Tech
Length of s1=14
s1 and s2 joined=A book on Java I like this Book
A book on Java from Dream Tech
substring 0th char to 6th char =  I like
Upper Case: s1 = A BOOK ON JAVA
Lower Case: s1 = a book on java
-------------------------------------------------------------
4) Write a program on class and object in java?
Program:
class Account

    int acc_no;
    String name;
    float amount;
    void insert(int a,String n,float amt)
       {
        acc_no = a;
        name = n;
        amount = amt;
       }
    void deposit(float amt)
           {  
             amount = amount + amt; 
             System.out.println(amt +" deposited"); 
           }
    void withdraw(float amt)
            { 
                if(amount < amt)
                   { 
                      System.out.println("Insufficient Balance");
                    }
                else
                   { 
                     amount = amount - amt; 
                     System.out.println(amt + " withdrawn"); 
                    } 
             } 
    void presentBalance()
           {
             System.out.println("Balance is: " + amount);
            } 
    void display( )
            {
              System.out.println("Account No: " + acc_no + " :Account Holder Name: "+ name + " :Amount: " + amount);
            } 

 
class TestAccount
  { 
     public static void main(String  args[ ])
       { 
         Account a1 = new Account( ); 
         a1.insert(832345,"Ankit",1000); 
         a1.display( ); 
         a1.presentBalance( ); 
         a1.deposit(40000); 
         a1.presentBalance( ); 
         a1.withdraw(15000); 
         a1.presentBalance( ); 
        }
  }

------------------------------------------------------------------------

D:\Lab>javac  TestAccount.java 
D:\Lab>java  TestAccount
Output:
Account No: 832345 :Account Holder Name: Ankit :Amount: 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0 

-------------------------------------------------------------------------
  
5) Write a java program to implement interface?
 Program:
interface   Area                    //interface  defined
{
     final  static  float  pi = 3.14F;
    float  compute (float  x,  float  y);
}
class   Rectangle  implements   Area
{
    public   float   compute(float  x, float  y)
    {
        return  (x * y);
    }
}
class   Circle  implements   Area
{
    public   float   compute(float  x, float  y)
    {
        return  (pi * x * x);
    }
}
class  InterfaceTest
{
     public  static  void  main(String  args[ ])
        {
    Rectangle   rect =  new  Rectangle(  );
    Circle  cir = new  Circle( );
    Area   area;        //interface  object
    area =  rect;         //area  refers to rect object
    System.out.println ("Area of Rectangle = " + area.compute(10, 20));
    area = cir;        //area  refers to cir object
    System.out.println ("Area of Circle = " + area.compute(10, 0));
         }
 }


-------------------------------------------------- 
 

D:\Lab>javac  InterfaceTest.java 
D:\Lab>java  InterfaceTest
Output:
 Area of Rectangle =200
 Area of Circle =314
----------------------------------------------------

6) Write a java program to create packages ?
create a package with name forest and place Tiger.clas in it throw program not manually.
Let us assume C:\snr>  is the current directory where we like to create the package.
Program:
package forest;
import java.util.*;
public class Tiger
{
  public void getDetails(String nickName, int weight)
  {
    System.out.println("Tiger nick name is " + nickName);
    System.out.println("Tiger weight is " + weight);
  }
}



C:\snr > javac   -d   .   Tiger.java
Here the –d   compiler option creates a new folder called forest and places the Tiger.class in it. The dot (.) is an operating system's environment variable that indicates the current directory. It is an instruction to the OS to create a directory called forest and place the Tiger.class in it.



Now write a program from the target directory and access the created package.


C:\snr> notepad Animal.java
The above statement creates a file called Animal.java and write the code in it, say, as follows. 

import forest.Tiger;
public class Animal
{
  public static void main(String args[ ])
  {
    Tiger t1 = new Tiger ();
    t1.getDetails("Everest", 50);
  }
}

---------------------------------------------------- 
The compilation and execution is as usual as follows.
C:\snr> javac Animal.java
C:\snr> java Animal
Following is the Output:
Tiger nick name is Everest
Tiger weight is 50
------------------------------------------------- 
7) Write a program to create Multiple Threads in java?

 Program:
class A  extends  Thread
{
     public void run ( )
    {
          for(int i=1; i<=5; i++)
          {
            System.out.println(" \t from thread A: i= "+i);
           }
          System.out.println("exit from A");
     }
}
class B  extends  Thread
{
         public void run ( )
         {
    for(int j=1; j<=5; j++)
    {
        System.out.println("\t from thread B: j= "+j);
    }
        System.out.println("exit from B");
         }
}
class  C  extends  Thread
{
       public void run ( )
        {
            for(int k=1; k<=5; k++)
              {
                 System.out.println(" \t from thread C: k= "+k);
               }
            System.out.println(" exit from C ");
         }
}
class ThreadTest
{
    public  static  void   main(String args[ ] )
    {
        A  threadA = new  A(  );
        B  threadB = new  B(  );
        C  threadC = new  C(  );
      
        System.out.println("start thread A");
        threadA.start(  );
      
        System.out.println("start thread B");
        threadB.start(  );

        System.out.println("start thread C");
        threadC.start(  );

        System.out.println("end of main thread");
    }
}
------------------------------------------------------------
Output:
start thread A
start thread B
thread A started
         from thread A: i= 1
         from thread A: i= 2
         from thread A: i= 3
start thread C
         from thread A: i= 4
         from thread A: i= 5
exit from A
thread B started
thread C started
end of main thread
         from thread C: k=1
         from thread B: j=1
         from thread C: k=2
         from thread B: j=2
         from thread C: k=3
         from thread B: j=3
         from thread C: k=4
         from thread B: j=4
         from thread C: k=5
         from thread B: j=5
 exit from C
exit from B
------------------------------------------------------
8) Write a program to assign priorities to Threads in java?

 Program:

 class A  extends  Thread
{
     public void run ( )
    {
        System.out.println("thread A started");
    for(int i=1; i<=5; i++)
          {
            System.out.println(" \t from thread A: i= "+i);
           }
          System.out.println("exit from A");
     }
}
class B  extends  Thread
{
      public void run ( )
      {
        System.out.println("thread B started");
      for(int j=1; j<=5; j++)
        {
         System.out.println("\t from thread B: j="+j);
        }
        System.out.println("exit from B");
      }
}
class  C  extends  Thread
{
       public void run ( )
        {
        System.out.println("thread C started");
            for(int k=1; k<=5; k++)
              {
                 System.out.println(" \t from thread C: k="+k);
               }
            System.out.println(" exit from C ");
         }
}
class ThreadPriority
{
    public  static  void   main(String args[ ] )
    {
        A  threadA = new  A(  );
        B  threadB = new  B(  );
        C  threadC = new  C(  );
        threadC.setPriority(Thread.MAX_PRIORITY);
        threadB.setPriority(threadA.getPriority(  )+5);
        threadA.setPriority(Thread.MIN_PRIORITY);
      
        System.out.println("start thread A");
        threadA.start(  );
      
        System.out.println("start thread B");
        threadB.start(  );

        System.out.println("start thread C");
        threadC.start(  );

        System.out.println("end of main thread");
    }
}

----------------------------------------------------------
Output:
start thread A
start thread B
thread A started
         from thread A: i= 1
thread B started
         from thread B: j=1
start thread C
         from thread B: j=2
         from thread A: i= 2
end of main thread
         from thread B: j=3
thread C started
         from thread A: i= 3
         from thread C: k=1
         from thread B: j=4
         from thread C: k=2
         from thread A: i= 4
         from thread C: k=3
         from thread B: j=5
         from thread C: k=4
         from thread A: i= 5
         from thread C: k=5
exit from B
 exit from C
exit from A

 ---------------------------------------------------------

9) Write a java program for Applets to draw the Smiley face ?


 Program:
import java.awt.*;
import java.applet.*;
public  class  Smiley  extends  Applet
{
      public void paint(Graphics g)
        {
              
                Font f = new  Font("Helvetica", Font.BOLD,20);
                g.setFont(f);
                g.drawString("Keep Smiling!!!",50,30);
                g.drawOval(60,60,200,200);
                g.fillOval(90,120,50,20);
                g.fillOval(190,120,50,20);
                g.drawLine(165,125,165,175);
                g.drawArc(110,130,95,95,0,-180);
        }

1) Save this program as  Smiley .java then compile it with  javac  Smiley .java
2)  After successful compilation Smiley.class file will be created .
3) Now open another text file and type the following html program with applet tag.
 HTML  Program:
<html>
            <applet
                          code = "
Smiley .class"
                          width = "400"
                          height = "200">
           </applet>
</html>

4) Save as Smiley .html file in the present directory.
5) Goto command prompt and execute the html file like below
      D:\current directory> appletviewer Smiley.html
6) Then output will be displayed as below.








10) Write a java program for Applets to accept two values from text fields then perform sum operation display the result?

import java.awt.*;

import java.applet.*;

public class Userin extends Applet

{

                TextField text1,text2;

                public void init( )

                  {

                                text1=new TextField( 8);

                                text2=new TextField( 8);

                                add( text1);

                                add( text2);

                                text1.setText( "0");

                                text2.setText( "0");

           }

                public void paint( Graphics g)

                  {

                                int x=0,y=0,z=0;

                                String s1,s2,s;

                                g.drawString( "input a number in each box",10,50);

                                   try

                                                {

                                                  s1=text1.getText( );

                                                  x=Integer.parseInt( s1);

                                                  s2=text2.getText( );

                                                  y=Integer.parseInt( s2);

                                                }

                                   catch( Exception ex)

                                     {

                       }

                                z=x+y;

                                s=String.valueOf( z);

                                g.drawString( "The sum is",10,75);

                                g.drawString( s,100,75);
                   }
               
}
1) Save this program as  Userin .java then compile it with  javac  Userin.java
2)  After successful compilation Userin.class file will be created .
3) Now open another text file and type the following html program with applet tag.
 HTML  Program:
<html>
            <applet
                          code = "Userin.class"
                          width = "400"
                          height = "200">
           </applet>
</html>

4) Save as Userin.html file in the present directory.
5) Goto command prompt and execute the html file like below
      D:\current directory> appletviewer  Userin.html
6) Then output will be displayed as below.





11) Write a java program which illustrate the implementation of multiple inheritance using interfaces in Java ?
interface vehicleone
{
            int  speed=70;
            public void distance( );
}

interface vehicletwo
{
            int distance=100;
            public void speed( );
}

class Vehicle  implements vehicleone,vehicletwo
{
            public void distance( )
        {
                        int  distance=speed*10;
                        System.out.println("Distance travelled is "+distance);
            }
            public void speed( )
        {
                        int speed=distance/5;
                System.out.println("Speed is: "+speed);
            }
}

class MultipleInterface
{
            public static void main(String args[ ])
        {
                        System.out.println("Vehicle");
                Vehicle  obj = new  Vehicle( );
                        obj.distance();
                        obj.speed( );
            }
}

Output:
Vehicle
Distance travelled is 700
Speed is: 20


12)Write a program to illustrate a) Method Overloading & b) Method Overriding methods in Java?
Program for a) Method Overloading:
class  Sum
   {
      void add(int a, int b)
         {
            System.out.println("Sum of two="+(a+b));
          }

    void add(int a, int b,int c)
         {
            System.out.println("Sum of three="+(a+b+c));
          }
   }
class  ExOverloading
   {
       public static void main(String args[ ])
        {
            Sum s=new Sum( );
            s.add(10,15);
            s.add(10,20,30);
         }
    }

Output:-
Sum of two = 25
Sum of three = 60

Program for b) Method Overriding:
class  Square
    {
       void cal(double x)
           {
              double square = (x * x);
              System.out.println("square value=" + square);
           }
    }
class  SquareRoot  extends  Square
    {
       void  cal(double x)
         {
                double sqrt = Math.sqrt(x);
                System.out.println("square root="+sqrt);
         }
     }
class ExOverriding
     {
        public static void main(String args[ ])
          {
            Square s=new Square( );
            SquareRoot sr = new SquareRoot( );
            s.cal(10);
            sr.cal(10);            
           }                  
     }

Output:-
square value=100.0
square root=3.1622776601683795


*****

Java Lab Viva Questions & Answers

1)      Who invented the java programming?
Ans: James Gosling in the year 1991. Initially java was called as Oak, later changed to java.
2)      Is pointers are supported in java?
Ans: No, java does not support the pointers. Because they creates confusion for a programmer.
3)      What is the difference between a function and a method?
Ans: A method is a function that is written in a class. We do not have functions in java, instead we have methods.
4)      Is java a purely object oriented language or not?
Ans: Java is a purely object oriented language because here everything represented in a class and objects.
5)      What is an object?
Ans: An object is anything that really exists in the world and differ from others. Example: a pen, a table, a dog, a person. etc.
6)      What is a class?
Ans: A group of objects exhibits same behavior (properties + actions) will come under the same group called a class.
7)      What is a garbage collector?
Ans: Garbage collector is invoked automatically to free the memory,by deleting the unused objects. Or by calling gc( ) method of System class.
8)      What is a JVM?
Ans: JVM full form is Java Virtual Machine, it a heart the entire java program execution process. It converts the .class (byte code) file into machine language.
9)      What is a Heap memory?
Ans: The area where objects are created.
10)  What is JIT compiler?
Ans: JIT compiler is the part of JVM which increase the speed of execution of a Java Program.
11)  What is the difference between print( ) and println( ) methods?
Ans: Bothe used to diplay the results on the monitor. Print( ) method displays the result and then retain the cursor in the same line. But println( ) displays the results and then throws the cursor to the next line.
12)  What is the difference between the System.exit(0) and System.exit(1)?
Ans: System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the program because of some error.
13)  On which memory arrays are created in java?
Ans: Arrays are created on dynamic memory by JVM.
14)  Can you call the main( ) of a class from another class?
Ans: Yes, we can call the main( ) method of a class from another class using
         classname.main(String args[ ]).
15)  Is String a class or data type?
Ans: String is a class in java.lang package. But in java, all classes are also considered as data types. So we can take String as a data type also.
16)  What is object oriented approach?
Ans: Object oriented programming approach is a programming methodology to design computer programs using classes and objects.
17)  What is a class?
Ans: A class is a model for creating objects and does not exist physically.
18)  What is a object?
Ans: An object is any thing that exists physically.
19)  Ans: Encapsulation: Wrapping up of data and methods into single unit is known as encapsulation.
20)  Ans: Abstranction: Hiding the unnecessary data from the user and expose only essemtial data is called abstraction.
21)  Ans: Inheritance: Aquiring the properties of parent class to child class is called inheritance.
22)  Ans: Polymorphism: Its came from two greek words ‘poly’ meAns many and ‘morphos’ meAns forms. Thus polymorphism represent the ability to act several different forms.
23)  What is a constructor?
Ans: A constructor is similar to a method, used to initialize the instance variables. The constructor name and class name should be same. A constroctor is called concurrently when the object creation is going on.
24)  What is constructor overloading?
Ans: Writing two or more constructors with the same name but with difference in the parameters is called constructor overloading.
25)  What are static methods?
Ans: Static methods are methods which declared by static keyword. This methods will be executed without creating/ using the objects.
26)  What is a recursion?
Ans: A method calling itself is known as recursive method.
27)  What is the advantage of inheritance?
Ans: In inheritance, a programmer reuses the super class code without rewriting it.
28)  Is java supports multiple inheritance?
Ans: No, Java does not support the multiple inheritance. But we can achieve this indirectly by using multiple interfaces.
29)  What is method signature?
Ans: Method signature represents the method name along with method parameters.
30)  What is method overloading?
Ans: Writing two or more methods with the same name in the same class, but with difference in the parameters is called method overloading.
31)  What is method overriding?
Ans: Writing two or more methods in super and sub classes such that methods have the same method signature is called method overriding.
32)  What is the static polymorphism?
Ans: The polymorphism exhibited at compilation time is called static polymorphism.
33)  What is abstract method?
Ans: An abstract method is a method withoud method body.
34)  What is abstract class?
Ans: An abstract class is a class that contains zero or more abstract methods.
35)  What is an interface?
Ans: An interface is a specication of method prototype. All the methods of the interface are public and abstract.
36)  Why the methods of interface are public and abstract by default?
Ans: Interface methods are public and abstract since they should be available to third party vendors to provide implementation.
37)  What is a package?
Ans: A package represents a directory that contains related group of classes and interfaces.
38)  What is a garbage collector? Or gc( ) method?
Ans: garbage collector of JVM will delete any unused variables and unreferenced objects from memory using gc( ) method.
39)  What is CLASSPATH?
Ans: The CLASSPATH is an environment variable that tells the java compliler where to look for class files to import.
40)  What is JAR files?
Ans: A Java Archive File (JAR) is a file that contains compressed version of several .class files.
41)  What is super class of all exceptions in java?
Ans: Exception is the super class of all exceptions in java.
42)  What is the difference between throws and throw?
Ans: throws clause is used when the programmer does not want to hangle the exception. throw clause is used when the programmer wants  to throw an exception and to handle it using catch block.
43)  What is a wrapper classes?
Ans: A wrapper class is a class whose object wraps or contains a primitive data type. Wrapper classes will convert primitive data types into objects.
44)  What is boxing?
Ans: Converting a primitive datatype into an object is called ‘boxing’.
45)  What is unboxing?
Ans: Converting an object into its corresponding primitive datatype is called unboxing.
46)  What is the advantage of stream concept?
Ans: Streams are mainly useful to move data from one place to another palce.
47)  What is a thread?
Ans: A thread represents a separate path of execution of a group of statements. Or a thread is a peace of process.
48)  Which tread always runs in a java program by defualt?
Ans: main( ) method as a thread.
49)  What is multi threading?
Ans: Multiple threads are executed by the processor simultaneously. This is called multi threading.
50)  What is Thread synchronization?
Ans: When a thread is already acting on an object, preventing any other thread from acting on the same object is called ‘Thread synchronization’ or ‘Thread safe’.
51)  What is the default priority of a thread?
Ans: When a thread is created, by default its priority will be 5.
52)  What is a deamon thread?
Ans: A daemon thread is a thread that executes continuously.
53)  What is an applet?
Ans: An applet represents Java byte code embedded in a web page.
54)  URL full form: Uniform Resource Locator.
55)  DSN full form: Data Source Name
56)  What is a platform independent?
Ans: The programs which run on any operating system is called platform independent. Our java programs are platform independent.
57)  What is Graphics class?
Ans: java’s Graphics class includes many methods to draw different types of shapes from simple lines to polygons and different fonts text. Using pant( ) method.
58)  Tell me applications of oop?
Ans: We can use in real time applications, in simulation and modeling, in neural networks and parallal programming.
59)  Tell me some java features?
Ans: compiled and interpreted, platform independent and portable, object oriented, robust and secure, multi threaded and interactive, high performance.
60)  What is the JIT compiler?
Ans: JIT meAns Just In Time compiler.

Note: There is no limited questions for viva voce. You must prepare Lab programs as well as all concepts of OOP Using Java subject.

Submit your Java Lab records and Lab observations on or before 4th October 2017 without fail.
Syllabus
II YEAR IV SEMESTER
Paper-IV : DATA STRUCTURES
Course Objectives
To introduce the fundamental concept of data structures and to emphasize the importance of data structures in developing and implementing efficient algorithms..

UNIT - I
Concept of Abstract Data Types (ADTs)- Data Types, Data Structures, Storage Structures, and   File  Structures, Primitive and Non-primitive Data Structures, Linear  and   Non-linear  Data Structures.
Linear Lists – ADT, Array and Linked representations, Pointers.         
Arrays – ADT, Mappings, Representations, Sparse Matrices,   Sets – ADT, Operations
Linked Lists: Single Linked List, Double Linked List, Circular Linked List , applications

UNIT - II
Stacks: Definition, ADT, Array and Linked representations, Implementations and Applications
Queues: Definition, ADT, Array and Linked representations, Circular Queues, Dequeues, Priority Queues,  Implementations and Applications.

UNIT - III
Trees: Binary Tree, Definition, Properties, ADT, Array and Linked representations,   Implementations   and Applications. Binary Search Trees (BST) – Definition, ADT, Operations and Implementations, BST Applications. Threaded Binary Trees, Heap trees.

UNIT - IV
Graphs – Graph and its Representation, Graph Traversals, Connected Components, Basic Searching Techniques, Minimal Spanning Trees

UNIT - V
Sorting and Searching: Selection, Insertion, Bubble, Merge, Quick, Heap sort, Sequential and Binary Searching.

REFERENCE BOOKS
1.      D S Malik, Data Structures Using C++, Thomson, India Edition 2006.
2.      Sahni S, Data Structures, Algorithms and Applications in C++, McGraw-Hill, 2002.
3.      SamantaD, Classic Data Structures, Prentice-Hall of India, 2001.
4.      Heilman G I,. Data Structures and Algorithms with Object-Oriented Programming,  Tata McGraw-l lill. 2002. (Chapters I and 14).
5.      Tremblay  P, and Sorenson P G, Introduction to Data Structures  with  Applications, Tata McGraw-Hill,




LAB NAME: DATA  STRUCTURES  USING  JAVA  LAB

1.Write a Program to implement the Linked List operations?
Program:
import java.util.*;
public class LinkedListDemo
 {
     public static void main(String args[])
      {
         LinkedList ll = new LinkedList();// Here ll is a object to LinkedList class
         ll.add("Virat");
         ll.add("Dhoni");
         ll.add("Rahane");
         ll.add("Jadeja");
         ll.add("Vijay");
         System.out.println("Linked List Content: \n" +ll);
         ll.addFirst("Ashwin");
         ll.addLast("Zaheer");
         System.out.println("LinkedList Content after addition: \n" +ll);
      
         ll.removeFirst();
         ll.removeLast();
         System.out.println("LinkedList after deletion of first and last element: \n" +ll);
         ll.add(1, "Karan");
         ll.remove(2);
         System.out.println("Final Content: \n" +ll);
     }
}
Save this program with LinkedList.java.
At command prompt:
D:\JDS Programs>javac -Xlint LinkedListDemo.java
D:\JDS Programs>java LinkedListDemo
OUTPUT:
Linked List Content:
[Virat, Dhoni, Rahane, Jadeja, Vijay]
LinkedList Content after addition:
[Ashwin, Virat, Dhoni, Rahane, Jadeja, Vijay, Zaheer]
LinkedList after deletion of first and last element:
[Virat, Dhoni, Rahane, Jadeja, Vijay]
Final Content:
[Virat, Karan, Rahane, Jadeja, Vijay]

----------------------------------------------------------------------------------------------------
2) Write a Program to implement the Stack operations using an Array?
Program:
import java.io.*;
class MyStack
 {
    private int top;
    private int item[ ];

    MyStack(int size)
     {
        top = -1;
        item = new int[size];
     }

    void pushItem(int data)
     {
           if (top == item.length - 1)
             {
                 System.out.println("Stack is Full");
             }
           else
           {
                item[++top] = data;
               System.out.println("Pushed Item :" + item[top]);
           }
     }

    void popItem( )
      {
        if (top < 0)
           {
               System.out.println("Stack is Empty");
           }
       else
          {
              top--;
              System.out.println("Pop Item : " + item[top+1]);
           }
      }
  public void display( )
     {
       for(int i =top; i>=0;i--)
            System.out.println(item[i]);
    }

}
class StackExample
{
    public static void main(String[] args) throws IOException
    {
        MyStack stk = new MyStack(10);
        boolean yes=true;
        int choice;
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
       
        do{
            System.out.println("_________________");
            System.out.println("Menu:");
            System.out.println("_________________");
            System.out.println("1.Push\n2.Pop\n3.Display\n4.Exit\n\nEnter Choice");
            choice = Integer.parseInt(is.readLine());
            switch(choice)
            {
                case 1: System.out.println("Enter Push Item: ");
                            stk.pushItem(Integer.parseInt(is.readLine()));
                            break;
                case 2: stk.popItem( );break;
                        case 3: System.out.println("Stack elements:");
                        stk.display( ); break;
                case 4: yes = false;break;
                default: System.out.println("Invalid Choice");
            }
        }while(yes= =true);
     }
}
Save this program with StackExample.java.
At command prompt:
D:\JDS Programs>javac  StackExample.java
D:\JDS Programs>java  StackExample
Output:
___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
1
Enter Push Item :
77
Pushed Item : 77
___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
1
Enter Push Item :
66
Pushed Item : 66
___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
3
Stack element
6677
77
___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
2
Pop item:66

___________________
Menu:
___________________
1.Push
2.Pop
3.Display
4.Exit
Enter Choice
4

-------------------------------------------------------------------------------------------------------
3.Write a Program to implement the Queue operations using an array? (updated)
Program:


class MyQueue
{
        int front;
        int item[ ];
        int rear;
        int temp;
        MyQueue(int size)
          {
                front=-1;
                rear=-1;
                item=new int[size];
           }
        void eQ(int data)
           {
              if (rear==item.length-1)
                 {
                  System.out.println("Queue is full");                      
                  }
               else
               {
                  if (rear= =-1)
                     {
                      front = 0;
                      rear = 0;
                      item[rear] = data;
                     }
                   else if (rear+1<item.length)
                    item[++rear] = data;   
                    System.out.println("Element " + data + " is entered into the Queue ");
                    display();
                }
           }
        public  void  dQ( )
          {
                if(front<0)
                    {
                         System.out.println("Queue is Empty");
                     }
                else
                    {
                      temp=front;
                      front++;
                          System.out.println("Deleted element from the queue is:"+item[temp]);
                          display( );
                        }
            }
        public void display( )
              {
                if(rear >= front)
                   {
                     System.out.println("Elements in the Queue :");
                     for(int i=front;i<=rear;i++)
                            {
                              System.out.println(item[i]);
                    }
               }
            }

     public static void main(String[ ]  args)
        {
              MyQueue q=new MyQueue(5);
              q.eQ(5);
              q.eQ(10);
              q.eQ(15);
              q.eQ(22);
              q.dQ();
              q.dQ();
             q.eQ(30);
             
        }
   }
Save this program with MyQueue.java.
At command prompt:
D:\ JDS Programs>javac MyQueue.java
D:\JDS Programs>java MyQueue
Output:
Element 5 is entered into the Queue
Elements in the Queue :
5
Element 10 is entered into the Queue
Elements in the Queue :
5
10
Element 15 is entered into the Queue
Elements in the Queue :
5
10
15
Element 22 is entered into the Queue
Elements in the Queue :
5
10
15
22
Deleted element from the queue is:5
Elements in the Queue :
10
15
22
Deleted element from the queue is:10
Elements in the Queue :
15
22
Element 30 is entered into the Queue
Elements in the Queue :
15
22
30

---------------------------------------------------------------------------------------------------------------
4.Write Programs to implement the Stack operations using a singly linked list?
Program:
import java.io.*;
class MyNode
{
    int item;
    MyNode next;
    MyNode(int val)
    {
        item = val;
    }
    public void displayNode()
    {
        System.out.println(item );
    }
}

class MyLinkedList
{
    MyNode first;
    boolean isEmpty()
    {
        return (first==null);
    }
    void insert(int val)
    {
        MyNode newNode = new MyNode(val);
        newNode.next = first;
        first = newNode;
    }
    MyNode delete()
    {
        MyNode temp = first;
        first = first.next;
        return temp;
    }
    void display()
    {
        System.out.println("Elements from top to bottom");
        MyNode current = first;
        while(current != null)
        {
            current.displayNode();
            current = current.next;
        }
        System.out.println("");
    }
    
}

class MyStack
{
    MyLinkedList list;
    MyStack() 
    {  
        list = new MyLinkedList();
    }
    void push(int num)
    {
        list.insert(num);
    }
    MyNode pop()
    {
        return list.delete();
    }
    boolean isEmpty()
    {
        return list.isEmpty();
    }
    void displayStack()
    {
        System.out.print("Stack : ");
        list.display();
    }
}

class StackLinkedList
{
    public static void main(String[] args) throws IOException
    {
        MyStack s= new MyStack();
        s.push(10);
        s.push(20);
        s.displayStack();
        s.push(30);
        s.push(40);
        s.displayStack();
        s.pop();
        s.pop();
        System.out.println("Two elements are popped");
        s.displayStack();
    }
}
Save this program with StackLinkedList.java.
At command prompt:
D:\ JDS Programs>javac StackLinkedList.java
D:\JDS Programs>java StackLinkedList
Output:
Stack : Elements from top to bottom
20
10

Stack : Elements from top to bottom
40
30
20
10

Two elements are popped
Stack : Elements from top to bottom
20
10
-----------------------------------------------------------------------------------------------------------

5.Write Programs to implement the Queue operations using a singly linked list?
Program:
import java.io.*;
class MyNode
 {
    int item;
    MyNode next;
    MyNode(int val)
      {
        item = val;
      }
    void  displayNode( )
      {
        System.out.print(item+"   " );
       }
  }
class MyLinkedList
   {
      MyNode start;
      MyNode end;
      boolean isEmpty( )
      {
        return start==null;
      }
     void insertEnd(int val)
       {
         MyNode newNode = new MyNode(val);
         if( isEmpty( ) )
            start = newNode;
         else
            end.next = newNode;
         end = newNode;
       }
     int deleteStart( )
       {
           int temp = start.item;
           if(start.next == null)
               end = null;
           start = start.next;
           return temp;
      }
    void displayList( )
      {
         MyNode current = start;
         while(current != null)
          {
            current.displayNode();
            current = current.next;
         }
        System.out.println("  ");
      }
}
class MyQueue
  {
     MyLinkedList list;
     MyQueue( )
     {
        list= new MyLinkedList( );
     }
    boolean isEmpty( )
     {
        return list.isEmpty( );
     }
    void insert(int k)
     {
        list.insertEnd(k);
     }
    int delete( )
     {
        return list.deleteStart( );
     }
    void display( )
      {
        System.out.print("Queue [start to end]: ");
        list.displayList( );
     }
  }
class QueueLinkedList
  {
      public static void main(String[ ] args)
     {
        MyQueue demo = new MyQueue( );
        System.out.println("Inserting two elements into the queue");
        demo.insert(10);
        demo.insert(20);
        demo.display( );
        System.out.println("Inserting one more element into the queue at the end");
        demo.insert(30);
        demo.display( );
        System.out.println("Deleting one element from the front");
        demo.delete( );
        demo.display( );
    }
}
Save this program with QueueLinkedList.java.

At command prompt:
D:\ JDS Programs>javac  QueueLinkedList.java
D:\JDS Programs>java  QueueLinkedList

Output:
Inserting two elements into the queue
Queue [start to end]: 10   20
Inserting one more element into the queue at the end
Queue [start to end]: 10   20   30
Deleting one element from the front
Queue [start to end]: 20   30

--------------------------------------------------------------------------------------------------------


6) Write a Java program for implementation of QuickSort?
Program:
class QuickSort
{
            /* This function takes last element as pivot, places the pivot element at its correct
            position in sorted array, and places all smaller (smaller than pivot) to left of
            pivot and all greater elements to right of pivot */

            int partition(int arr[ ], int low, int high)
            {
                        int pivot = arr[high];
                        int i = (low-1);     // index of smaller element
                        for (int j=low; j<high; j++)
                        {
                                    // If current element is smaller than or  equal to pivot
                                    if (arr[ j] <= pivot)
                                    {
                                                i++;
                                                // swap arr[ i] and arr[ j]
                                                int temp = arr[i];
                                                arr[i] = arr[ j];
                                                arr[ j] = temp;
                                    }
                        }
                        // swap arr[i+1] and arr[high] (or pivot)
                        int temp = arr[i+1];
                        arr[i+1] = arr[high];
                        arr[high] = temp;
                        return  i+1;
            }
            /* The main function that implements QuickSort( )
            arr[ ] --> Array to be sorted,
            low --> Starting index,
            high --> Ending index */
            void  sort(int arr[ ], int  low, int  high)
            {
                        if (low < high)
                        {
                                    /* pi is partitioning index, arr[pi] is now at right place */
                                    int pi = partition(arr, low, high);
                                    // Recursively sort elements before partition and after partition
                                    sort(arr, low, pi-1);
                                    sort(arr, pi+1, high);
                        }
            }

            /* A utility function to print array of size n */
            static void  printArray(int arr[ ])
            {
                        int n = arr.length;
                        for (int i=0; i<n; ++i)
                                    System.out.print(arr[i]+" ");
                        System.out.println( );
            }

            public  static  void  main(String args[])
            {
                        int arr[ ] = {10, 7, 8, 9, 1, 5};
                        int n = arr.length;

                        QuickSort ob = new QuickSort( );
                        ob.sort(arr, 0, n-1);

                        System.out.println("Sorted Array:");
                        printArray(arr);
            }
}
------------------------------------------------------
Save this program with QuickSort.java
At command prompt:
D:\ JDS Programs>javac  QuickSort.java
D:\JDS Programs>java  QuickSort
Press enter key
Output:
Sorted Array:
          10

------------------------------------------------------------------------------------------------------------------


7) Write a Java program for implementation of Binary Search?
Program:
class  BinarySearchExample
{ 
  public static void  binarySearch(int arr[ ], int  first, int  last, int  key)
  { 
    int  mid = (first + last)/2; 
    while( first <= last )
     { 
         if ( arr[mid] < key )
         { 
           first = mid + 1;    
          }
         else if ( arr[mid] = = key )
         { 
            System.out.println("Element is found at index: " + mid); 
             break; 
          }
           else
               { 
                  last = mid - 1; 
                } 
      mid = (first + last)/2; 
   } 
   if ( first > last )
   { 
      System.out.println("Element is not found!"); 
   } 
 } 
  public static void main(String args[ ])
  { 
        int  arr[ ] = {10,20,30,40,50}; 
        int  key = 40; 
        int  last=arr.length-1; 
        binarySearch(arr,0,last,key);    
   } 
}
------------------------------------------------------------------------

Save this program with BinarySearchExample.java
At command prompt:
D:\ JDS Programs>javac  BinarySearchExample.java
D:\JDS Programs>java  BinarySearchExample
Press enter key
Output:

 Element is found at index: 3
------------------------------------------------------------------------------------------------------


8) Write a Java program for implementation of Linear Search (or) Sequential Search?
Program:
public class LinearSearchExample
{   
    public static int linearSearch(int[] arr, int key)
    {   
        for(int i=0;i<arr.length;i++)
        {   
            if(arr[i] == key)
              {   
                return i;   
              }   
        }   
        System.out.println("searching element was not found in the array"); 
        return -1;
    }   
    public static void main(String a[ ])
     {   
        int  a1[ ]= {10,20,30,50,70,90};   
        int  key = 70;   
        System.out.println(key+" is found at index: "+linearSearch(a1, key));   
        
}
-------------------------------------------------------------------------
Save this program with StackLinkedList.java.
At command prompt:
D:\ JDS Programs>javac LinearSearchExample.java
D:\JDS Programs>java LinearSearchExample

Output:
70  is found at index: 4
--------------------------------------------------------------------------------------------------------


9) Write a Java program to implement the Selection Sort?
/* Following Java Program ask to the user to enter the array size and array elements, then it will sort the array in ascending order and display the sorted array: */
/* Java Program Example - Selection Sort */
           
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int size, i, j, temp;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
        
       System.out.print("Enter Array Size : ");
       size = scan.nextInt();
        
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
        
       System.out.print("Sorting Array using Selection Sort Technique:\n");
       for(i=0; i<size; i++)
       {
           for(j=i+1; j<size; j++)
           {
               if(arr[i] > arr[j])
               {
                   temp = arr[i];
                   arr[i] = arr[j];
                   arr[j] = temp;
               }
           }
       }
        
       System.out.print("Now the Array after Sorting is :\n");
       for(i=0; i<size; i++)
       {
           System.out.print(arr[i]+ "  ");
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output:
---------------------------------------------------------------------
Output:
Enter Array Size : 6
Enter Array Elements : 12
98
23
87
45
76
Sorting Array using Selection Sort Technique:
Now the Array after Sorting is:
12    23   45   76   87   98
-----------------------------------------------------------------------------------------------------------------------

10) Write a Java program to implement the Insertion Sort?
/*Following Java Program ask to the user to enter array size and array elements to sort the array using the insertion sort technique, then display the sorted array on the screen:*/
/* Java Program Example - Insertion Sort */
           
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int size, i, j, temp;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
        
       System.out.print("Enter Array Size : ");
       size = scan.nextInt();
        
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
        
       System.out.print("Sorting Array using Insertion Sort Technique:\n");
       for(i=1; i<size; i++)
       {
           temp = arr[i];
           j = i - 1;
           while((temp < arr[j]) && (j >= 0))
           {
               arr[j+1] = arr[j];
               j = j - 1;
           }
           arr[j+1] = temp;
       }
       
       System.out.print("Array after Sorting is : \n");
       for(i=0; i<size; i++)
       {
           System.out.print(arr[i] + "  ");
       }
   }
}
When the above Java Program is compile and executed, it will produce the following output:
------------------------------------------------------------------
Output:
Enter Array Size : 6
Enter Array Elements : 12
98
23
87
45
76
Sorting Array using Insertion Sort Technique:
Now the Array after Sorting is:
12    23   45   76   87   98
--------------------------------------------------------------------------------------------------


Q) Write a Java program to implement the Bubble Sort?
Program:
import java.util.Scanner;
class BubbleSort
{
     public static void main(String   args[ ])
      {
         int n, i, j, swap;
         Scanner in = new Scanner(System.in);
         System.out.println("Enter number of integers to sort:");
         n = in.nextInt();
         int array[ ] = new int[n];
         System.out.println("Enter " + n + " elements:");

        for (i = 0; i < n; i++)
         {
            array[i] = in.nextInt( );
          }
       for (i = 0; i < ( n - 1 ); i++)
       {
          for (j = 0; j < n - i - 1; j++)
             {
                if (array[ j] > array[ j+1])             /* For descending order use < */
                  {
                     swap       = array[j];
                     array[ j]   = array[j+1];
                     array[ j+1] = swap;
                  }
              }
        }
       System.out.println("Sorted list of numbers:");
       for (i = 0; i < n; i++)
         System.out.print("    "+array[i]);
     }
}
-----------------------------------------------------------
Output:
Enter number of integers to sort:
6
Enter  6 elements:
8
4
6
11
3
10
Sorted list of numbers:
    3    4    6    8    10    11
-----------------------------------------------------------------------------





----------------------------------------------------------------------------------------------------------------------------
Previous Semester Related


 OOP USING JAVA - Previous Question Paper



*******

2 comments: