0% found this document useful (0 votes)
17 views12 pages

FJP Micro 123

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views12 pages

FJP Micro 123

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit 3- Write a method called public int add(int x, double y){ //method 4

String Delete(String str, int m) return x+(int)y;


That returns the input str with mth element }
removed. }
class Main { class Test{
public static String delete(String str,int m) public static void main(String[] args){
{ DemoOverload demo=new DemoOverload();
str = str.substring(0, m)+ str.substring(m + 1);; System.out.println(demo.add(2,3));
return str; //method 1 called
} System.out.println(demo.add(2,3,4)); //method 2
public static void main(String args[]) called
{ System.out.println(demo.add(2,3.4)); //method 4
String str = "GeeksForGeeks"; called
//int m=str.length()-1; System.out.println(demo.add(2.5,3)); //method 3
int m=5; called
System.out.print(delete(str,m)); }
} }
} Dynamic Polymorphism
Output: GeeksorGeek Suppose a subclass overrides a particular method
a) Explain static and dynamic polymorphism of the superclass. The polymorphic nature of
with suitable examples. [8] Java will use the overriding method. Let’s say we
Polymorphism in Java has two types: Runtime create an object of the subclass and assign it to
polymorphism (dynamic binding) and Compile the superclass reference. Now, if we call the
time polymorphism (static binding). Method overridden method on the superclass reference
overriding is an example of dynamic then
polymorphism, while method overloading is an the subclass version of the method will be called.
example of static polymorphism. class Vehicle{
Static Polymorphism public void move(){
In Java, static polymorphism is achieved through System.out.println(“Vehicles can move!!”);
method overloading. Method overloading }
means there are several methods present in a }
class having the same name but different class MotorBike extends Vehicle{
types/order/number of parameters. public void move(){
At compile time, Java knows which method to System.out.println(“MotorBike can move and
invoke by checking the method signatures. So, accelerate too!!”);
this is called compile time polymorphism or static }
binding. The concept will be clear from the }
following example: class Test{
class DemoOverload{ public static void main(String[] args){
public int add(int x, int y){ //method 1 Vehicle vh=new MotorBike();
return x+y; vh.move(); // prints MotorBike can move and
} accelerate too!!
public int add(int x, int y, int z){ //method 2 vh=new Vehicle();
return x+y+z; vh.move(); // prints Vehicles can move!!
} }
public int add(double x, int y){ //method 3 }
return (int)x+y; b) Write a program to join two strings. [5]
}
Concatenation is the process of combining two or }
more strings to form a new string by }
subsequently appending the next string to the Output:
end of the previous strings. Elements of original array:
In Java, two strings can be concatenated by using 52871
the + or += operator, or through the concat() Elements of array sorted in ascending order:
method, defined in the java.lang.String class. 12578
This section will discuss how to perform string Q. What is method overriding? Explain the rules
concatenation using both of these methods. to
Example 1 be followed while method overriding.
The program below demonstrates how to If subclass (child class) has the same method as
concatenate two strings using the + operator in declared in the parent class, it is known as
Java. method
class HelloWorld { overriding in Java.If a subclass provides the
public static void main( String args[] ) { specific implementation of the method that has
String first = "Hello"; been declared by one of its parent class, it
String second = "World"; isknown as method overriding.
String third = first + second; *Usage of Java Method Overriding
System.out.println(third); Method overriding is used to provide the specific
first += second; implementation of a method which is already
System.out.println(first); provided by its superclass.
} Method overriding is used for runtime
} polymorphism
c) Write a program to sort n numbers given in an *Rules for Java Method Overriding
array. [5] 1.The method must have the same name as in the
public class SortAsc { parent class
public static void main(String[] args) { 2.The method must have the same parameter as
int [] arr = new int [] {5, 2, 8, 7, 1}; in the parent class.
int temp = 0; 3.There must be an IS-A relationship (inheritance).
System.out.println("Elements of original array: "); Method overriding is one of the way by which
for (int i = 0; i < arr.length; i++) { java achieve Run Time Polymorphism.The version
System.out.print(arr[i] + " "); of a method that is executed will be determined
} by the object that is used to invoke it.
for (int i = 0; i < arr.length; i++) { If an object of a parent class is used to invoke the
for (int j = i+1; j < arr.length; j++) { method, then the version in the parent class will
if(arr[i] > arr[j]) { be executed, but if an object of the subclass is
temp = arr[i]; usedto invoke the method, then the version in
arr[i] = arr[j]; the child class will be executed.
arr[j] = temp; In other words, it is the type of theobject being
} referred to (not the type of the reference
} variable) that determines which version of an
} overridden method will be executed.
System.out.println(); Q.What is the meaning of inheritance in Java?
System.out.println("Elements of array sorted in Explain each type of inheritance with the help of
ascending order: "); suitable example and diagram
for (int i = 0; i < arr.length; i++) { Inheritance in Java is a mechanism in which
System.out.print(arr[i] + " "); oneobject acquires all the properties (field-
} inputdata/output
data)and behaviors (Methods)of a parentobject. void weep(){System.out.println("weeping...");}
It is an important part of OOPs (Object Oriented }
programming system). class TestInheritance2{
The idea behind inheritance in Java is that you public static void main(String args[]){
cancreate new classes that are built upon existing BabyDog d=new BabyDog();
classes.When you inherit from an existing class, d.weep();
you can reusemethods and fields of the parent d.bark();
class. d.eat();
Moreover, youcan add new methods and fields in }}
your current class also. Hierarchical Inheritance: When multiple classes
The syntax of Java Inheritance are derived from a class and further more classes
class Subclass-name extends Superclass-name are derived from these derived classes.
{ //methods and fields } Example
The extends keyword indicates that you are class Animal{
making a new class that derives from an existing }
class. The meaning of "extends" is to increase the void eat(){System.out.println("eating...");}
functionality. }
*Types of inheritance in java class Dog extends Animal{
On the basis of class, there can be three types of void bark(){System.out.println("barking...");}
inheritance in java: single, multilevel and }
hierarchical. class Cat extends Animal{
In java programming, multiple and hybrid void meow(){System.out.println("meowing...");}
inheritance is not provided. }
*Single Inheritance: In this case only one class is class TestInheritance3{
derived from another class public static void main(String args[]){
class Animal{ Cat c=new Cat();
void eat(){System.out.println("eating...");} c.meow();
} c.eat();
class Dog extends Animal{ }}
void bark(){System.out.println("barking...");} Q.Write a program to implement single
} inheritance in
class TestInheritance{ java.
public static void main(String args[]){ Single Inheritance :
Dog d=new Dog(); When a class inherits another class, it is known as
d.bark(); a single inheritance. In the example given below,
d.eat(); Dog class inherits the Animal class, so there is the
}} single inheritance.
*Multilevel Inheritance: In this case one class is public class A {
derived from a class which is also derived from public void display() {
another class System.out.println("I am a method from class A");
Example }
class Animal{ }
void eat(){System.out.println("eating...");} class B extends A {
} public void print() {
class Dog extends Animal{ System.out.println("I am a method from class B");
void bark(){System.out.println("barking...");} }
} public static void main(String[] args) {
class BabyDog extends Dog{ B objB = new B();
objB.display();
display
objB.print();
}
}
Output:
I am a method from class A
I am a method from class B
Unit 4 a) Explain implementation of interface annotations ) providing access protection and
using suitable example. [7] namespace management.
Interface in Java Some of the existing packages in Java are −
An interface in Java is a blueprint of a class. It has ● java.lang − bundles the fundamental classes
static constants and abstract methods. ● java.io − classes for input , output functions are
The interface in Java is a mechanism to achieve bundled in this package
abstraction. There can be only abstract methods Programmers can define their own packages to
in the Java interface, not method bodies. It is bundle groups of classes/interfaces, etc. It is a
used to achieve abstraction and multiple good practice to group related classes
inheritance in Java. implemented by you so that a programmer can
In other words, you can say that interfaces can easily determine that the classes, interfaces,
have abstract methods and variables. It cannot enumerations, and annotations are related.
have a method body. ●The String class which is present in java.lang
Java Interface also represents the IS-A package. To use the String class we don’t
relationship. need to write an import statement, because java
It cannot be instantiated just like the abstract by default adds all the classes of the
class. java.lang package in all the programs.
Since Java 8, we can have default and static ●We use the Properties class which is present in
methods in an interface. java. util package. To use this class we have to
Since Java 9, we can have private methods in an write an import statement because this is in a
interface. different package. import
Why use the Java interface? java.util.Properties;
There are mainly three reasons to use interfaces. ●We use the File class which is present in the
They are given below. java.io package. To use file class we have to
● It is used to achieve abstraction. write an import statement. import java.io.File;
● By interface, we can support the functionality There are two ways to access a different package
of multiple inheritance. class in our program
● It can be used to achieve loose coupling ●First is a fully qualified name as we see in the
interface printable{ above statements. import java.io.File;
void print(); ●Second is giving the super package name and
} including all the sub packages and subclasses
class A6 implements printable{ import java.io.*;
public void print(){System.out.println("Hello");} Package Naming Convention
public static void main(String args[]){ ●We can declare packages names using any
A6 obj = new A6(); standard Java naming rules.
obj.print(); ●By the convention, however, packages begin
} with lowercase letters. In this way, it is very
} easy for users to distinguish package names from
Output: Hello class names when looking at an explicit
QExpain the concept of package using example reference to a class.
Packages are used in Java in order to prevent ●We know that all class names, again by the
naming conflicts, to control access, to make convention, begin with an only uppercase
searching/locating and usage of classes, letter.
interfaces, enumerations and annotations easier, ●Packages names follow the reverse order of
etc. domain names
A Package can be defined as a grouping of related ●For example, if a package name is
types (classes, interfaces, enumerations and university.engineering.csedept, then there are
three directories- university, engineering, and
csedept such that csedept is present in }}
engineering and engineering is present in Output:
university. Cleaning the vehicle
●The package university can be considered as a Vehicle is starting
top-level package while engineering is a Q.What are the advantages of packages in Java?
subpackage of university and cse dept is a sub- List and explain various Java API packages.
package of engineering. ANS: ● Make easy searching or locating of classes
In the following package: and interfaces.● Avoid naming conflicts. For
java.util.Vector example, there can be two classes with the name
●java is a top-level package Student in two packages,
●util is a sub package and Vector is a class which university.csdept.Student and
is present in the subpackage util. college.itdept.Student● Implement data
b) Explain the concept of default interface with encapsulation (or data-hiding). ● Provide
suitable examples. [9] controlled access: The access specifiers protected
An interface in Java is similar to class but it and default have access control on package level.
contains only abstract methods and fields which A member declared as protected is accessible by
are final and static. classes within the same package and its
Since Java8 static methods and default methods subclasses. A member without any access
are introduced in interfaces. specifier that is default specifier is accessible only
Default methods are methods that can have a by classes in the same package.● Reuse the
body. The most important use of default methods classes contained in the packages of other
in interfaces is to provide additional functionality programs.● Uniquely compare the classes in
to a given type without breaking down the other packages
implementing classes. List and explain variousJava API packages:
Default Methods - Unlike other abstract methods 1.Java.lang: lang stands for language. The Java
these methods can have a default language package consists of java classes and
implementation. If you have a default method in interfaces that form the core of the Java language
an interface, it is not mandatory to override and the JVM. It is a fundamental package that is
(provide body) it in the classes that are already useful for writing and executing all Java
implementing this interface. programs.Examples are
In short, you can access the default methods of classes, objects, String, Thread, predefined data
an interface using the objects of the types, etc. It is imported automatically into the
implementing classes. Java programs.2. Java.io: io stands for input and
Syntax of default methods: output. It provides a set of I/O streams that are
public interface Vehicle { used to read and write data to files. A stream
void cleanVehicle(); represents a flow of data from one place to
default void startVehicle() { another place.3. Java util: util stands
System.out.println("Vehicle is starting"); for utility. It contains a collection of useful utility
} classes and related interfaces that implement
} data structures like LinkedList, Dictionary,
public class Car implements Vehicle { HashTable, stack, vector, Calender, data utility,
public void cleanVehicle() { etc.4. Java.net: net stands for network. It contains
System.out.println("Cleaning the vehicle"); networking classes and interfaces for networking
} operations. The programming related to client-
public static void main(String args[]){ server can be done by using this package.
Car car = new Car();
car.cleanVehicle();
car.startVehicle();
System.out.println("thread is running...");
Unit 5 What is Multithreading? Explain ways to }
create a thread in java. [9] public static void main(String args[])
* Multithreading in java is a process of executing {
multiple processes simultaneously Multi3 m1=new Multi3();
* A program is divided into two or more Thread t1 =new Thread(m1); t1.start();
subprograms, which can be implemented at the }}
same time in parallel. Output: thread is running…
* Multiprocessing and multithreading, both are Explain applet and differentiate between applet
used to achieve multitasking. and application. [9]
* Java Multithreading is mostly used in games, Applet
animation etc. An applet is a Java program that can be
* Threads are implemented in the form of embedded into a web page. It runs inside the web
objects. browser and works at the client side. An applet is
•The run() and start() are two inbuilt methods embedded in an HTML page using the
•The run() method is the heart and soul of any APPLET or OBJECT tag and hosted on a web
thread which helps to thread server.
implementation Applets are used to make the website more
•It makes up the entire body of a thread dynamic and entertaining.
•The run() method can be initiated with the help ●Important points :
of start() method. 1.All applets are sub-classes (either directly or
Threads can be created by using two mechanisms indirectly) of java.applet.Applet class.
1. Extending the Thread class 2.Applets are not stand-alone programs. Instead,
2. Implementing the Runnable Interface they run within either a web browser
1.By Extending Thread class or an applet viewer. JDK provides a standard
class Multi extends Thread applet viewer tool called applet viewer.
{ 3.In general, execution of an applet does not
public void run() begin at main() method.
{ 4.Output of an applet window is not performed
System.out.println("thread is running..."); by System.out.println(). Rather it is
} handled with various AWT methods, such as
public static void main(String args[]) drawString().
{ Explain the concept of thread priority with the
Multi t1=new Multi(); help of suitable examples. [9]
t1.start(); Concept of thread priority along with syntax of
} setPriority and getPriority method[04 marks]
} Priority of a Thread (Thread Priority)
Output: thread is running… Each thread has a priority. Priorities are
2.By implementing Runnable interface represented by a number between 1 and 10. In
▪ Define a class that implements Runnable most cases, the thread scheduler schedules the
interface. threads according to their priority (known as
▪ The Runnable interface has only one method, preemptive scheduling). But it is not guaranteed
run(), that is to be defined in the because it depends on JVM specification that
method with code to be executed by the thread. which scheduling it chooses. Note that not only
lass Multi3 implements Runnable JVM a Java programmer can also assign the
{ priorities of a thread explicitly in a Java program.
public void run() Thread priorities are represented by a number
{ from 1 to 10 that specifies the relative priority of
one thread to another. The thread with the System.out.println("Priority of the thread th1 is : "
highest priority is selected by the scheduler to be + th1.getPriority());
executed first System.out.println("Priority of the thread th2 is : "
The default priority of a thread is 5. Thread class + th2.getPriority());
in Java also provides several priority constants to System.out.println("Priority of the thread th3 is : "
define the priority of a thread. These are: + th3.getPriority());
1. MIN_PRIORITY = 1 System.out.println("Currently Executing The
2. NORM_PRIORITY = 5 Thread : " + Thread.currentThread().getName());
3. MAX_PRIORTY = 10 System.out.println("Priority of the main thread is
These constants are public, final, and static : " + Thread.currentThread().getPriority());
members of the Thread class. Thread.currentThread().setPriority(10);
Setter & Getter Method of Thread Priority System.out.println("Priority of the main thread is
public final int getPriority(): The : " + Thread.currentThread().getPriority());
java.lang.Thread.getPriority() method returns the }
priority of the given thread. }
public final void setPriority(int newPriority): The b)Write a java code using buffer Reader class to
java.lang.Thread.setPriority() method read names from users. [5]
updates or assigns the priority of the thread to import java.io.BufferedReader;
newPriority. The method throws import java.io.IOException;
IllegalArgumentException if the value newPriority import java.io.InputStreamReader;
goes out of the range, which is 1 (minimum) public class Test
to 10 (maximum). {
Example of priority of a Thread: public static void main(String[] args) throws
FileName: ThreadPriorityExample.java IOException
import java.lang.*; {
public class ThreadPriorityExample extends BufferedReader reader = new
Thread BufferedReader(new
{ InputStreamReader(System.in));
public void run() String name = reader.readLine();
{ System.out.println(name);
System.out.println("Inside the run() method"); }}
} public static void main(String argvs[]) Explain syntax of try and catch block . [4]
{ Java try-catch block
ThreadPriorityExample th1 = new 1. The try is used to define a block of code in
ThreadPriorityExample(); which exceptions may occur.
ThreadPriorityExample th2 = new 2. One or more catch clauses matching a specific
ThreadPriorityExample(); exception will handle the occurred
ThreadPriorityExample th3 = new exception.
ThreadPriorityExample(); public class TryCatchExample3 {
System.out.println("Priority of the thread th1 is : " public static void main(String[] args) {
+ th1.getPriority()); try
System.out.println("Priority of the thread th2 is : " {
+ th2.getPriority()); int data=50/0; //may throw exception
System.out.println("Priority of the thread th2 is : " System.out.println("rest of the code");
+ th2.getPriority()); }
th1.setPriority(6); catch(ArithmeticException e)
th2.setPriority(3); {
th3.setPriority(9); System.out.println(e); }}
Q.With reference to exception handling, explain Each thread gets a time slice, the time slice
the depends on its priority (importance).
terms try, catch and throw. If a stop() method is executed for a thread then it
ANS: try:*The try is used to define a block of code goes into the dead state. if sleep(), suspend() or
in which exceptions may occur.*One or more block() method is called, the thread enters into
catch clauses matching a specific exception will the blocked state.
handle the occurred exception. 3BLOCKED STATE-A thread is in this state when it
Finally:*A finally block encloses code that is is blocked because of some resource or if a delay
always executed at some point after the try block, (sleeping) is required. The thread enters into this
whether an exception was thrown or not.*Even if state by the sleep(), suspend() or block()
there is a return statement in the try block, the methods.
finally block executes right after the return The thread enters into this state from the active
statement is encountered, and before the return state.
executes! The thread exits from this state when the
Catch:The "catch" block is used to handle the resume() or notify()method is called. In case if the
exception. It must be preceded by try block which thread is blocked for some event to occur using
means we can't use catch block alone. It can be the block() method, then it is to be notified about
followed by finally block later. the occurrence by the notify() method.
Throw:The "throw" keyword is used to throw an . In case if the thread is suspended using the
exception. suspend() method(), then it is to be resumed
Throws:The "throws" keyword is used to declare using the resume() method().
exceptions. It specifies that there may occur an In case if the thread is made to go to sleep by the
exception in the method. It doesn't throw an sleep() method, then the thread automatically
exception. It is always used with method wakes up after the specified milliseconds in the
signature. brackets while calling the sleep() method. This
Q.Explain life-cycle of a thread. What are the indicates that when calling the sleep() method,
ways to the delay for which the thread is expected to
create a thread in a Java program? sleep, must be passed in the brackets. For e.g
ANS: A thread may have to go through the Thread sleep(5000), will make the current thread
following states during its life time: sleep for 5000 milliseconds.
1 New Born State-A thread is in this state when it 4 DEAD STATE-The thread goes into this state
is created or made. when it is stopped by the stop() method.
When we call the start() method for a thread it *CREATING THREAD
enters into the runnable state. The thread will There are two ways of creating threads. We have
remain in this state until its turn comes to be in an interface named as Runnable and a class
the running state. named as Thread. Based on this, there are two
. If a stop() method is executed for a thread then ways to create thread:
it goes into the dead state. 1 By Implementing the Runnable interface.
2 Blocked State-This is the most important state 2 By Extending the Thread class.
of a thread When the thread is started, it comes Q.What are the types of errors that occur in a
in this state. The thread is in active state means, Java program? Write a Java program to handle
that it can be in either runnable state or running arithmetic exception.
state. ANS: Type of Error:
Only one thread can be in running state at any 1.Compile Time Error
given time. All other threads can be in runnable, if All syntax errors will be detected and displayed by
they are ready for execution. Based on the JAVA compiler & therefore errors are known as
priorities time slices are allocated to each thread compile time errors.
in the runnable state. e.g ; missing
2.Run Time Error
A program may compile successfully but may not
run
properly and iving wrong output due to logical
errors.
e.g divide by zero error
accessing an element that is out of bounds
passing a parameter not valid value or range.
JAVA PROGRAM FOR HANDLE ARITHMATIC
EXCEPTION
Java
import java.util.Scanner;
public class SimpleArithmeticExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter denominator: ");
int denominator = scanner.nextInt();
try }
int result = divideNumbers(numerator,
denominator);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
}
private static int divideNumbers(int numerator,
int
denominator) {
if (denominator==0)
throw new ArithmeticException("Division by zero
is
not allowed.");
}
return numerator / denominator;
}
}
Unit6 a) Explain the Graphics class in java. List {
out and explain any three drawing methods Frame fm=new Frame();
from graphics class. [9] Label lb = new Label("Welcome to world of Java");
Explanation of the Graphics class in java[3 Marks] fm.add(lb);
* The Graphics class is the abstract base class. fm.setSize(300, 300); //setting frame size.
* A Graphics object manages a graphics context fm.setVisible(true); //set frame visibilty true
and draws pixels on the screen that represent }
text and other graphical objects (e.g., lines, public static void main(String args[])
ellipses, rectangles and other polygons). {
* Graphics objects contain methods for drawing, Testawt ta = new Testawt();
font manipulation, color manipulation and }
the like. }
•Main feature in java is creating a graphical Write a java program using Swing to display
interface. “Welcome to java”. [7]
•Graphics in any language gives a wonderful look import javax.swing.*;
and feel to the users. public class example{
•Two packages that are mainly used to draw public static void main(String args[]) {
graphics. JFrame a = new JFrame("example");
○Applet package JTextField b = new JTextField("Welcome to Java");
○awt package b.setBounds(50,100,200,30);
Listing out and Explanation of any three drawing a.add(b);
methods from graphics class [2 Marks each] a.setSize(300,300);
* drawString(String str, int x, int y) a.setLayout(null);
* Draws the text given by the specified string, a.setVisible(true);
using this graphics context's current font and }
color. }
* abstract void drawLine(int x1, int y1, int x2, int ) Explain the hierarchy of AWT. [5]
y2) AWT classes
* Draws a line, using the current color, between * The AWT classes are contained in the java.awt
the package.
points (x1, y1) and (x2, y2) in this graphics * It is one of Java‟s largest packages.
context's coordinate system. Hierarchy Of AWT
* abstract void drawOval(int x, int y, int width, int The hierarchy of Java AWT classes are given
height) below, all the classes are available in java.awt
* Draws the outline of an oval. package.
•drawArc(int x, int y, int width, int height, int Component class
startAngle, int arcAngle) Component class is at the top of AWT hierarchy. It
•Draws the outline of a circular or elliptical arc is an abstract class that encapsulates all the
covering the specified rectangle. attributes of a visual component. A component
•drawRect(int x, int y, int width, int height) object is responsible for remembering the current
•Draws the outline of the specified rectangle. foreground and background colors and the
b) Create an application to create window in java currently selected text font.
deriving from the Frame class to display message Container
“Welcome to World of Java”. [8] Container is a component in AWT that contains
import java.awt.*; another component like button, text field, tables
public class Testawt etc. Container is a subclass of component class.
{ Container class keeps track of components that
Testawt() are added to another component.
Panel Q.What is AWT in Java? Explain the limitations of
Panel class is a concrete subclass of Container. AWT. How events are handled in AWT
Panel does not contain title bar, menu bar or components.
border. It is a container that is used for holding ANS: Java AWT (Abstract Window Toolkit) is an
components. API to
Window class develop Graphical User Interface (GUI) or
Window class creates a top level window. windowsbased applications in Java.
Window does not have borders and a menubar. Java AWT components are platform-dependent
Frame i.e. components are displayed according to the
Frame is a subclass of Window and has resizing view of operating system. AWT is heavy weight
canvas. It is a container that contains several i.e. its components are using the resources of
different components like button, title bar, underlying operating system (OS).
textfield, label etc. In Java, most of the AWT The java.awt package provides classes for AWT
applications are created using Frame window. API
Frame class has two different constructors, such as TextField, Label, TextArea, RadioButton,
c) Write a code in java to open a file for reading. CheckBOX Choice, List etc.
[5] Event Handling: Event Handling is the mechanism
package practical; that controls the event and decides what should
import java.io.FileReader; happen if an event occurs. This mechanism have
public class FileReaderExample { the code which is known as event handler that is
public static void main(String args[])throws executed when an event occurs. Java Uses the
Exception Delegation Event Model to handle the events.
{ Event and Listener (Java Event Handling) Changing
FileReader fr=new FileReader the state of an object is known as an event. For
("C:\\Users\\Lenovo\\Desktop\\javaprac\\3FileRe example,
ader\\A.txt"); click on button, dragging mouse etc.
int i; Source: Events are generated from the source.
while((i=fr.read())!=-1) There are various sources like buttons,
{ checkboxes, list,
System.out.print((char)i); menu-item, choice, scrollbar, text components,
} windows, etc., to generate events.
fr.close(); Listeners: Listeners are used for handling the
} events generated from the source. Each of these
} listeners represents interfaces that are
Q.What are stream classes in Java? List and responsible for handling events.
explain Registering the Source With Listener
the methods of Byte Array Output Stream class. Different Classes provide different registration
ANS: STREAM:- methods.
A stream is a sequence of data. I/O Stream refers Flow of Event Handling
to a stream that is unlikely a method to User Interaction with a component is required to
sequentially access a file. I/O Stream means an generate an event.
input source or output destination representing The object of the respective event class is created
different types of sources e.g. disk files. The automatically after event generation, and it holds
java.io package provides classes that allow you to all information of the event source.
convert between Unicode character The newly created object is passed to the
streams and byte streams of non-Unicode text. methods of the registered listener.
*Input Stream: reads data from the source. The method executes and returns the result.
*Output Stream: writes data to a destination.

You might also like