Tuesday, October 23, 2012

JAVA question Bank


Question Bank
Unit - I
2 Marks
  1. Define Object oriented Programming?
i.)          Object oriented programming is a programming methodology that uses ‘objects’ to design applications and computer programs.
ii.)         Since Java is an object oriented programming language it has following features: 
·         Reusability of Code
·         Emphasis on data rather than procedure
·         Data is hidden and cannot be accessed by external functions
·         Objects can communicate with each other through functions
·         New data and functions can be easily added

  1. What is Java ?
JAVA- Just Another Virtual Architecture
          Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++. Java was given birth at Sun Microsystems, Inc. in 1991. Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc in 23 March 1995. It was developed to provide a platform-independent programming language.

  1. What is the Java Virtual Machine? What is its role?
                Java was designed with a concept of ‘write once and run everywhere’. At the heart of the Java platform lies in the Java Virtual Machine, or JVM. Most programming languages compile source code directly into machine code, suitable for execution on particular microprocessor architecture. The difference with Java is that it uses bytecode - a special type of machine code.

  1. When to use pipe stream for performing I/O operation? Or What is meant by Piped Streams?
Pipes are used to channel the output from one program (or thread) into the input of another.

  1. What is the storage structures used to represent byte code?
Various systems may often be stored in separate files, similar to object module, but distinguishably during execution. The byte code gets its name from a set of instructions called one-byte opcodes.

  1. What is the use of thread?
    Thread are used to provide multi-programming environment.

  1. Give the syntax and use of any four classes in swing?
JFrame classes
                                         JFrame frame = new JFrame("JFrame Source Demo");
                         frame.addWindowListener(new WindowAdapter(){public void 
                                                                 windowClosing(WindowEvent e) { System.exit(0);}});       
 
  1. Write a java program to read an integer and to display the same.
import java.io.*;
import java.lang.*;
public class BinaryToDecimal{
public static void main(String[] args) throws IOException{
                BufferedReader bf = new BufferedReader(new  InputStreamReader(System.in));
                System.out.println("Enter the Binary value:");
                String binaryNumber = bf.readLine();
                int decimalNumber = Integer.parseInt(binaryNumber,2);
                System.out.println("Binary number converted to decimal number");
                System.out.println("Decimal number is : " + decimalNumber);
}
}

  1. What are the benefits in using swings compared to awt?
                    1. Pluggable Look and Feel
    2. Swing is more lightweight than AWT
    3. Components can be bound to keyboard events to react to keystrokes.
    4. Built on the MVC model
    5. Better support for multi-threading
 
  1. How are the strings transferred between native methods in Java?
The class JNIString to transfer strings between Java and the native code.

  1. Write a Java statement that tests if a thread is alive.
class RThread implements Runnable
{
        Thread t;
        RThread (String msg)
        {
                t = new Thread (this, msg);
                t.start();
        }
        public void run()
        {
                for (int i=0;i<5;i++)
                {
                        try
                        {
                                 System.out.println(Thread.currentThread()+" : "+i);
                                 t.sleep(100);
                        } catch(InterruptedException e){}
                }
        }
}
class T
{
        public static void main(String arg[])
        {
                RThread r1 = new RThread("First");
                RThread r2 = new RThread("Second");
                RThread r3 = new RThread("Third");
                System.out.println("Alive Status of Thread1 :" +r1.t.isAlive());
                System.out.println("Alive Status of Thread2 :" +r2.t.isAlive());
                System.out.println("Alive Status of Thread3 :" +r3.t.isAlive());
        }
}

  1. Define the term Byte code in Java. (or) State the purpose of Byte code.
Byte code is a term which assigned to various forms of instructions framed for efficient execution of a java program, also for the implementation of compilation into machine code.

  1. What is Reflection?
Reflection is a powerful approach to analyses the class at runtime. Reflection uses special kind of java class: Class. The object of the Class type can hold all the information of the class and have getter methods to extract this information.

  1. What is Java I/O?
The Java Input/Output (I/O) is a part ofjava.io package. The java.io package contains a relatively large number of classes that support  input and output operations.
  1. What are the two ways to create a simple Thread?
Java defines two ways in which this can be accomplished:
·         You can implement the Runnable interface.
·         You can extend the Thread class, itself.

  1. Difference between the Applet and Swing.
1) Swing is light weight component while applet is heavy weight component.
2) Applet has no main method, but swings have.
3) Swing have look and feel while Applet Does not provide this facility
4) Swing uses for standalone Applications while Applet needs HTML code for Run the 
    Applet
5) Swing has its own Layout while Applet uses Awt Layout.

      17.  What is Swings in java?
i.) A part of The JFC (Java Foundation Classes)
ii.) Swing Java consists of
·         Look and feel
·         Accessibility
·         Java 2D
·         Drag and Drop, etc

18. What is Java Streaming?
               Java streaming is nothing more than a flow of data. There are input streams that direct data from the outside world from the keyboard, or a file for instance, into the computer; and output streams that direct data toward output devices such as the computer screen or a file. 
             
19. What are Byte streams?
                Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used for example when reading or writing binary data.

20. What are Character streams?
              Character streams, provide a convenient means for handling input and output of characters. They use Unicode, and therefore, can be internationalized.

21. List some Byte Stream supported classes.
·         BufferedInputStream
·         BufferedOutputStream
·         ByteArrayInputStream
·         ByteArrayOutputStream
·         DataInputStream
·         DataOutputStream


      22. List some Character Stream supported classes.
·         BufferedReader
·         BufferedWriter
·         CharArrayReader
·         CharArrayWriter
·         FileReader
·         FileWriter




23. Write note on FileInputStream class.
               The FileInputStream class creates an InputStream that you can use to read bytes from a file. Its two most
        common constructors are
                            FileInputStream(String filepath)
                            FileInputStream(File fileobj)

24. Write note on FileOutputStream class.
                   FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most commonly used
       constructors are
                        FileOutputStream(String filepath)
                        FileOutputStream(File fileobj)
                        FileOutputStream(String  filepath, Boolean append)
        They can throw an IOException or a SecurityException.

       25. What is the use of the class “ByteArrayInputStream”?
                       ByteArrayInputStream is an implementation of an input stream that uses a byte array  as the source. This class as 
              two constructors, each of which requires a byte array to provide the data source:
                            ByteArrayInputStream(byte array[])
                             ByteArrayInputStream(byte array[], int start, int numbytes)

       26. What is an Event?
                  An event is an object that describes a state change in a source. It can be generated as a consequence of a person
             interacting with the elements in a graphical user interface. Some of  the activities that cause events to be generated are
             pressing a button, entering a character via the keyboard, selecting an item in a list and clicking the mouse.
                     
       27. What is an Event Listener?
                    A Listener is an object that is notified when an event occurs. Only the types of events, which are registered with an
              event listener will be received by that listener.

      28. When does an ActionEvent generate?
                     An ActionEvent is generated when a button is pressed, a list-item is double-clicked, or a  menu item is selected.
                   You can obtain the command name for the invoking ActionEvent object by using the  getActionMethod() method.
                           String getActionCommand()
                                 
     29. When is ComponentEvent  generated?
                       A ComponentEvent is generated when the size, position, or visibility of a component  is changed. The
           getComponent() method of ComponentEvent returns the component that  generated the event.

     30. Define Multithread Programming.
                      A multithreaded program contains two or more parts that can run concurrently. Each  part of such program is
           called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of  
            multitasking.

    31. What is Synchronization?
                   When two or more threads need access to a shared resource, they need some way to ensure that the resource will be
            used by only one thread at a time. The process by which this is achieved is called synchronization.

    32. In multithreading, When does a deadlock situation occur?
                      Deadlock situation occurs, when two threads have a circular dependency on a pair of  synchronized objects.
 
    33. What is the need of Thread Priorities?
                     Thread priorities are used by the thread scheduler to decide when each thread be allowed to run. Higher-priority
           threads get more CPU time than lower-priority threads. To set a thread’s priority, use the setPriority() method, which is
           a member of Thread.
          
    34. What is the use of Layout Managers in Swing?
       The Layout Managers are used to place the components in a predefined manner relative  to each other.  The  
layout manager puts the components in a queue and arranges them one after  the other rather than placing the
components according to the coordinates.  This helps in  achieving platform independence.




    35. List some Layout Managers supported by Swing.
     The most common Layout Managers supported by Swing are
·         Box Layout
·         Grid Layout
·         GridBag Layout
·         Border Layout


16 Marks

  1. Explain Byte stream and Data stream with their applicability.(8)
Definition of Byte stream and Data stream (3),
Using of Byte stream and Data Input and Output stream (3),
Example program (2),

  1. How to extract the methods and constructors defined in a class using reflection in Java.  (8)
(or) What is reflection? Explain its use. (8)  (or) Explain Dynamic reflexive classes. (8)
Definition of Reflection (3)
Uses of Reflection (3)
Example program (2)

  1. Explain the implementation of thread synchronization in Java.(10)
Definition of Multi-Threading (1)
List out the Multi-Threading Concepts (1)
Thread Synchronization using Synchronized Block With Example (4)
Thread Synchronization using Synchronized Method With Example (4)

  1. Write a Java program for Reading and Writing the data from a file. (8)
import java.io.*;
class ReadWriteData
{
                public static void main(String args[])
                {
                                int ch=0;
                                int[] numbers = {12,8,13,29,50};
                                try
                                {
                                                System.out.println("1. Write Data");
                                                System.out.println("2. Read Data");     
                                                System.out.println("Enter your choice ");
                                                BufferedReader br=new BufferedReader(new
                                                                                                                   InputStreamReader(System.in));
                                                ch=Integer.parseInt(br.readLine());
                                                switch(ch)
                                                {
                                                                case 1:         
                                                                                DataOutputStream out =new DataOutputStream                      
                                                                                     (new FileOutputStream("datafile.txt"));
                                                                                for (int i=0; i < numbers.length; i++)
                                                                                {
                                                                                                out.writeInt(numbers[i]);
                                                                                }
                                                                                System.out.print("write successfully");   
                                                                                out.close();           
                                                                case 2:
                                                                                DataInputStream in =new DataInputStream                             
                                                                                        (new FileInputStream("datafile.txt"));
                                                                                while (true)
                                                                                {
                                                                                                System.out.print(in.readInt());
                                                                                }
                                                                default:
                                                                              System.out.println("Invalid choice");     
                                                }
                                }
                                catch(IOException e)
                                {
                                                System.out.println(e.getMessage());
                                }             
                }
}

  1. Write a program in Java Applet  for dynamically changing the color of Text using Multithreading. (8)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class FontAnimation extends Applet implements ActionListener
{
                TextField text=new TextField(20);
                TextField red=new TextField(20);
                TextField gr=new TextField(20);
                TextField blue=new TextField(20);
                Button b1=new Button("Apply");
                String str="Hello";
                int size=10;
                Font f;
                boolean inc=true;
                int r,g,b;
                Color fcolor;
                public void init()
                {
                                add(new Label("Enter Text to animate here"));
                                add(text);
                                add(new Label("Enter value for Red Color here"));
                                add(red);
                                red.setText("0");
                                add(new Label("Enter value for Green Color here"));
                                add(gr);
                                gr.setText("0");
                                add(new Label("Enter value for Blue Color here"));
                                add(blue);
                                blue.setText("0");
                                add(b1);
                                b1.addActionListener(this);
                }
                public void actionPerformed(ActionEvent e)
                {
                                if(e.getSource()==b1)
                                {
                                                str=text.getText(); if(str=="") str="Hello";
                                                r=Integer.parseInt(red.getText());
                                                g=Integer.parseInt(gr.getText());
                                                b=Integer.parseInt(blue.getText());
                                                fcolor=new Color(r,g,b);
                                                repaint();
                                }
                 }
                public void paint(Graphics g)
                {
                                f=new Font("Arial",Font.BOLD,size);
                                g.setFont(f);
                                g.setColor(fcolor);              
                                g.drawString(str,50,200);
                                try
                                {
                                                Thread.sleep(500);
                                }
                                catch(Exception e)
                                {
                                                 System.out.println(e.getMessage());
                                }
                                if(inc==true)
                                {
                                                size+=10;
                                                if(size==100)
                                                inc=false;
                                }
                                else
                                {
                                                size-=10;
                                                if(size==10)
                                                inc=true;
                                }
                                repaint();
                }
}


  1. Develop Java swing code for creating student Bio-data form. (8)  
import javax.swing.*;
import java.awt.*;
public class BioData extends JFrame
{
                int i;
                JLabel lbl1,lbl2,lbl3,lbl4,lbl5,lbl6,lbl7,lbl8,lbl9;
                JTextField txt1,txt2;
                JTextArea ta1;
                JCheckBox c1,c2,c3;
                JRadioButton r1,r2;
                JTable t1;
                JList l1;
                JButton b1,b2;
                JComboBox date,month,year;
                String[] colHeads={"Year","Percenatage","School/Degree"};
                Object[][] data={{"","","S.S.L.C"},{"","","H.S.C"},{"","","Bsc"},{"","","MCA"}};
                String[] listData={"English","Tamil","Telegu"};
                String[] mon= {"Jan","Feb","March","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"};
                public BioData(String t)
                {
                                super(t);
                                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                Container cp=getContentPane();
                                cp.setLayout(new BorderLayout());
                                JPanel jp1=new JPanel();
                                JPanel jp2=new JPanel();
                                JPanel jp3=new JPanel();
                                jp1.setLayout(new GridBagLayout());
                                GridBagConstraints gbc=new GridBagConstraints();
                                lbl1=new JLabel("BIO-DATA");
                                jp3.add(lbl1);
                                lbl2=new JLabel("Name");
                                lbl3=new JLabel("Address");
                                lbl4=new JLabel("Tel No");
                                lbl5=new JLabel("Gender");
                                lbl6=new JLabel("Hobbies");
                                lbl7=new JLabel("Educational Qualification");
                                lbl8=new JLabel("Language Known");
                                lbl9=new JLabel("Date Of Birth");
                                date=new JComboBox();
                                for(i=1;i<=31;i++)
                                {
                                                String str=Integer.toString(i);
                                                date.addItem((Object)str);
                                }
                                month=new JComboBox(mon);
                                year=new JComboBox();
                                for(i=1980;i<=2020;i++)
                                {
                                                String str=Integer.toString(i);
                                                year.addItem((Object)str);
                                }
                                txt1=new JTextField(25);
                                txt2=new JTextField(25);
                                ta1=new JTextArea();
                                JScrollPane s1=new JScrollPane(ta1,
                                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
                                b1=new JButton("SUBMIT");
                                b2=new JButton("RESET");
                                c1=new JCheckBox("Reading");
                                c2=new JCheckBox("Music");
                                c3=new JCheckBox("Movies");
                                ButtonGroup b=new ButtonGroup();
                                r1=new JRadioButton("Male");
                                r2=new JRadioButton("Female");
                                b.add(r1);
                                b.add(r2);
                                t1=new JTable(data,colHeads);
                                JScrollPane s=new JScrollPane(t1,
                                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                l1=new JList(listData);
                              l1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                                gbc.insets=new Insets(10,10,10,10);
                                gbc.weightx=1.0;
                                gbc.weighty=1.0;
                                gbc.fill=GridBagConstraints.HORIZONTAL;
                                gbc.gridx=0;         
                                gbc.gridy=0;
                                jp1.add(lbl2,gbc);
                                gbc.gridx=1;
                                gbc.gridy=0;
                                jp1.add(txt1,gbc);
                                gbc.gridx=0;
                                gbc.gridy=1;
                                gbc.gridheight=2;
                                jp1.add(lbl3,gbc);
                                gbc.gridx=1;
                                gbc.gridy=1;
                                gbc.gridheight=2;
                                gbc.weighty=1.0;
                                gbc.fill=GridBagConstraints.BOTH;
                                jp1.add(s1,gbc);
                                gbc.gridx=0;
                                gbc.gridy=3;
                                gbc.gridheight=1;
                                gbc.weighty=0.0;
                                jp1.add(lbl4,gbc);
                                gbc.gridx=1;
                                gbc.gridy=3;
                                jp1.add(txt2,gbc);
                                gbc.gridx=0;
                                gbc.gridy=4;
                                jp1.add(lbl5,gbc);
                                gbc.gridx=1;
                                gbc.gridy=4;
                                jp1.add(r1,gbc);
                                gbc.gridx=2;
                                gbc.gridy=4;
                                jp1.add(r2,gbc);
                                gbc.gridx=0;
                                gbc.gridy=5;
                                jp1.add(lbl9,gbc);
                                gbc.gridx=1;
                                gbc.gridy=5;
                                jp1.add(date,gbc);
                                gbc.gridx=2;
                                gbc.gridy=5;
                                jp1.add(month,gbc);
                                gbc.gridx=3;
                                gbc.gridy=5;
                                jp1.add(year,gbc);
                                gbc.gridx=0;
                                gbc.gridy=6;
                                jp1.add(lbl6,gbc);
                                gbc.gridx=1;
                                gbc.gridy=6;
                                jp1.add(c1,gbc);
                                gbc.gridx=2;
                                gbc.gridy=6;
                                jp1.add(c2,gbc);
                                gbc.gridx=3;
                                gbc.gridy=6;
                                jp1.add(c3,gbc);
                                gbc.gridx=0;
                                gbc.gridy=7;                         
                                jp1.add(lbl7,gbc);
                                gbc.gridx=1;
                                gbc.gridy=7;
                                gbc.weighty=1.0;
                                gbc.gridwidth=gbc.REMAINDER;
                                jp1.add(s,gbc);
                                gbc.gridx=0;
                                gbc.gridy=8;
                                gbc.weighty=0.0;
                                jp1.add(lbl8,gbc);
                                gbc.gridx=1;
                                gbc.gridy=8;
                                gbc.gridwidth=gbc.REMAINDER;
                                jp1.add(l1,gbc);
                                jp2.add(b1);
                                jp2.add(b2);
                                cp.add(jp3,BorderLayout.NORTH);
                                cp.add(jp1,BorderLayout.CENTER);
                                cp.add(jp2,BorderLayout.SOUTH);
                                setSize(500,630);
                                setVisible(true);
                }
                public static void main(String args[])
                {
                                new BioData("BIODATA");
                }
}

  1. Write a java program to read a text file and to count the number of words and sentences. (8)
import java.io.*;
import java.util.*;
class Tip
{
                public static void main(String [] args) throws Exception
                {
                                FileInputStream is = new FileInputStream( "tip.txt" );
                                Scanner scan = new Scanner( is );
                                String tempString = "";
                                int lines = 0;
                                int words = 0;
                                Vector<Integer> wordLength = new Vector<Integer>();
                                while(scan.hasNextLine() == true)
                                {
                                                tempString = scan.nextLine();
                                                lines++;
                                }
                                is.close();
                                is = new FileInputStream( "tip.txt" );
                                scan = new Scanner( is );
                                while(scan.hasNext() == true)
                                {
                                                tempString = scan.next();
                                                wordLength.add(tempString.length());
                                                words++;
                                }
                                System.out.println("Lines : " + lines);
                                System.out.println("Words : " + words);
                                is.close();    
                }
}

  1. Explain the life cycle of thread. (8)
Definition of Thread (3)
Several Stages of Thread (New, Runnable, Waiting, Terminated) (3)
Thread Life Cycle Diagram (2)

  1. What is JNI? Explain its usage. (10)
Definition of JNI (2)
Role of the JNI (4)
Implication of using JNI (4)

  1. Briefly explain the Java i/o stream class hierarchy. (10)
Java I/O streams (2)
Input Stream class Hierarchy and explanation of any one class with example (4)
Output Stream class Hierarchy and explanation of any one class with example (4)

  1. Illustrate the use of Pipes for communication between the threads with suitable java program. (6)
Definition of pipes (2)
PipeReader and PipeWriter Class (2)
Example (2)

  1. Explain Inter-thread communication in java with an example. (8)
Definition of Thread, Multithreading and Inter-thread Communication (3)
Explanation of few methods of Inter-process communication (wait(), notify(), notifyAll()) (3)
Example (2)

  1. What is swing? Explain its features. (8)
Swing Model/view design (2)
Swing Class hierarchy and explanation of any two swing component classes (3)
Example (3)

  1. Explain JVM in detail. (6)
Explanation of Java, JRE, Java API classes, and JVM (3)
Structure of JVM. (3)

No comments:

Post a Comment