5.Inheritance

Method Overriding:-
In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the versio n of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass' version. This allows all instance variables to be displayed.

Next
// Methods with differing type signatures are overloaded – not
// overridden.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}
The output produced by this program is shown here:
This is k: 3
i and j: 1 2
The version of show( ) in B takes a string parameter. This makes its type signature different from the one in A, which takes no parameters. Therefore, no overriding (or name hiding) takes place.
Access specifier:-
protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package, but not from anywhere else. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes.
package Test;
class A
{
protected int i,j;
void setijA()
{
i = 10;
j = 20;
}
}
class B
{
void showA()
{
System.out.println("I : " + i);
System.out.println("J : " + j);
}
}
class DemoProtected
{
public static void main(String args[])
{
B ObjectB = new B();
ObjectB.showA();
}
}
The Protected Modifier:-
The protected visibility modifier allows a member of a base class to be accessed in the child
protected visibility provides more encapsulation than public does
protected visibility is not as tightly encapsulated as private visibility
All these methods can access the pages instance variable.
Note that by constructor chaining rules, pages is an instance variable of every object of class Dictionary.

Class Hierarchy
A child class of one parent can be the parent of another child, forming class hierarchies
At the top of the hierarchy there’s a default class called Object.
Good class design puts all common features as high in the hierarchy as reasonable
inheritance is transitive
An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object
The class hierarchy determines how methods are executed:
Previously, we took the simplified view that when variable v is an instance of class C, then a procedure call v.proc1() invokes the method proc1() defined in class C
However, if C is a child of some superclass C’ (and hence v is both an instance of C and an instance of C’), the picture becomes more complex, because methods of class C can override the methods of class C’

super Keyword
The keyword super is used to refer to the direct superclass of a class.
The keyword can be used to explicitly invoke the superclass methods and constructors.
To explicitly invoke a constructor of the superclass, the statement: super(args) is used.  This statement invokes the superclass constructor, passing it the values to be initialized.  The superclass constructor then initialized the values of the inherited data fields for the current object.
The calls to the superclass constructor must be the first statement in the method body.  If it is omitted, the compiler will implicitly invoke the constructor by inserting a call to the constructor that has no parameters (default constructor). 
The prefix “super. “ can also be used to call a method of the superclass.  For example, super.toString() invokes the toString() method of the superclass


What is inheritance? How can you make constructor in class hierarchy? Explain with example.[2060]Ans:
Inheritance in JAVA programming is the process by which one class takes the property of another class. The new classes, known as derived classes or subclasses, take over the attributes and behavior of the pre-existing classes, which are referred to as base classes or super classes.
It helps the programmer to re-use the class just by modifying minor objects and methods in it.
For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements.
Syntax:
Class ABC
{

}
Class derived class extends ABC
{


}

What is abstract base class? Explain it with an example.[2065]
Ans:
An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class.
Example:-
abstract class A
{
abstract void callme();
void callmetoo() {
System.out.println(“This is a concerte method”);
}
}
class B extends A {
void call me(){
System.out.println(“B’s implementation of callme.”);
}
}
 class AbstractDemo
{
public  static void main(String args[])
{
B b =new B();
b.callme();
b.callmetoo();
}}
Notice that no object of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete method called callmetoo(). This is perfectly acceptable.

Why is inheritance used in java? Describe the different types of classes in java class hierarchy with an example that create multilevel hierarchy. [2064]
Ans:
In Java, inheritance is used for two purposes:
1. Class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class inheritance.
2. Interface inheritance - create a new class to implement the methods defined as part of an interface for the purpose of sub typing. That is a class that implements an interface “conforms to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.
What are the uses of super in Java? Explain with an example. [2064]
Ans:
The keyword super is used to access methods/variables of the parent class.
ex:
public class A {
public String getName(){
.....
}
}
public class B extends A {
public String getName(){
.....
}
}
If you want to access the method getName of class A inside class B you cannot do directly because the compiler would get confused. you need not create an object of A since it is already available. At this point you can use super super.getName() is enough to call the method of the parent class

6.Exception and Package

Exception and Package
Introduction to ExceptionAn Exception is an abnormal condition that arises in a code sequence at run time, ie. run-time error. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
General for of an exception-handling block:
try{ // block of code to monitor for errors }
catch (ExceptionType1 exOb){// exception handler for ExceptionType1 }
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2 }
//…..
finally{ // block of code to be executed before try block ends }
Mechanism of Exception Handling in Java
 Java exception handling is managed via  five keywords: try, catch, throw, throws and finally. Exception handling is accomplished through the “try – catch” mechanism, or by a “throws” clause in the method declaration. For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception “up the chain” (to a parent class).
Any code that absolutely must be executed after a try block completes is put in a finally block.

Explain the different types of exceptionsThere are three main types of Exceptions:
1. Checked exceptions: which have to be handled by the code. These represent avoidable exceptional conditions which can be handled and recovered from.
2. Runtime Exceptions: which need not be handled by the code. These represent unexpected exceptional conditions which can be handled but not necessarily recover from.
3. Errors: which need not be handled by the code. These represent severe unexpected exceptional conditions which should not be attempted to handle.
There are two Process of Exception Flow
Checked & Unchecked it one of common condition
here Java used Type of Exception Following Types
(1)IOException
(2)FileNotFoundException
(3)ArithmeticException
(4)NullPointerException
(5)ArrayIndexOfBoundException
(6)NegativeArraySizeException
(7)NumberFormatException
What are the different between error and exceptions? Explain about some exceptions in Java. [2064]
Explain about some exceptions in Java
. [2064]
Error Exception
1. Error is the compile time error 1. Exception is an run time error
2. Error is uncoverable 2. Exception iscoverable
3. Error can not behandled 3. Exception can be handled
4. For example: Overflow,Out of memory. 4. Examples for exceptions: Array out of bonds, attempt to divide by zero etc.
Basic of exceptionsJava exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you want to monitor for 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) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java runtime 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 before a method returns is put in a finally block. This is the general form of an exception-handling block:

User-defined exceptionsA user defined exception is exception class provided by API provider or application provider which extends Exception defined in the classes of JAVA API.It's used to deal with the unconventional action in your codes. JAVA use try-catch construct to take it.
In user defined exception class, you must rewrite method extends its parent class Exception. You can throw the exception out in try construct and deal with in catch.

How can you create user define exception?
When a program encounters an exceptional condition, it throws the exception like IOException, IllegalArgumentException etc.
Sometimes no standard class adequately represents the exceptional condition. In this condition programmer can choose to create his own exception class.
To create our own Exception existing type of exception are inherited, preferably one that is close in meaning to your new exception.
This code shows the use of user defined exception. In this code ApplicationException is user defined Exception. public class ApplicationException extends Exception { private int intError;
  ApplicationException(int intErrNo){
    intError = intErrNo;  }
 ApplicationException(String strMessage){
    super(strMessage);  }
   public String toString(){
    return "ApplicationException["+intError+"]"; } 
}
class ExceptionDemo{
  static void compute(int a) throws ApplicationException{
    System.out.println("called compute(" +a +" )");
    if(a>10){
      throw new ApplicationException(a);
    }
    System.out.println("NORMAL EXIT");  }
  public static void main(String[] args) {
    try{ compute(1);  compute(20);
    }catch(ApplicationException e){
      System.out.println("caught " + e);}} }
Output:
called comute(1 )
mohti
called comute(20 )
caught ApplicationException[20]

Packages:
Packages are collection of similar classes grouped together. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
Using packages
package java.awt.event;
import java.util.ArrayList; // Import the ArrayList class from the java.util package import java.util.*; // Import all public classes from the java.util package

What happens if an exception is not caught?
The program will terminate abnormally and then default exception handler will handle the exception.
What are the different ways to handle exceptions?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the   exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

7.Managing Input and Output

Explain I/O streams in Java in detail.[2065,2064]
Ans:
InputStream class is an abstract base class which do provides the minimal programming interface and partial implementation of the input streams in Java. The InputStream defines the methods to read bytes or the arrays of bytes, marking the locations in stream, skipping the bytes of input, finding out the number of bytes which are available for reading, and resetting current position within the stream. The input stream is automatically opened when we create it. we can explicitly close the stream with the method close(), or let it be closed implicitly when a object is garbage collected.
OutputStream class is the abstract base class which provides minimal programming interface and the partial implementation of the output stream in Java. the OutputStream defines methods for writing the bytes or arrays of bytes to stream and flushing the stream. The output stream is automatically opened when we create it. We can explicitly close the output stream using close() method, or let it be closed implicitly when an object is garbage collected.
I/O Streams
Byte Streams handle I/O of raw binary data.
Character Streams handle I/O of character data, automatically handling translation to and from the local character set.
Buffered Streams optimize input and output by reducing the number of calls to the native API.
Scanning and Formatting allows a program to read and write formatted text.
I/O from the Command Line describes the Standard Streams and the Console object.
Data Streams handle binary I/O of primitive data type and String values.
Object Streams handle binary I/O of objects.
Console I/O Stream

Stream Tokenized[2060]
A stream tokenizer takes an input stream and parses it into tokens, allowing the tokens to be read one at a time.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class StreamTokenApp {
  public static void main(String args[]) throws IOException {
    BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));
    StreamTokenizer inStream = new StreamTokenizer(inData);
    inStream.commentChar('#');
    boolean eof = false;
    do {
      int token = inStream.nextToken();
      switch (token) {
      case inStream.TT_EOF:
        System.out.println("EOF encountered.");
        eof = true;
        break;
      case inStream.TT_EOL:
        System.out.println("EOL encountered.");
        break;
      case inStream.TT_WORD:
        System.out.println("Word: " + inStream.sval);
        break;
      case inStream.TT_NUMBER:
        System.out.println("Number: " + inStream.nval);
        break;
      default:
        System.out.println((char) token + " encountered.");
        if (token == '!')
          eof = true;
      }
    } while (!eof);
  }
}

Console I/O stream:
a. InputStrem:-
It is used to store the information about the connection between an input devices and computer program.
b. InputStreamReader:-
It is used to translate data bytes received from InputStream Object in to a stream of character. To obtain InputStreamReader object that is linked to system.in.
c. BufferedReader:-
It is used to buffer(store) the input received from InputStreamReader.
To take input From Keyboard
import java.io.*;
public class IODemo
{
public static void main(String args[])
{
int a=0,b=0,sum=0;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter two number");
try
{
a=Integer.parseInt(br.ReadLine());
b=Integer.parseInt(br.ReadLine());
}
catch(IOException ex)
{
System.out.println(ex);
}
sum =a+b;
System.out.println("Sum="+sum);
}
}
To take Input frm File
import java.io.*;
class FileInputDemo
{
public static void main(String args[])
{
String Text,filename=" ";
try
{
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader kbr =new BufferedReader(isr);
System.out.println("Enter File name");
filename=kbr.Readline;
FileReader fr= new FileReader("File name");
BufferedReader br =new BufferedReader(fr);
while(Text =br.ReadLine())!=null)
{
System.out.println(Text);
}
}
catch(FileNotFoundException ex)
{
System.out.println(ex);
}
catch(IOException ee)
{
System.out.println(ee);
}
}
}
To Write in file
import java.io.*;
class FileOutDemo
{
public static void main(String args[])
{
try
{
String text="Welcome",filename=" ";
{
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader kbr =new BufferedReader(isr);
System.out.println("Enter File name");
filename=kbr.ReadLine();
FileOutputStream fos =new FileOutputStream(filename);
PrintStream Ps= new PrintStream (fos);
Ps.priintln(text);
}
catch(IOException ex)
{
System.out.println(ex);
}
}
}
FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file name . The read() method of this class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class. This class throws FileNotFoundException, if the specified file is not exist. You can use the constructor of this stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the constructor of this stream as:
FileOutputstream(File filename);
Reading Text from the Standard Input
import java.io.*;
 
public class ReadStandardIO{
 
  public static void main(String[] args) throws IOException{
      InputStreamReader inp = new InputStreamReader(System.in)
      BufferedReader br = new BufferedReader(inp);
      System.out.println("Enter text : ");
 
     String str = in.readLine();

     System.out.println("You entered String : ");
      System.out.println(str);
  }
}

To read and write to the command prompt console:
import java.io.*;
public class ReadStringFromConsole {
public static void main (String[] args) {
System.out.print("Prompt: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strInput = null;
try {
strInput = br.readLine();
} catch (IOException ioe) {
System.out.println("Error trying to read input.");
System.exit(1);
}
System.out.println("Thank you, " + strInput );
} // end of main.
} // end of ReadStringFromConsole class
Java read file line by line
import java.io.*;
public class ReadFile{
    public static void main(String[] args) throws IOException{
      File f;
    f=new File("myfile.txt");
      if(!f.exists()&& f.length()<0)
      System.out.println("The specified file is not exist");
      else{
         FileInputStream finp=new FileInputStream(f);
      byte b;
    do{
      b=(byte)finp.read();
      System.out.print((char)b);
    }
      while(b!=-1);
        finp.close();
        }
    }
  }
Java Write To File
import java.io.*;
public class WriteFile{
    public static void main(String[] args) throws IOException{
      File f=new File("textfile1.txt");
      FileOutputStream fop=new FileOutputStream(f);
      if(f.exists()){
      String str="This data is written through the program";
          fop.write(str.getBytes());
          fop.flush();
          fop.close();
          System.out.println("The data has been written");
          }
          else
            System.out.println("This file is not exist");
    }
  }
Create File in Java
import java.io.*;
public class CreateFile1{
    public static void main(String[] args) throws IOException{
      File f;
      f=new File("myfile.txt");
      if(!f.exists()){
      f.createNewFile();
      System.out.println("New file \"myfile.txt\" has been created
                          to the current directory");
      }
    }
}

8.Graphical User Interface(GUI) Programming

Graphical User Interface (GUI) Programming

Introduction to AWT
AWT stands for Abstract Window Toolkit. It is a portable GUI library between Solaris and Windows 95/NT. The Abstract Window Toolkit provides many classes for programmers to use. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support AWT.
The AWT helps to create graphical component as textbox, Radio button, Command button, etc. which helps for data manipulation.

Applets
An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM).

How does applet differ from application? Write are the basic steps to create applets? [2066,2060,2064] [8M]
Ans:
Applet VS Application
1. Applets are web applications & small. 1.Applications are desktop application and large
2. Do not contain main function. 2. It contains main function
3. Applets can be embedded in HTML pages and downloaded over the Internet. 3. Applications have no special support in HTML for embedding or downloading.
4. It is used over a network. 4. It is used the local system resources.
5.Applets must import ‘AWT’ and ‘applet’ package. 5. Application do not need it.
6.Applets must have GUI 6. Applications mayn’t have GUI.
7. Applet starts execution after init() method 7. Applications start execution after main() method

Steps for creating applets
1. Edit a java source file
a. Initialize an applet.
b. Start the operation
c. Perform specified activities.
d. Stop applet.
2. Compile program
3. Execute the applet viewer, specifying the name applet’s source file.


Example:-
import java.awt.*;
import jave.applet.*;
public class appletDemo extends Applet
{
String msg = “ “;
public void Paint (Graphics g)
{
g.drawString(“Welcome !”,100,200);
}
public void start()
{
msg =msg +”Inside Start”;
}
public void init()
{
Msg=msg+ “Inside init”;
}
public void stop()
{
Msg= msg+ “Inside Stop”;
}
}

Next Example
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class SimpleApplet extends Applet{

String text = "I'm a simple applet";

public void init() {
text = "I'm a simple applet";
setBackground(Color.cyan);
}
public void start() {
System.out.println("starting...");
}
public void stop() {
System.out.println("stopping...");
}
public void destroy() {
System.out.println("preparing to unload...");
}
public void paint(Graphics g){
System.out.println("Paint");
g.setColor(Color.blue);
g.drawRect(0, 0,
getSize().width -1,
getSize().height -1);
g.setColor(Color.red);
g.drawString(text, 15, 25);
}
}


HTML tags
The applet tag is used to start an applet from both an HTML document and form an applet viewer. An applet viewer will execute each Applet tag that it finds in a separate window.

<APPLET>
Codebase=(pathof.classFile)
Alt=(AlternativeText)
Name=(AppletName)
Width=(pixels)
Height=(pixels)
Vspace=(VetricalSpace)
Hspace=(HorizontalSpace) </APPLET>

Passing Parameters to Applets
Parameters are passed to applets in NAME=VALUE pairs in
tags between the opening and closing APPLET tags. Inside the applet, you read the values passed through the PARAM tags with the getParameter() method of the java.applet.Applet class.

The program below demonstrates this with a generic string drawing applet. The applet parameter "Message" is the string to be drawn.
import java.applet.*;
import java.awt.*;
public class DrawStringApplet extends Applet {
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
String inputFromPage = this.getParameter("Message");
if (inputFromPage == null) inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 25);
}
}
You also need an HTML file that references your applet. The following simple HTML file will do:






This is the applet:



Build in methods in applet(Applet activities)
i. init()
ii. start()
iii. paint()
iv. stop()
v. destroy()
Web Page with Applet






9.AWT continued

Event handling and Java Technology

How can I extend Java event handling code to suit
application specific event handling?

Ans:
There are four parts to event handling, one is listener,
second one is event object, the third one is the event
container and fourth one is the event propagator.

Extension point for first two parts are provided by
Java api as java.util.EventListener and java.util.EventObject
respectively. The third one (Event listener container) and
fourth one (event generator) has to be provided by programmer

Event generator should extend event listener container,
and every event generator/source should add event listeners
added to it, and calls event methods and passes event object
associated with this event listener.
The first one is the event listener as follows:

public interface DemoListener extends
java.util.EventListener
{
public void demoEvent(DemoEvent dm);
}

and second one the event object as follows:

public class DemoEvent extends java.util.EventObject
{
Object obj;
public DemoEvent(Object source)
{
super(source);
obj = source;

}
public Object getSource()
{
return obj;
}
......
}

The third part is the event container:

public class EventContainer
{
private Vector repository = new Vector();
DemoListener dl;
public EventContainer()
{

}
public void addDemoListener(DemoListener dl)
{
repository.addElement(dl);
}
public void notifyDemoEvent()
{
Enumeration enum = repository.elements();
while(enum.hasMoreElements())
{
dl = (DemoListener)enum.nextElement();
dl.demoEvent(new DemoEvent(this));
}
}
......
}

The fourth one is the event listener implementor, that
implements event listener and implements event handling
code/method.

EventContainer adds implemented DemoListener and based
on certain event, notifyDemoEvent methods executes
demoEvent method for all the demo listeners in the
repository inside EventContainer.

Event in Java[2065]
Ans:
An event is a state change in any object. E.g. when a button is clicked the click event of button occurs. Similarly load event of a page occurs when a HTML page loaded first time. The event may be of two type
a. Interactive event
b. Non-interactive

Type of Event[2060]
Ans:
Interactive event:-
Those events which are fixed due to user’s interaction with java controls. Eg. Click, key down, key up, mouse move, etc.
Non-interactive
Those events in which there is no need of user interaction for their occurrence. They are fixed automatically. E.g. load, unload, etc.

Event handler
The event Handler are method or routine which execute after event occurred. For each event there is one corresponding event handler. The responsibility of a event handler of a event is to perform specific assigned task after occurance of associated event.
e.g.
on click,
on change
on select



What is AWT?
Ans:
AWT stands for Abstract Window Toolkit. It is a portable GUI library between Solaris and Windows 95/NT. The Abstract Window Toolkit provides many classes for programmers to use. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support AWT.
The AWT helps to create graphical component as textbox, Radio button, Command button, etc. which helps for data manipulation.


What are the AWT containers? What are the different types of layout managers? [2060,2062]. [4+4M]
Ans:

Applet
This subclass of Panel is actually part of the java.applet package. It is the base class for all applets.

Panel
A generic container used to create nested layouts.

Window
A heavyweight window with no titlebar or other decoration, suitable for pop-up menus and similar uses.

ScrollPane
A container that contains a single child and allows that child to be scrolled vertically and horizontally

Dialog
A window suitable for dialog boxes.

Frame
A window suitable for use as the main window of an application. In AWT, Frame is the only container that can contain a MenuBar and related menu components.


A layout Manager is an object that is used to organize components in a container. The different layouts available in java.awt are:
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.

GridBagLayout:
The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy more
than one row or column of the grid. In addition, the rows and columns may have different sizes.

What is interface? What are the major differences and similarities between interface and classes.
Ans:
An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. An interface can also include constant declarations. Interfaces are declared using the interface keyword. and may only contain method signatures and constant declarations. An interface may never contain method definitions.

Similarities
Classes and Interfaces are both Java files. They are saved as .java files with the name as the public class or public interface name.

Differences
The difference is that, classes are fully coded. That is, they have all the necessary variables and methods coded in them. But in case of Interfaces, only methods are declared. They are not defined. Interfaces are only like skeletons whereas classes can implement interfaces and complete the skeleton.

Interfaces are syntactically similar to classes, but they lack instance variables,and their methods are declared without any body.One class can implement any number of interfaces.Interfaces are designed to support dynamic method resolution at run time.

10.JDBC

What is JDCB?
Ans:
JDCB (Java Database Connectivity) is a Java API for connecting programs written in Java to the data in relational databases. It consists of a set of classes and interfaces written in the Java programming language. JDBC provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API.
Simply put, JDBC makes it possible to do three things:
 Establish a connection with a database
 Send SQL statements
 Process the results.


Advantages of JDCB
The main advantage of JDBC is that it is platform independent (as Java is platform independent) as well as database independent. It means that any software developed on platforms such as Linux can be used on platforms such as Windows, with very minor changes.

ODBC:-
ODBC (Open Database Connectively) is a standard or open application programming interface (API) for accessing a database. By Using ODBC statements in a program, you can access files in a number of different databases including Access, dBase, DB2, Excel and Text. It allows programs to use SQL requests that will access database without having to known the proprietary interfaces to the databases.
Comparison of JDCB with ODBC [2060,2062,2064]
Ans:
1. ODBC is for Microsoft and JDBC is for java applications.
2. ODBC mixes simple and advanced features together and has complex options for simple queries but JDBC is designed to keep things simple while allowing advanced capabilities when required.
3. ODBC can't be directly used with java because it uses a c interface.
4. ODBC is sued between application but JDBC is used by Java programmer to connect to database.
5. JDBC API is a natural Java Interface and is built on ODBC. JDBC retains some of the basic feature of ODBC.
6. ODBC makes use of pointers which have been removed totally from java.

The java sql package
Ans:
This package provides the APIs for accessing and processing data which is stored in the database especially relational database by using the java programming language. This java.sql package contains API for the following :
1. Making a connection with a database with the help of DriverManager class
2. Sending SQL Parameters to a database
3. Updating and retrieving the results of a query
4. Providing Standard mappings for SQL types to classes and interfaces in Java Programming language.
5. Metadata
6. Exceptions
7. Custom mapping an SQL user- defined type (UDT) to a class in the java programming language.


Steps for using JDBC [2064, 2065]
Ans:
Steps for JDBC
There are seven standard steps in querying databases:
a. Load the JDBC driver.
b. Define the connection URL.
c. Establish the connection.
d. Create a statement object.
e. Execute a query or update.
f. Process the results.
g. Close the connection.
Sample program
import java.sql.* ;
class JDBCQuery
{
public static void main( String args[] )
{
try
{
// Load the database driver
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” ) ;
// Get a connection to the database
Connection conn = DriverManager.getConnection( “jdbc:odbc:Database” ) ;
//DriverManager.getConnection(“jdbc:mysql://localhost/test?user=root&password=mypass”);
// Print all warnings
for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
{
System.out.println( “SQL Warning:” ) ;
System.out.println( “State : ” + warn.getSQLState() ) ;
System.out.println( “Message: ” + warn.getMessage() ) ;
System.out.println( “Error : ” + warn.getErrorCode() ) ;}
// Get a statement from the connection
Statement stmt = conn.createStatement() ;
// Execute the query
ResultSet rs = stmt.executeQuery( “SELECT * FROM Cust” ) ;
// Loop through the result set
while( rs.next() )
System.out.println( rs.getString(1) ) ;
// Close the result set, statement and the connection
rs.close() ;
stmt.close() ;
conn.close() ;}
catch( SQLException se )
{
System.out.println( “SQL Exception:” ) ;
// Loop through the SQL Exceptions
while( se != null )
{
System.out.println( “State : ” + se.getSQLState() ) ;
System.out.println( “Message: ” + se.getMessage() ) ;
System.out.println( “Error : ” + se.getErrorCode() ) ;
se = se.getNextException() ; }}
catch( Exception e )
{
System.out.println( e ) ;}}}

What are the necessary steps needed for connecting a database with a java program through JDBC? [2062]
Ans:
Steps to connect to JDBC.
1. Import java.sql package
2. Load the driver, using Class.forName(DriverName);
3. Get the connection object, Connection con = Driver.getConnection(loaded driver name);
4. Create a SQL statement, Statement s = con.createStatement();
5. Execute a query or update ResultSet rs = s.executeQuery("sql statement");
ResultSet rs = s.executeUpdate("sql statement");
6. Retrive the result
while(rs.next())
System.out.println(“Name=”+rs.getstring(“Column Name”)
7. Close statement & Connection
s.close(); con.close();