Você está na página 1de 10

Bachelor of Computer Java Programming A + B all

Semester 5
Applications qs

B
c. Create the following form in Java:-
Subject should display name of subjects :
C++

VB

Java

Foreign language should display choice of foreign languages French, German


and Japanese.
Submit button should submit the result.
Import java.awt.*
import java.applet.*
import java.awt.event.*
public class student extends Frame implements ActionListener
(
String fin;
Button s = submit(submit);
Label l1= new Label(Subjects, Label.LEFT);
Label l2 = new Label(Languages, Label.LEFT);
Label l3 = new Label(Student form, Label.CENTER);
CheckboxGroup sub = new CheckboxGroup( ) ;
Checkbox c1 = new Checkbox(C++, false, sub);
Checkbox c2 = new Checkbox(Java, false, sub);
Checkbox c3 = new Checkbox(VB, false, sub);
TextField t1 = new TextField( );
Choice language = new Choice( );
public void student (){
addWindowListener(new myWindowAdapter());
setLayout(null);
add(c1);
add(c2);
add(c3);
add(l1);
add(l2);
add(t1);
add(language);
s.addActionListener(this);
add(s);
language.add(French);
language.add(German);
language.add(Japanese);
l1.setBounds(25,120,90,20);
c1.setBounds(120,120,50,20);
c2.setBounds(170,120,60,20);
c3.setBounds(220,120,70,20);
l2.setBounds(25, 90, 90, 20);
Languages.setBounds(30, 90, 95,20);
s.setBounds(25, 140, 90, 50, 30);
}
public void paint(Graphics g){
{g.drawString(msg,100,250);}
public void actionPerformed(ActionEvent ae)
if(ae.getActionCommand().equals("submit"))
{fin="submitted!";}
}
public static void main(String g[]) {
student f=new student();
f.setSize(new Dimension(300,300));
f.setTitle("Registration Form");
f.setVisible(true);
}
}
class myWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

1 Explain the event delegation models in AWT. What are the


components of an event?
Components of an event
Source (generating an event) : example any window's fundamental elements
such as Container, Panel, Window, Frame and form elements, Button, Checkbox,
Choice, List, Menu item, Scroll bar, Text components, Window
notifies one or more listeners (receives, processes and returns an event) .
Supported by a number of packages including :
java.util - contains the superclass in the Java event class
hierarchy, EventObject,
java.awt - contains the AWT superclass , AWTEvent, with its
getID() method determining the type of event
Swing
java.awt.event - defines methods for listener interfaces. Each
method has specific interfaces that must be
implemented appropriately in the listener so that it can
receive the type of event desired. Adapter classes can be
used if only certain methods are needed from a listener interface.
commonly used are

ActionListener

AdjustmentListener

ComponentListener

ContainerListener

Focus Listener

ItemListener

KeyListener

MouseListener

MouseMotionListener

MouseWheelListener

TextListener

WindowFocusListener

WindowListener

Each source must provide code for registering and unregistering (if needed) the
listener, which receives event notifications. .
e.g. KeyEvent is generated when keybaord input occurs. In this class, integer
constants are defined for

ASCII equivalents of numbers and letters: VK_0 through VK_9 and VK_A
through V_Z

KEY_PRESSED and KEY_RELEASED and KEY_TYPED

enter, shift, ctl, alt, page down/up, left, right, esc,

KeyEvent and MouseEvent are subclasses of the abstract class InputEvent, a subclass
of ComponentEvent

Methods for keyboard and mouse event listeners are found in the Component class.

public void addKeyListener (KeyListener listenerName) //registers a keyboard


event object for all specified listener
methods

public void removeKeyListener (KeyListener listenerName) //removes a


listener for that event

KeyEvent class may take a constructor as follows.


KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

src: reference to the component that generated the event

type: type of the event

when: system time at which the key was pressed

modifiers: modifiers that were pressed when this key event occurred

code: VK coke

ch: character equivalent if one exists

Some common methods are defined for all events, in for example KeyEvent,

char getKeyChar( )

int getKeyCode( )

Each listener must have been registered with one or more sources, and must provide
implementation methods to receive and process the notifications.
5 What is a static method?
Why cant a static method use this and super? Explain with
example
The purpose of a static method in Java is to have a unit of program is
independent of any of its instances. No updates on a static variable or method. It
can be declared in a class, so it can be inherited and passed information in
subclasses. Main() is declared like this, only once and before any object exists. A
static member is accessible before any objects of its class are created, and
outside its class. Two ways to access static methods are with import static
statement or a dot operator reference ,
Example
import static java.lang.Math.pow; //can use this method by name i.e. pow
import static java.lang.*; //can use all and any method of this class
Math.pow() //have to reference the class to use this method, useful in avoiding
namespace collisions when the method is not used much
A static method is independent of the instance of an object, class, interface. It
does not have a current instance. Therefore they cannot use 'this'. Static
methods can only call other static methods and can access static data. Therefore
they cannot use 'super'.
A static block can be used to initialise variables of a class, before they are used.,
when the class is first loaded.
Static methods can be declared in an interface, and can be called without an
instance of the interface.
Methods of local inner classes can't be marked as static.

4 State the significance of public, private, protected, default


modifiers

These are access modifiers specified on a class, memmbers (method and


variables).
public : code can be modified by any other code . Always precedes main()
private : can only be accessed by other members of the same class
protected : can be accessed by members, classes, and interfaces of the
same class, package subclass and subclasses using different packages.
Default : no access modifier, can only be accessed by members using the
same package. i.e. Java is a package-oriented language
2 Explain the concept of interface.
What is scope and nature of variables and methods defined in an
interface?
B
b. Create a Java applet with a button Display. On click of button it should
display Rectangle, Oval and Circle within the Applet.
import java.awt.Button;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Panel;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

class drawShapes extends java.applet.Applet implements ActionListener

Panel circle = new Panel();

Panel rectangle = new Panel();

Panel oval = new Panel();

Button displayShape = new Button("Display");

public void init()

add(displayShape);

displayShape.addActionListener(this);

public void paint(Graphics g) {

super.paint(g);

if (displayShape) {
g.drawOval(45, 75, 75);
g.drawRect(10, 10, 60, 50);
g.drawOval(10, 10, 50, 50);
}
}

3 a) How does exception-handling work in Java?


An exception is a run-time error, that can be codified away in Java with a try,
catch, (optional) final block. The method that might throw the exception is put in
the try clause. You want to monitor this code. If an exception occurs, if something
happens here that violates the rules of Java language, an exception is thrown,
and handled in a catch block. The catch block is supposed to resolve the error,
and continue execution in the next segment. Code that must be implemented
after the try-catch block is put in a finally block.
Exceptions are built-in to Javas runtime. All are subclasses of Throwable. They
can be Exception (notably RuntimeException) or Error subclasses. You can extend
any of these classes. Being a class object, they can be used in debugging to
simply print out an error message. Throwable;s methods are to do with the
stacktrace, description of the exception.
Exception-handling clauses can contain multiple catch statements and nested
try-catch statements. Subclasses of an exception must come before any of their
superclasses in multiple catch statements. Nested try statements form an
ordered list by declaration order of catch handlers to match a try statement.
Assignment B
a) Create a try block that is likely to generate two types of exception and then
incorporate necessary catch block to handle them appropriately
Divide by zero
array out of bounds
class A {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try {
if(a==1) a = a/(a-a); // division by zero
if(a==2) {
int c[] = { 1 };
c[42] = 99;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

b) Why Java doesn't support multiple inheritances?


6 Explain the concept of method overriding.
Overriding methods is a method in a subclass that has the same (signature)
name, argument list (number and type), and return type or subtype, with a
different (overriding) implementation. He access specifier can be more,
but not less accessible.
Can we over-ride method within the same class? Explain.
No. Overriding is between interfaces and class objects only. Classes are for
concrete, namespace aware implementations.
7 a) What are native methods? How do you use them?
Native methods are written in another language like C or C++. They are
declared same as any other method, with the native keyword. The native
code is compiled as separate files into a dynamically loadable library, that can be
referenced by file name in the Java source code by its name. The .class files and
the native code Is run in the Java interpreter.
b) What are wrapper classes? Why are they used?
Type wrappers are classes, objects that encapsulate a primitive type in an object
in Java, for operations such as passing between methods, and use in data
structure. They all override the toString ( ) method, returning the value within
the wrapper, so they can be used with printIn( ). Value of the wrapper can be
extracted, or unboxed, with a typeValue ( ) method, example
Character(char ch) unboxed using char charValue ( )
Normally objects are created with the new keyword. No need for wrappers, done
automatically
Integer x = 1 ; // autoboxed wrapper class. This occurs also when an
argument is passed to a method, or returned by a method, or
otherwise any conversion to to or from an object.
Other wrappers are
Boolean(boolean boolValue)
Boolean(String boolString) //if the string is true then object is true
and all Numeric type wrappers, example byte byteValue( ) and also from a
valid numeric containing string Integer(String s)

8 What are the most important features of Java? How does Java achieve
platform independence?
From the whitepapers, Java is described as

Simple easy to learn, resembles C and C++

Object-oriented everythings an object, code modules can be


developed independently

Robust the language provide memory management and exception


handling ; strictly typed forcing few constraints on the programmer to
reduce potential issues at compile-time

Multithreaded allows you to write programs that do many things


simultaneously using the Thread class and Runnable interface
Architecture-neutral write once, run anywhere, any time, forever
design . ever changing hardware resources, processor upgrades, operating
system upgrades means that the a programming language may be
obsoletized or outdated. Java can be executed on any system
implementing the Java Virtual Machine.

Interpreted and high performance Java as an internet language can be


executed on any computer, as it is interpreted compiled into an
intermediate representation called Java bytecode, which then. translates
into any native machine code using a just-in-time compiler.

Distributed handles TCP/IP protocols and has methods for remote


invocation across a network.

Dynamic can be updated dynamically in a running system, due to run-


time verification and resolution of object accesses

Você também pode gostar