1.23.2020

JAVA


A. OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming. They are an abstractionencapsulationinheritance, and polymorphism. Grasping them is key to understanding how Java works. Basically, Java OOP concepts let us create working methods and variables, then re-use all or part of them without compromising security.
List of OOP Concepts in Java
There are four main OOP concepts in Java. These are:
Abstraction. Abstraction means using simple things to represent complexity. We all know how to turn the TV on, but we don’t need to know how it works in order to enjoy it. In Java, abstraction means simple things like objectsclasses, and variables represent more complex underlying code and data. This is important because it lets avoid repeating the same work multiple times.
abstract class Bike
{ 
  abstract void run(); 
} 
class Honda4 extends Bike
{ 
        void run()
           {
                    System.out.println("running safely");
        } 
        public static void main(String args[])
        { 
                                Bike obj = new Honda4(); 
                                obj.run(); 
        } 
} 

Encapsulation. This is the practice of keeping fields within a class private, then providing access to them via public methods. It’s a protective barrier that keeps the data and code safe within the class itself. This way, we can re-use objects like code components or variables without allowing open access to the data system-wide.
Inheritance. This is a special feature of Object Oriented Programming in Java. It lets programmers create new classes that share some of the attributes of existing classes. This lets us build on previous work without reinventing the wheel.
class Professor
{ 
 float salary=40000; 
} 
class Singlelevelinh extends Professor
{ 
        int bonus=10000; 
        public static void main(String args[])
{ 
        Singlelevelinh p=new Singlelevelinh(); 
        System.out.println("Programmer salary is:"+p.salary); 
        System.out.println("Bonus of Programmer is:"+p.bonus); 
 } 
} 
Polymorphism. This Java OOP concept lets programmers use the same word to mean different things in different contexts. One form of polymorphism in Java is method overloading. That’s when different meanings are implied by the code itself. The other form is method overriding. That’s when the different meanings are implied by the values of the supplied variables.
class Vehicle
{ 

         void run()
         {
                    System.out.println("Vehicle is running");
         } 
} 

class Bike2 extends Vehicle
{ 
  void run()
  {
                     System.out.println("Bike is running safely");
          } 

         public static void main(String args[])
        { 
                     Bike2 obj = new Bike2(); 
                    obj.run(); 
        } 
} 

Output:
Bike is running safely



Write the Applet lifecycle with neat diagram?




the life cycle of an applet starts with init() method and ends with destroy() method. Other life cycle methods are start(), stop() and paint(). The methods to execute only once in the applet life cycle are init() and destroy(). Other methods execute multiple times.
init(): The init() method is the first method to execute when the applet is executed. Variable declaration and initialization operations are performed in this method.
       start(): The start() method contains the actual code of the applet that should run. The start() method executes immediately after the init() method. It also executes whenever the applet is restored, maximized or moving from one tab to another tab in the browser.

stop(): The stop() method stops the execution of the applet. The stop() method executes when the applet is minimized or when moving from one tab to another in the browser.

destroy(): The destroy() method executes when the applet window is closed or when the tab containing the webpage is closed. stop() method executes just before when destroy() method is invoked. The destroy() method removes the applet object from memory.

paint(): The paint() method is used to redraw the output on the applet display area. The paint() method executes after the execution of start() method and whenever the applet or browser is resized.

The method execution sequence when an applet is executed is:

init()
start()
paint()


The method execution sequence when an applet is closed is:

stop()
destroy()

import java.awt.*;
import java.applet.*;

/*

<applet code = "Myapp.class" height=300 width=400>
</applet>
*/

public class Myapp extends Applet
{

     public void init()
     {
         setBackground(Color.yellow);
     }
     public void paint(Graphics g)
     {
        g.drawString("hello applets !",50,100);
     }
}

Write the thread lifecycle with neat diagram?
LIFE CYCLE OF A THREAD

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.



New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run when thread is in this state. When a thread lies in the new state, it’s code is yet to be run and hasn’t started to execute.



Runnable State: A thread that is ready to run is moved to runnable state. In this state, a thread might actually be running or it might be ready run at any instant of time. It is the responsibility of the thread scheduler to give the thread, time to run. A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every thread runs for a short while and then pauses and relinquishes the CPU to another thread, so that other threads can get a chance to run. When this happens, all such threads that are ready to run, waiting for the CPU and the currently running thread lies in runnable state.
Blocked/Waiting state:When a thread is temporarily inactive, then it’s in one of the following states:
Blocked
Waiting\\
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s the responsibility of the thread scheduler to reactivate and schedule a blocked/waiting thread. A thread in this state cannot continue its execution any further until it is moved to runnable state. Any thread in these states does not consume any CPU cycle.



A thread is in the blocked state when it tries to access a protected section of code that is currently locked by some other thread. When the protected section is unlocked, the schedule picks one of the thread which is blocked for that section and moves it to the runnable state. Whereas, a thread is in the waiting state when it waits for another thread on a condition. When this condition is fulfilled, the scheduler is notified and the waiting thread is moved to runnable state.

If a currently running thread is moved to blocked/waiting state, another thread in the runnable state is scheduled by the thread scheduler to run. It is the responsibility of thread scheduler to determine which thread to run.
Timed Waiting: A thread lies in timed waiting state when it calls a method with a time out parameter. A thread lies in this state until the timeout is completed or until a notification is received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following reasons:
Because it exists normally. This happens when the code of thread has entirely executed by the program.
Because there occurred some unusual erroneous event, like segmentation fault or an unhandled exception.
A thread that lies in a terminated state does no longer consumes any cycles of CPU.
// Java program to demonstrate thread states
class thread implements Runnable
{
                public void run()
                {
                                // moving thread2 to timed waiting state
                                try
                                {
                                                Thread.sleep(1500);
                                }
                                catch (InterruptedException e)
                                {
                                                e.printStackTrace();
                                }
                               
                                System.out.println("State of thread1 while it called join() method on thread2 -"+
                                                Test.thread1.getState());
                                try
                                {
                                                Thread.sleep(200);
                                }
                                catch (InterruptedException e)
                                {
                                                e.printStackTrace();
                                }             
                }
}

public class Test implements Runnable
{
                public static Thread thread1;
                public static Test obj;
               
                public static void main(String[] args)
                {
                                obj = new Test();
                                thread1 = new Thread(obj);
                               
                                // thread1 created and is currently in the NEW state.
                                System.out.println("State of thread1 after creating it - " + thread1.getState());
                                thread1.start();
                               
                                // thread1 moved to Runnable state
                                System.out.println("State of thread1 after calling .start() method on it - " +
                                                thread1.getState());
                }
               
                public void run()
                {
                                thread myThread = new thread();
                                Thread thread2 = new Thread(myThread);
                               
                                // thread1 created and is currently in the NEW state.
                                System.out.println("State of thread2 after creating it - "+ thread2.getState());
                                thread2.start();
                               
                                // thread2 moved to Runnable state
                                System.out.println("State of thread2 after calling .start() method on it - " +
                                                thread2.getState());
                               
                                // moving thread1 to timed waiting state
                                try
                                {
                                                //moving thread1 to timed waiting state
                                                Thread.sleep(200);
                                }
                                catch (InterruptedException e)
                                {
                                                e.printStackTrace();
                                }
                                System.out.println("State of thread2 after calling .sleep() method on it - "+
                                                thread2.getState() );
                               
                               
                                try
                                {
                                                // waiting for thread2 to die
                                                thread2.join();
                                }
                                catch (InterruptedException e)
                                {
                                                e.printStackTrace();
                                }
                                System.out.println("State of thread2 when it has finished it's execution - " +
                                                thread2.getState());
                }
               
}





Write the collection interface?
(i) Iterable interface (ii) Collection interface (iii) List interface (iv) Queue interface

(v) Set interface (vi) Deque interface ITERABLE INTERFACE
The Java Iterable interface (java.lang.Iterable) is one of the root interfaces of the Java Collections API. A class that implements the Java Iterable interface can be iterated with the Java for-each loop. By iterating I mean that its internal elements can be iterated.
You will see examples of this later in this tutorial.

Implementations of Iterable in Java

There are several classes in Java that implements the Java Iterable interface. These classes can thus have their internal elements iterated via the Java for-each loop.

There are also several Java interfaces that extends the Iterable interface. Classes implementing an interface which extends the Iterable interface thus also implement the Iterable interface. Such classes can also be used with the for-each loop.

The Collection interface extends Iterable, so all subtypes of Collection also implement the Iterable interface. For instance, both the Java List and Set interfaces extend
the Collection interface, and thereby also the Iterable interface. Here is how the Java Iterable interface is defined:


Collections Interface:
A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes.
Need for Collection Framework :
Before Collection Framework (or before JDK 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Vectors or Hashtables. All of these collections had no common interface.
Accessing elements of these Data Structures was a hassle as each had a different method (and syntax) for accessing its members:
Example:
// Java program to show why collection framework was needed import java.io.*; import java.util.*; class Test
{
public static void main (String[] args)
{
Vector<Integer> v = new Vector();
Hashtable<Integer, String> h = new Hashtable(); v.addElement(1);
v.addElement(2); h.put(1,"geeks");
h.put(2,"4geeks"); System.out.println(v.elementAt(0)); System.out.println(h.get(1));
}
}
Output:

LIST INTERFACE:

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.
Elements can be inserted or accessed by their position in the list, using a zero- based index.

A list may contain duplicate elements.

In addition to the methods defined by Collection, List defines some of its own, which are summarized in the following table.
Several of the list methods will throw an Unsupported Operation Exception if the collection cannot be modified, and a Class Cast Exception is generated when one object is incompatible with another.


Sr.
No.
Method & Description
1

void add(int index, Object obj)

Inserts obj into the invoking list at the index passed in the index. Any pre- existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.
2

boolean addAll(-int index, Collection c)

Inserts all elements of c into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten. Returns true if the invoking list changes and returns false otherwise.
3

Object get(int index)

Returns the object stored at the specified index within the invoking collection.
4

int indexOf(Object obj)

Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.
5

int lastIndexOf(Object obj)

Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.
6

ListIterator listIterator( )

Returns an iterator to the start of the invoking list.
7

ListIterator listIterator(int index)

Returns an iterator to the invoking list that begins at the specified index.
8

Object remove(int index)

Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one.
9

Object set(int index, Object obj)

Assigns obj to the location specified by index within the invoking list.
10

List subList(int start, int end)

Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object.
QUEUE INTERFACE IN JAVA


The Queue interface is available in java.util package and extends the Collection interface. The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle. Being an interface the queue needs a concrete class for the declaration and the most common classes are the Priority Queue and Linked List in Java. It is to be noted that both the implementations are not thread safe. Priority Blocking Queue is one alternative implementation if thread safe implementation is needed. Few important characteristics of Queue are:

The Queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It follows FIFO concept.
The Java Queue supports all methods of Collection interface including insertion, deletion etc.
Linked List, Array Blocking Queue and Priority Queue are the most frequently used implementations.
If any null operation is performed on Blocking Queues, Null Pointer Exception is thrown.

SET INTERFACE:

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.


Sr.
No.
Method & Description
1

add( )
Adds an object to the collection.
2

clear( )
Removes all objects from the collection.
3

contains( )
Returns true if a specified object is an element within the
4

isEmpty( )
Returns true if the collection has no elements.
5

iterator( )
Returns an Iterator object for the collection, which may be used to retrieve an object.
6

remove( )
Removes a specified object from the collection.
7

size( )
Returns the number of elements in the collection.


DEQUE INTERFACE:
The Deque interface is a subtype of the Queue interface. The Deque is related to the double-ended queue that supports addition or removal of elements from either end of the data structure, it can be used as a queue (first-in-first-out/FIFO) or as a stack (last- in-first-out/LIFO). These are faster than Stack and LinkedList.
This is the hierarchy of Deque interface in Java:
Few important features of Deque are:
It provides the support of resizable array and helps in restriction-free capacity, so to grow the array according to the usage.
Array deques prohibit the use of Null elements and do not accept any such elements.
Any concurrent access by multiple threads is not supported.
In the absence of external synchronization, Deque is not thread-safe.



 write the collection classes?
(i) Array List (ii) Linked List (iii) Hash set (iv) Linked Hash set
(v)   Tree Set (vi) Stack (vii) Vector (viii) Array Deque
ARRAY LIST IN JAVA

Array List is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
ArrayList inherits AbstractList class and implements List interface.
ArrayList is initialized by a size, however the size can increase if collection grows or shrunk if objects are removed from the collection.
Java ArrayList allows us to randomly access the list.
ArrayList cannot be used for primitive types, like int, char, etc. We need a wrapper class for such cases (see this for details).
ArrayList in Java can be seen as similar to vector in C++.
Constructors in Java ArrayList:
ArrayList(): This constructor is used to build an empty array list
ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from collection c
ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified

LINKED LIST:

Java Linked List class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java Linked List are:

Java Linked List class can contain duplicate elements.
Java Linked List class maintains insertion order.


Java Linked List class is non-synchronized.
In Java Linked List class, manipulation is fast because no shifting needs to occur.
Java Linked List class can be used as a list, stack or queue.

Hierarchy of Linked List class

As shown in the above diagram, Java Linked List class extends Abstract Sequential List class and implements List and Deque interfaces.

Java Linked List Example import java.util.*;
public class LinkedList1{
public static void main(String args[]){


LinkedList<String> al=new LinkedList<String>(); al.add("Ravi"); al.add("Vijay");
al.add("Ravi");
al.add("Ajay");


Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next());
}
}
}





HASHSET CLASS

Java Hash Set class is used to create a collection that uses a hash table for storage. It inherits the Abstract Set class and implements Set interface.

The important points about Java Hash Set class are:

Hash Set stores the elements by using a mechanism called hashing.
Hash Set contains unique elements only.
Hash Set allows null value.
Hash Set class is non-synchronized.
Hash Set doesn't maintain the insertion order. Here, elements are inserted on the basis of their hash code.
Hash Set is the best approach for search operations.
The initial default capacity of Hash Set is 16, and the load factor is 0.75.

LINKEDHASH SET CLASS:

Java Linked Hash Set class is a Hashtable and Linked list implementation of the set interface. It inherits Hash Set class and implements Set interface.

The important points about Java Linked Hash Set class are:

Java Linked Hash Set class contains unique elements only like Hash Set.
Java Linked Hash Set class provides all optional set operation and permits null elements.
Java Linked Hash Set class is non-synchronized.
Java Linked Hash Set class maintains insertion order.


TREESET CLASS

Java Tree Set class implements the Set interface that uses a tree for storage. It inherits Abstract Set class and implements the Navigable Set interface. The objects of the Tree Set class are stored in ascending order.

The important points about Java Tree Set class are:

Java Tree Set class contains unique elements only like Hash Set.
Java Tree Set class access and retrieval times are quiet fast.
Java Tree Set class doesn't allow null element.
Java Tree Set class is non-synchronized.
Java Tree Set class maintains ascending order.

STACK:

Java Collection framework provides a Stack class which models and implements Stack data structure. The class is based on the basic principle of last-in-first-out. In addition to the basic push and pop operations, the class provides three more functions of empty, search and peek. The class can also be said to extend Vector and treats the class as a stack with the five mentioned functions. The class can also be referred to as the subclass of Vector.
This diagram shows the hierarchy of Stack class:




VECTOR CLASS:
The Vector class implements a grow able array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections.
Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index
They are very similar to ArrayList but Vector is synchronised and have some legacy method which collection framework does not contain.
It extends AbstractList and implements List interfaces.
Constructor:
Vector (): Creates a default vector of initial capacity is 10.
Vector (int size): Creates a vector whose initial capacity is specified by size.
Vector (int size, int incr): Creates a vector whose initial capacity is specified by size and increment is specified by incr. It specifies the number of elements to allocate each time that a vector is resized upward.
Vector (Collection c): Creates a vector that contains the elements of collection c.


ARRAY DEQUE CLASS:

Array Deque in Java provides a way to apply resizable-array in addition to the implementation of the Deque interface. It is also known as Array Double Ended Queue or Array Deck. This is a special kind of array that grows and allows users to add or



remove an element from both the sides of the queue. Few important features of Array Deque are as follows:
Array deques have no capacity restrictions and they grow as necessary to support usage.
They are not thread-safe which means that in the absence of external synchronization, Array Deque does not support concurrent access by multiple threads.
Null elements are prohibited in the Array Deque.
Array Deque class is likely to be faster than Stack when used as a stack.
Array Deque class is likely to be faster than Linked List when used as a queue.


write the java input/output
(i) File Output Stream (ii) File Input Stream (iii) Writer (iv) Reader
(v)   File Writer (vi) File Reader
 FILE OUTPUT STREAM
File Output Stream class belongs to byte stream and stores the data in the form of individual bytes. It can be used to create text files. A file represents storage of data on a second storage media like a hard disk or CD. Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one File Output Stream (or other file-writing objects) at a time. In such situations, the constructors in this class will fail if the file involved is already open.
File Output Stream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using File Writer.
Important methods:
void close() : Closes this file output stream and releases any system resources associated with this stream.
protected void finalize() : Cleans up the connection to the file, and ensures that the close method of this file output stream is called when there are no more references to this stream.


void write(byte[] b) : Writes b.length bytes from the specified byte array to this file output stream.
void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array starting at offset off to this file output stream.
void write(int b) : Writes the specified byte to this file output stream.
FILE INPUT STREAM
File Input Stream is useful to read data from a file in the form of sequence of bytes. File Input Stream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using File Reader.
Constructor and Description
File Input Stream(File file) :Creates an input file stream to read from the specified File object.
File Input Stream(File Descriptor fdobj) :Creates an input file stream to read from the specified file descriptor.
File Input Stream(String name) :Creates an input file stream to read from a file with the specified name.

Here is a simple File Input Stream example:




JAVA WRITER

It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality or both.

Fields

Modifier and Type
Fiel d
Description
protected Object
lock
The object used to synchronize operations on this stream.
Constructor


Modifier
Constructor
Description
protected
Writer()
It creates a new character-stream writer whose critical sections will synchronize on the writer itself.
protected
Writer(Object lock)
It creates a new character-stream writer whose critical sections will synchronize on the
given object.


JAVA READER



Java Reader is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int) and close(). Most subclasses, however, will override some of the methods to provide higher efficiency, additional functionality, or both. Some of the


Fields

Modifier and Type
Field
Description
protected Object
lock
The object used to synchronize operations on this stream.
Constructor


Description
protected
Reader()
It creates a new character-stream reader whose critical sections will synchronize on the reader itself.
protected
Reader(Object lock)
It creates a new character-stream reader whose critical sections will synchronize on the given object.


JAVA FILE WRITER CLASS

Java File Writer class is used to write character-oriented data to a file. It is character- oriented class which is used for file handling in java.

Unlike File Output Stream class, you don't need to convert string into byte array because it provides method to write string directly.

Java FileWriter class declaration

Let's see the declaration for Java.io.FileWriter class:

Constructors of File Writer class


Constructor
Description
FileWriter(String file)
Creates a new file. It gets file name in string.
FileWriter(File file)
Creates a new file. It gets file name in File object.

JAVA FILEREADER CLASS:

The Java File Reader class, File Reader makes it possible to read the contents of a file as a stream of characters. It works much like the File Input Stream except
the FileInputStream reads bytes, whereas the FileReader reads characters.
The FileReader is intended to read text, in other words. One character may correspond to one or more bytes depending on the character encoding scheme.

The Java FileReader is a subclass of the Java Reader class, so it has many of the same methods.

Java FileReader Example

Here is a simple Java FileReader example:










This example first creates a FileReader which is connected directly to the file pointed to by the file path passed as parameter to the FileReader constructor. Second, this example reads all characters one char at a time from the FileReader. Third,
the FileReader is closed.

Difference between Abstract Class and Concrete Class in Java?
      A. Modifier: An abstract class is declared using abstract modifier. Concrete class should not be declared using           abstract keyword, on doing so, it will also become abstract class.
Instantiation: An abstract class cannot be instantiated directly, i.e. object of such class cannot be created directly using new keyword. An abstract class can be instantiated either by concrete subclass, or by defining all the abstract method along with the new statement. A concrete class can be instantiated directly, using a new keyword.

Example: Invalid direct instantiation of an abstract class.


abstract class DemoAbstractClass {
        abstract void display();
}

public class JavaApplication {
        public static void main(String[] args)
        {
                    DemoAbstractClass AC = new DemoAbstractClass();
                    System.out.println("Hello");
        }
}

Example: Valid instantiation by defining all abstract method of an abstract class.

abstract class DemoAbstractClass {
        abstract void display();
}

public class JavaApplication {
        public static void main(String[] args)
        {
                    DemoAbstractClass AC = new DemoAbstractClass() {
                                void display()
                                {
                                            System.out.println("Hi.");
                                }
                    };
                    AC.display();
                    System.out.println("How are you?");
        }
}

Abstract methods: An abstract class may or may not, have an abstract method. A concrete class cannot have an abstract method, because class containing an abstract method must also be abstract.
The only real difference is that a concrete class can be instantiated because it provides (or inherits) the implementation for all of its methods. An abstract classcannot be instantiated because at least one method has not been implemented.Abstract classes are meant to be extended       




Different applet vs swing in java ?
A.
Swing
Applet
Swing is light weight Component.
Applet is heavy weight Component.
Swing have look and feel according to user view you can change look and feel using UIManager.
Applet Does not provide this facility.
Swing uses for stand lone Applications, Swing have main method to execute the program.
Applet need HTML code for Run the Applet.
Swing uses MVC Model view Controller.
Applet not.
Swing have its own Layout like most popular Box Layout.
Applet uses AWT Layouts like flowlayout.
Swing have some Thread rules.
Applet doesn't have any rule.
To execute Swing no need any browser By which we can create stand alone application But Here we have to add container and maintain all action control with in frame container.
To execute Applet programe we should need any one browser like Appletviewer, web browser. Because Applet using browser container to run and all action control with in browser container.






Discuss This, Final, super  Keywords ?
This Keyword:
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Example Program on without This Keyword:
  class Student
{ 
        int rollno; 
        String name; 
        float fee; 
        Student(int rollno,String name,float fee)
        { 
                    rollno=rollno; 
                    name=name; 
                    fee=fee; 
        } 
        void display()
        {
                    System.out.println(rollno+" "+name+" "+fee);
        } 
} 
class TestThis1
{ 
        public static void main(String args[])
        { 
                    Student s1=new Student(111,"ankit",5000f); 
                    Student s2=new Student(112,"sumit",6000f); 
                    s1.display(); 
                    s2.display(); 
        }
} 
Final Keyword:
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
variable
method
class
java final variable:
If you make any variable as final, you cannot change the value of final variable(It will be constant).
class FinalExample1
{ 
         final int speedlimit=90; 
         void run()
         { 
                    speedlimit=400; 
         } 
         public static void main(String args[])
        { 
            FinalExample1 obj=new  FinalExample1(); 
            obj.run(); 
        } 
} 

Super Keyword:
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
super is used to refer immediate parent class instance variable:
class Animal
{ 
        String color="white";  
} 
class Dog extends Animal
{ 
        String color="black"; 
        void printColor()
        { 
                    System.out.println(color);
                    System.out.println(super.color);
        } 
}
class Testsuper1
{ 
        public static void main(String args[])
        { 
                    Dog d=new Dog(); 
                    d.printColor(); 
        }
} 






Discuss String, String Tokenize, StringBuffer ?
A.

Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created.

String is used to represents group of characters or character array enclosed with in the double quotes

String & StringBuffer both classes are final classes present in java.lang package.

We  are able to create String objects in two ways
Without using new operator        eg:String str = “ vamsi”;
By using new operator                eg: String str = new String(“vamsi”);

When we create String object without using new operator the objects are created in
SCP(string constant pool) area

Whenever we are creating String object by using new operator the object created in HEAP area

SCP area does not allow duplicate objects

Heap memory allows duplicate objects

When ever create the objects in Heap area instead of checking previous objects it directly create the objects

When ever we create objects without using new operator then just before object creation it is
always checking previous objects,if the previous object is available with the same content then won’t  create new object that reference variable  pointing to existing objects.If the previous objects are not  available the JVM will create new objects

we are able create StringBuffer objects only one approach by using new operator.

StringBuffer  sb  =  new StrinBuffer(“osmaina uiveristy”);   

public class Example1
{ 
   public static void main(String args[])
  { 
       
        String str = "Beginnersbook";

        char arrch[]={'h','e','l','l','o'};
       
        String str2 = new String(arrch);
                   
        String str3 = new String("Java String Example");
                   
        System.out.println(str); 
        System.out.println(str2); 
        System.out.println(str3); 
   }
}


String Tokenizer:
In Java, you can StringTokennizer class to split a String into different tokenas by defined delimiter.(space is the default delimiter)

Uses StringTokennizer to split a string by “space” and “comma” delimiter, and iterate the StringTokenizer elements and print it out one by one.

Example 1:
import java.util.StringTokenizer;

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

                    String str = "This is String , split by StringTokenizer, created by mkyong";
                    StringTokenizer st = new StringTokenizer(str);

                    System.out.println("---- Split by space ------");
                    while (st.hasMoreElements()) {
                                System.out.println(st.nextElement());
                    }

                    System.out.println("---- Split by comma ',' ------");
                    StringTokenizer st2 = new StringTokenizer(str, ",");

                    while (st2.hasMoreElements()) {
                                System.out.println(st2.nextElement());
                    }
        }
}







Java AWT ?  AWT where we are creating instance of Frame class. Here, we are showing Button component on the Frame.?
A.

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.
The java.awt package provides classes for AWT api such as TextFieldLabelTextArea, RadioButton, CheckBoxChoiceList etc.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.



Container:
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc.
The classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another window for creating a window.
Panel:
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc.
Frame:
The Frame is the container that contain title bar and can have menu bars. It can have other components like button, textfield etc.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
1.By extending Frame class (inheritance)
2.By creating the object of Frame class (association)
Program to create the awt controls by extending the Frame class
import java.awt.*; 
class First extends Frame
{ 
        First()
        { 
                    Button b=new Button("click me"); 
                    b.setBounds(30,100,80,30);
                    add(b); 
                    setSize(300,300);
                    setLayout(null);
                    setVisible(true);
        }

        public static void main(String args[])
        { 
                    First f=new First(); 
        }
} 


AWT where we are creating instance of Frame class. Here, we are showing Button component on the Frame.
import java.awt.*; 
class Cde
{ 
        Cde()
       { 
                    Frame f=new Frame(); 
                    Button b=new Button("click me"); 
                    b.setBounds(30,50,80,30); 
                    f.add(b); 
                    f.setSize(300,300); 
                    f.setLayout(null);  
                    f.setVisible(true); 
       } 
        public static void main(String args[])
        { 
                    Cde f=new Cde(); 
        }
}
write  a program create button with the Action Listener
import java.awt.event.*; 
public class ButtonExample
{ 
        public static void main(String[] args)
         { 
                    Frame f=new Frame("Button Example"); 
                    final TextField tf=new TextField(); 
                    tf.setBounds(50,50, 150,20); 
                    Button b=new Button("Click Here"); 
                    b.setBounds(50,100,60,30); 
                    b.addActionListener(new ActionListener()
                    { 
                                public void actionPerformed(ActionEvent e)
                                { 
                                tf.setText("Welcome to Javatpoint."); 
                    } 
                    });

                    f.add(b);f.add(tf); 
                    f.setSize(400,400); 
                    f.setLayout(null); 
                    f.setVisible(true);  
         } 
} 

what is thread synchronization in java ?—very importing questations---
A.
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
The synchronization is mainly used to.
1.      To prevent thread interference.
2.      To prevent consistency problem.
There are two types of synchronization
1.      Process Synchronization
2.      Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1.      Mutual Exclusive
2.      Cooperation (Inter-thread communication in java)
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:
1.      by synchronized method
2.      by synchronized block
3.      by static synchronization
When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues.
For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.
Programe to use Thread without Synchronization.
class PrintDemo
 {
   public void printCount( )
 {
                    Try
 {
                                for(int i = 5; i > 0; i--)
 {
                                System.out.println("Counter   ---   "  + i );
                                }
                      }
          catch (Exception e)
         {
                                System.out.println("Thread  interrupted.");
                    }
        }
}

class ThreadDemo extends Thread
{
   private Thread t;
           private String threadName;
          PrintDemo  PD;

        ThreadDemo( String name,  PrintDemo pd)
 {
                     threadName = name;
                     PD = pd;
   }


  public void run()
 {
      PD.printCount();
      System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start ( )
 {
         System.out.println("Starting " +  threadName );
          if (t == null)
         {
                      t = new Thread (this, threadName);
                      t.start ();
         }
   }
}

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

                     PrintDemo PD = new PrintDemo();

                     ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
                     ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

                     T1.start();
                     T2.start();

                      try
{
                                 T1.join();
                                  T2.join();
                     }
 catch ( Exception e)
 {
                                System.out.println("Interrupted");
                      }
         }}
what is serialization?---- very important ---------

A. Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an object.
The serialization and deserialization process is platform-independent, it means you can serialize an object in a platform and deserialize in different platform.
For serializing the object, we call the writeObject() method ObjectOutputStream.
 deserialization we call the readObject() method of ObjectInputStream class.








Advantages of Java Serialization

It is mainly used to travel object's state on the network (which is known as marshaling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces.
It must be implemented by the class whose object you want to persist.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Program  to Serialize Student object Student object.

import java.io.*;
class Student implements Serializable
{
    int rno;
    String sname;
    double marks;

    Student(int r,String nm,double m)
    {
       rno = r;
       sname = nm;
       marks = m;
    }
    void display( )
    {
       System.out.println("Rollno "+rno);
       System.out.println("Name "+sname);
       System.out.println("Marks "+marks);
    }
    public static Student getData() throws IOException
    {
         int r;
         String nm;
         double m;
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

         System.out.print("enter a rollnumber:");
         r = Integer.parseInt(br.readLine());

         System.out.print("enter a  name:");   
         nm = br.readLine();

         System.out.print("wnter total marks:");
         m = Double.parseDouble(br.readLine());

         Student s = new Student(r,nm,m);
         return s;
    }
}

Save the above  program as Student.java

import java.io.*;
class StudentSerialiZation
{
   public static void main(String args[]) throws IOException
   {
     FileOutputStream fos = new FileOutputStream("Student");
     ObjectOutputStream oos = new ObjectOutputStream(fos);

     Student s = Student.getData();
     oos.writeObject(s);
     oos.close();
   }
}










Define linked list, hash set, tree set?
A        Linked List  :-
Linked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses. Each element is known as a node. ... In JavaLinked List class implements the list interface.
program on LinkedList  example:
import java.util.*; 
public class LinkedListclass1
{ 
   public static void main(String args[])
   { 
       LinkedList<String> al=new LinkedList<String>(); 
       al.add("Mohan"); 
       al.add("Das"); 
       al.add("Karam"); 
       al.add("Chand");
       al.add("Gandhi"); 
       Iterator<String> itr=al.iterator(); 
       while(itr.hasNext())
       { 
          System.out.println(itr.next()); 
       } 
   } 
}
Tree set:- TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class. 
Few important features of TreeSet are as follows:
1.    TreeSet implements the SortedSet interface so duplicate values are not allowed.
2.    Objects in a TreeSet are stored in a sorted and ascending order.
3.    TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
4.    TreeSet does not allow to insert Heterogeneous objects. It will throw classCastException at Runtime if trying to add hetrogeneous objects.
5.    TreeSet serves as an excellent choice for storing large amounts of sorted information which are supposed to be accessed quickly because of its faster access and retrieval time.
6.    TreeSet is basically implementation of a self-balancing binary search tree like Red-Black Tree. Therefore operations like add, remove and search take O(Log n) time. And operations like printing n elements in sorted order takes O(n) time.

import java.util.*; 
class TreeSetclass3
{ 
  public static void main(String args[])
  { 
        TreeSet<Integer> set=new TreeSet<Integer>(); 
        set.add(24); 
        set.add(66); 
        set.add(12); 
        set.add(15); 
        System.out.println("Highest Value: "+set.pollFirst()); 
        System.out.println("Lowest Value: "+set.pollLast()); 
  } 
} 

Hash Set:-  Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
HashSet stores the elements by using a mechanism called hashing.
HashSet contains unique elements only.
HashSet allows null value.
HashSet class is non synchronized.
HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
HashSet is the best approach for search operations.
Program  on HashSet class. The insertion order  differ.

import java.util.*; 
class HashSetclass1
{ 
   public static void main(String args[])
   { 

  //Creating HashSet and adding elements

           HashSet<String> set=new HashSet(); 
           set.add("One");   
           set.add("Two");   
           set.add("Three");  
           set.add("Four"); 
           set.add("Five"); 
           Iterator<String> i=set.iterator(); 
           while(i.hasNext()) 
           { 
           System.out.println(i.next()); 
           } 
 } 
} 

 what is character stream in java?
A. The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.
For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input and output done with stream classes automatically translates to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer.
If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues. Later, if internationalization becomes a priority, your program can be adapted without extensive recoding. See the Internationalization trail for more information.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacters {
    public static void main(String[] args) throws IOException {

        FileReader inputStream = null;
        FileWriter outputStream = null;

        try {
            inputStream = new FileReader("xanadu.txt");
            outputStream = new FileWriter("characteroutput.txt");

            int c;
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

what is Exception Handling ? try ,catch, Final  ?
A. The main objective of exception handling is to get normal termination of the application in order to execute rest of the application code.

Exception handling means just we are providing alternate code to continue the execution of remaining code & to get normal termination of the application.

Every Exception is a predefined class present in different packages.
java.lang.ArithmeticException
java.io.IOException
java.sql.SQLException
javax.servlet.ServletException ……etc

Types of Exceptions:-
As per the sun micro systems standards The Exceptions are divided into three types
1) Checked Exception
2) Unchecked Exception
3) Error
[
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
There are 5 keywords which are used in handling exceptions in Java.
Keyword
Description
Try
The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.
catch
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finally
The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throw
The "throw" keyword is used to throw an exception.
throws
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.

Finally Block:

Finally block code is always executed irrespective of try-catch block
It is used to provided clean-up code

 a.Database connectin closing

 b.streams closing

 c.Object destruction

Program to Handling the finally block without Exception

class TestFinallyBlock
{ 
  public static void main(String args[])
  { 
   try
   { 
   int data=25/5; 
   System.out.println(data); 
   } 
   catch(NullPointerException e)
   {
      System.out.println(e);
   } 
  finally
  {
     System.out.println("finally block is always executed");
  } 
  System.out.println("rest of the code..."); 
  } 
}   
explain how to handle exception in java?
A.. Default Exception Handling : Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it off to the run-time system(JVM). The exception object contains name and description of the exception, and current state of the program where exception has occurred. Creating the Exception Object and handling it to the run-time system is called throwing an Exception.There might be the list of the methods that had been called to get to the method where exception was occurred. This ordered list of the methods is called Call Stack.Now the following procedure will happen.
·         The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler.
·         The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods were called.
·         If it finds  appropriate handler then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
·         If run-time system searches all the methods on call stack and couldn’t have found the appropriate handler then run-time system handover the Exception Object to default exception handler , which is part of run-time system. This handler prints the exception information in the following format and terminates program abnormally.
Customized Exception Handling : Java exception handling is managed via five keywords: trycatchthrowthrows, and finally. Briefly, here is how they work. Program statements that you think can raise exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.
class TestFinallyBlock
{ 
  public static void main(String args[])
  { 
   try
   { 
   int data=25/5; 
   System.out.println(data); 
   } 
   catch(NullPointerException e)
   {
      System.out.println(e);
   } 
  finally
  {
     System.out.println("finally block is always executed");
  } 
  System.out.println("rest of the code..."); 
  } 
} 

 what is polymorphism ?
A.. The word polymorphism is used in various contexts and describes situations in which something occurs in several different forms. In computer science, it describes the concept that objects of different types can be accessed through the same interface. Each type can provide its own, independent implementation of this interface. It is one of the core concepts of object-oriented programming (OOP).
If you’re wondering if an object is polymorphic, you can perform a simple test. If the object successfully passes multiple is-a or instanceof tests, it’s polymorphic. As I’ve described in my post about inheritance, all Java classes extend the class Object. Due to this, all objects in Java are polymorphic because they pass at least two instanceof checks.
There are two types of polymorphism in Java:

1)compile-time polymorphism

2) runtime polymorphism.

We can perform polymorphism in java by method overloading and method overriding.

1.8.1) Method overloading:

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
There are two ways to overload the method in java
1.      By changing number of arguments
2.      By changing the data type
3.      In java Method Overloading is not possible by changing the return type of the method only
Example program for method overloading
class TestMethodoverload
{
                    void m1(int i)
                    {
                                 System.out.println("int-argument method");
                    }
                    void m1(int i,int j)
                    {
                                 System.out.println("int,int argument method=");
 }
                    void m1(char ch)
                    {
                                System.out.println("char-argument method");
                    }
                    public static void main(String[] args)
                    {
                                TestMethodoverload t = new TestMethodoverloadT();
                                t.m1(10);
                                t.m1(10,20);
                                t.m1('a');
                    }
}
) Method Overriding:

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

Usage of Java Method Overriding

o    Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
o    Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1.      The method must have the same name as in the parent class
2.      The method must have the same parameter as in the parent class.
3.      There must be an IS-A relationship (inheritance).
Example Program on Method Overiding:

class Vehicle
{ 
        void run()
         {
                    System.out.println("Vehicle is running");
        } 
} 

class Bike1 extends Vehicle
{ 
         public static void main(String args[])
        { 

                    Bike1 obj = new Bike1(); 
                    obj.run(); 
         } 
} 

Output:
Vehicle is running




write about the  packages in java?
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for:
·         Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
·         Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
·         Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only.
·         Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related classes where some of the classes are accessible are exposed and others are kept for internal purpose.
We can reuse existing classes from the packages as many time as we need it in our program.


Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.
2)  java.io: Contains classed for supporting input / output operations.
3)  java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations.
4)  java.applet: Contains classes for creating Applets.
5)  java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).
6)  java.net: Contain classes for supporting networking operations.

User-defined packages

These are the packages that are defined by the user. First we create a directory myPackage (name should be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package names.

package pack;
public class Addition
{
   private double d1,d2;

   public Addition(double a,double b)
   {
          d1 = a;
          d2 = b;
   }
   public void sum()
   {
        System.out.println("sum = " +(d1+d2));
   }
}

Explain why multiple inheritance is not possible in java and how this can be overcome ?

A. When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends class A and B then this type of inheritance is known as multiple inheritance. Java doesn’t allow multiple inheritance. In this article, we will discuss why java doesn’t allow multiple inheritance and how we can use interfaces instead of classes to achieve the same purpose.

Why Java doesn’t support multiple inheritance?

C++ , Common lisp and few other languages supports multiple inheritance while java doesn’t support it. Java doesn’t allow multiple inheritance to avoid the ambiguity caused by it. One of the example of such problem is the diamond problem that occurs in multiple inheritance. What is diamond problem?
We will discuss this problem with the help of the diagram below: which shows multiple inheritance as Class D extends both classes B & C. Now lets assume we have a method in class A and class B & C overrides that method in their own way. Wait!! here the problem comes – Because D is extending both B & C so if D wants to use the same method which method would be called (the overridden method of B or the overridden method of C). Ambiguity. That’s the main reason why Java doesn’t support multiple inheritance.

Can we implement more than one interfaces in a class

Yes, we can implement more than one interfaces in our program because that doesn’t cause any ambiguity(see the explanation below).
interface X
{
   public void myMethod();
}
interface Y
{
   public void myMethod();
}
class JavaExample implements X, Y
{
   public void myMethod()
   {
       System.out.println("Implementing more than one interfaces");
   }
   public static void main(String args[]){
                  JavaExample obj = new JavaExample();
                  obj.myMethod();
   }
}

write about layout manager in java –very important----?
A.. The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons.
·        It is very tedious to handle a large number of controls within the container.
·        Oftenly the width and height information of a component is not given when we need to arrange them.
Java provide us with various layout manager to position the controls. The properties like size,shape and arrangement varies from one layout manager to other layout manager. When the size of the applet or the application window changes the size, shape and arrangement of the components also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:
1.    java.awt.BorderLayout
2.    java.awt.FlowLayout
3.    java.awt.GridLayout
4.    java.awt.CardLayout
5.    java.awt.GridBagLayout
6.    javax.swing.BoxLayout
7.    javax.swing.GroupLayout
8.    javax.swing.ScrollPaneLayout
9.    javax.swing.SpringLayout etc.
import java.awt.*;  
import javax.swing.*;  
  
public class Border {  
JFrame f;  
Border(){  
    f=new JFrame();  
      
    JButton b1=new JButton("NORTH");;  
    JButton b2=new JButton("SOUTH");;  
    JButton b3=new JButton("EAST");;  
    JButton b4=new JButton("WEST");;  
    JButton b5=new JButton("CENTER");;  
      
    f.add(b1,BorderLayout.NORTH);  
    f.add(b2,BorderLayout.SOUTH);  
    f.add(b3,BorderLayout.EAST);  
    f.add(b4,BorderLayout.WEST);  
    f.add(b5,BorderLayout.CENTER);  
      
    f.setSize(300,300);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new Border();  
}  
}  

write about byte Streams?

A. Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile {
 
   public static void main(String args[]) throws IOException {  
      FileInputStream in = null;
      FileOutputStream out = null;
 
      try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }
   }
}

write about object oriented development?
A. Object Oriented Development (OOD) has been touted as the next great advance in software engineering. It promises to reduce development time, reduce the time and resources required to maintain existing applications, increase code reuse, and provide a competitive advantage to organizations that use it. While the potential benefits and advantages of OOD are real, excessive hype has lead to unrealistic expectations among executives and managers. Even software developers often miss the subtle but profound differences between OOD and classic software development.
Expected Benefits of OOD
Many benefits are cited for OOD, often to an unrealistic degree. Some of these potential benefits are
Faster Development: OOD has long been touted as leading to faster development. Many of the claims of potentially reduced development time are correct in principle, if a bit overstated.
  • Reuse of Previous work: This is the benefit cited most commonly in literature, particularly in business periodicals. OOD produces software modules that can be plugged into one another, which allows creation of new programs. However, such reuse does not come easily. It takes planning and investment.
  • Increased Quality: Increases in quality are largely a by-product of this program reuse. If 90% of a new application consists of proven, existing components, then only the remaining 10% of the code has to be tested from scratch. That observation implies an order-of-magnitude reduction in defects.
  • Modular Architecture: Object-oriented systems have a natural structure for modular design: objects, subsystems, framework, and so on. Thus, OOD systems are easier to modify. OOD systems can be altered in fundamental ways without ever breaking up since changes are neatly encapsulated. However, nothing in OOD guarantees or requires that the code produced will be modular. The same level of care in design and implementation is required to produce a modular structure in OOD, as it is for any form of software development.
  • Client/Server Applications: By their very nature, client/server applications involve transmission of messages back and forth over a network, and the object-message paradigm of OOD meshes well with the physical and conceptual architecture of client/server applications.
  • Better Mapping to the Problem Domain: This is a clear winner for OOD, particularly when the project maps to the real world. Whether objects represent customers, machinery, banks, sensors or pieces of paper, they can provide a clean, self-contained implication which fits naturally into human thought processes.
Therefore, OOD offers significant benefits in many domains, but those benefits must be considered realistically. There are many pitfalls that await those who venture into OOD development. These pitfalls threaten to undermine the acceptance and use of object-oriented development before its promise can be achieved. Due to the excitement surrounding OOD, expectations are high and delays and failures, when they come, will have a greater negative impact.
The purpose of this paper is to summarize different types of pitfalls that developers should try to avoid when developing applications in an OOD environment. In addition, suggested approaches to avoid these pitfalls can enable system developers to truly capitalize on the benefits of OOD.


1 comment:

  1. Thanks For sharing such good information. You can visit good collection of Java tutorials Visit Java Tutorials

    ReplyDelete