0% found this document useful (0 votes)
15 views

Java Solution for end Sem _Oct_Nov_2022-3

Uploaded by

soumyadeepg244
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Solution for end Sem _Oct_Nov_2022-3

Uploaded by

soumyadeepg244
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

[5926]-92

T.E. (Electronics / E&TC)


FUNDAMENTALS OF JAVA PROGRAMMING
(2019 Pattern) (Semester-I) (Elective-I) (304185 (C ))
Time: 2 ½ Hours] [Max. Marks :70
Solution

Q 1) a) Write a program to implement single inheritance in java. [5]


Solution:
Single Inheritance :

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

public class A {
public void display() {
System.out.println("I am a method from class A");
}
}

// B is inheriting display method of A


class B extends A {
public void print() {
System.out.println("I am a method from class B");
}

public static void main(String[] args) {


B objB = new B();
objB.display(); // Reusing the method of A named display
objB.print();
}
}
Output:
I am a method from class A
I am a method from class B

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{


void bark(){System.out.println("barking...");}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

}}

Output:

barking...
eating...
b) Write a method called
String Delete(String str, int m)
That returns the input str with mth element removed. [8 Marks]

class Main {

// Function to remove the last character of a string


public static String delete(String str,int m)
{

// Removing last character


// of a string using substring() method
str = str.substring(0, m)+ str.substring(m + 1);;

// Return the modified string


return str;
}

// Driver Code
public static void main(String args[])
{
// Given String str
String str = "GeeksForGeeks";
//int m=str.length()-1;
int m=5;

// Print the modified string


System.out.print(delete(str,m));
}
}

Output: GeeksorGeek

OR
public class Demo {
public static void main(String[] args) {
String str = "The Haunting of Hill House!";
System.out.println("String: "+str);
// removing character at position 7
int pos = 7;
String res = str.substring(0, pos) + str.substring(pos + 1);
System.out.println("String after removing a character: "+res);
}
}

OUTPUT:The Hauting of Hill House!

c) What is an array? How to declare an array in java? compare C array with java array. [5]

Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value. To declare an array, define the variable type with square brackets:
String[] cars; We have now declared a variable that holds an array of strings.
OR
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed.
OR
Array in java is a group of like-typed variables referred to by a common name. Arrays in Java
work differently than they do in C/C++. Following are some important points about Java
arrays.

● In Java, all arrays are dynamically allocated.


● Arrays are stored in contiguous memory [consecutive memory locations].
● Since arrays are objects in Java, we can find their length using the object property length.
This is different from C/C++, where we find length using sizeof.
● A Java array variable can also be declared like other variables with [] after the data type.
● The variables in the array are ordered, and each has an index beginning with 0.
● Java arrays can also be used as a static field, a local variable, or a method parameter.
● The size of an array must be specified by int or short value and not long.
● The direct superclass of an array type is Object.
● Every array type implements the interfaces Cloneable and java.io.Serializable.
● This storage of arrays helps us randomly access the elements of an array [Support
Random Access].
● The size of the array cannot be altered(once initialized). However, an array reference can
be made to point to another array.

Syntax:

datatype var-name[];
OR
datatype[] var-name;
OR
datatype []var-name;

You must be very careful when indexing an array in C. In Java, you immediately get an
ArrayIndexOutOfBoundsException when you try to access an illegal element in an array.
Another issue is that C arrays do not have a length property, unlike in Java.

Q 2) a) Explain static and dynamic polymorphism with suitable examples. [8]

Polymorphism in Java has two types: Runtime polymorphism (dynamic binding) and Compile
time polymorphism (static binding). Method overriding is an example of dynamic
polymorphism, while method overloading is an example of static polymorphism.

[4 Marks]
Static Polymorphism

In Java, static polymorphism is achieved through method overloading. Method overloading


means there are several methods present in a class having the same name but different
types/order/number of parameters.

At compile time, Java knows which method to invoke by checking the method signatures. So,
this is called compile time polymorphism or static binding. The concept will be clear from the
following example:

class DemoOverload{
public int add(int x, int y){ //method 1
return x+y;
}
public int add(int x, int y, int z){ //method 2
return x+y+z;
}

public int add(double x, int y){ //method 3


return (int)x+y;
}

public int add(int x, double y){ //method 4


return x+(int)y;
}
}

class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
}
}

[4 Marks]
Dynamic Polymorphism

Suppose a subclass overrides a particular method of the superclass. The polymorphic nature of
Java will use the overriding method. Let’s say we create an object of the subclass and assign it to
the superclass reference. Now, if we call the overridden method on the superclass reference then
the subclass version of the method will be called.

class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}

class MotorBike extends Vehicle{


public void move(){
System.out.println(“MotorBike can move and accelerate too!!”);
}
}
class Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
vh=new Vehicle();
vh.move(); // prints Vehicles can move!!
}
}

Q 2) 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 end of the previous strings.

In Java, two strings can be concatenated by using the + or += operator, or through the concat()
method, defined in the java.lang.String class.

This section will discuss how to perform string concatenation using both of these methods.

Example 1

The program below demonstrates how to concatenate two strings using the + operator in Java.

class HelloWorld {
public static void main( String args[] ) {
String first = "Hello";
String second = "World";

String third = first + second;


System.out.println(third);

// yet another way to concatenate strings


first += second;
System.out.println(first);
}
}
OR
class HelloWorld {

public static void main( String args[] ) {

String first = "Hello";


String second = "World";

String third = first.concat(second);

System.out.println(third);

Note: You can also directly concatenate the strings within the println method itself as
System.out.println(first + second); or System.out.println(first.concat(second));.

Q 2) c) Write a program to sort n numbers given in an array. [5]

public class SortAsc {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();

//Displaying elements of array after sorting


System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
Elements of original array:
52871
Elements of array sorted in ascending order:
12578

Q 3) a) Explain implementation of interface using suitable example. [7]

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method bodies. It is used to achieve abstraction and multiple inheritance
in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.


It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use the Java interface?

There are mainly three reasons to use interfaces. They are given below.

● It is used to achieve abstraction.


● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling

interface printable{

void print();

class A6 implements printable{


public void print(){System.out.println("Hello");}

public static void main(String args[]){

A6 obj = new A6();

obj.print();

Output: Hello

//Interface declaration: by first user

interface Drawable{

void draw();

//Implementation: by second user

class Rectangle implements Drawable{

public void draw(){System.out.println("drawing rectangle");}

class Circle implements Drawable{

public void draw(){System.out.println("drawing circle");}

//Using interface: by third user

class TestInterface1{

public static void main(String args[]){

Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()

d.draw();

}}

Output: drawing circle


interface Bank{

float rateOfInterest();

class SBI implements Bank{

public float rateOfInterest(){return 9.15f;}

class PNB implements Bank{

public float rateOfInterest(){return 9.7f;}

class TestInterface2{

public static void main(String[] args){

Bank b=new SBI();

System.out.println("ROI: "+b.rateOfInterest());

}}

Output: ROI: 9.15

Q 3) b) List out the advantages of packages. [5]


There are several advantages of using Java Packages, some of them, are as follows –

● Make easy searching or locating of classes and interfaces.


● Avoid naming conflicts. For example, there can be two classes with the name Student in
two packages, university.csdept.Student and college.itdept.Student
● Implement data encapsulation (or data-hiding).
● Provide controlled access: The access specifiers protected and default have access control
on package level. A member declared as protected is accessible by classes within the same
package and its subclasses. A member without any access specifier that is default
specifier is accessible only by classes in the same package.
● Reuse the classes contained in the packages of other programs.
● Uniquely compare the classes in other packages

Q 3) c) List out java API packages. [5]

Java API packages or built-in packages

Types of Packages in Java

They can be divided into two categories:

1. Java API packages or built-in packages and


2. User-defined packages.

Java provides a large number of classes grouped into different packages based on a particular
functionality.

Examples:

java.lang: It contains classes for primitive types, strings, math functions, threads, and
exceptions.

java.util: It contains classes such as vectors, hash tables, dates, Calendars, etc.

java.io: It has stream classes for Input/Output.

java.awt: Classes for implementing Graphical User Interface – windows, buttons, menus, etc.

java.net: Classes for networking

java. Applet: Classes for creating and implementing applets

Q 4) a) Explain the concept of the package using suitable examples. [8]


Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.

Some of the existing packages in Java are −

● java.lang − bundles the fundamental classes


● java.io − classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle groups of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.

● The String class which is present in java.lang package. To use the String class we don’t
need to write an import statement, because java by default adds all the classes of the
java.lang package in all the programs.
● We use the Properties class which is present in java. util package. To use this class we
have to write an import statement because this is in a different package. import
java.util.Properties;
● We use the File class which is present in the java.io package. To use file class we have to
write an import statement. import java.io.File;

There are two ways to access a different package class in our program-
● First is a fully qualified name as we see in the above statements. import java.io.File;
● Second is giving the super package name and including all the sub packages and
subclasses import java.io.*;

Package Naming Convention


● We can declare packages names using any standard Java naming rules.
● By the convention, however, packages begin with lowercase letters. In this way, it is very
easy for users to distinguish package names from class names when looking at an explicit
reference to a class.
● We know that all class names, again by the convention, begin with an only uppercase
letter.

● Packages names follow the reverse order of domain names


● For example, if a package name is university.engineering.csedept, then there are three
directories- university, engineering, and csedept such that csedept is present in
engineering and engineering is present in university.
● The package university can be considered as a top-level package while engineering is a
subpackage of university and cse dept is a sub-package of engineering.

In the following package:

java.util.Vector

● java is a top-level package


● util is a sub package
● and Vector is a class which is present in the subpackage util.
Q 4) b) Explain the concept of default interface with suitable examples. [9]

An interface in Java is similar to class but it contains only abstract methods and fields which are
final and static.

Since Java8 static methods and default methods are introduced in interfaces.

Default methods are methods that can have a body. The most important use of default methods in
interfaces is to provide additional functionality to a given type without breaking down the implementing
classes.

Default Methods - Unlike other abstract methods these methods can have a default
implementation. If you have a default method in an interface, it is not mandatory to override
(provide body) it in the classes that are already implementing this interface.

In short, you can access the default methods of an interface using the objects of the
implementing classes.

Syntax of default methods:


public interface Vehicle {

void cleanVehicle();

default void startVehicle() {


System.out.println("Vehicle is starting");
}
}

public class Car implements Vehicle {


@Override
public void cleanVehicle() {
System.out.println("Cleaning the vehicle");
}

public static void main(String args[]){


Car car = new Car();
car.cleanVehicle();
car.startVehicle();
}
}
Output:
Cleaning the vehicle
Vehicle is starting

Example
interface MyInterface{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface");
}
}
public class InterfaceExample implements MyInterface{
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.display();
}
}

Output

display method of MyInterface

Q 5) a) What is Multithreading? Explain ways to create a thread in java. [9]

• Multithreading in java is a process of executing multiple processes simultaneously


• A program is divided into two or more subprograms, which can be implemented at the
same time in parallel.
• Multiprocessing and multithreading, both are used to achieve multitasking.

• Java Multithreading is mostly used in games, animation etc.

• Threads are implemented in the form of objects.


• The run() and start() are two inbuilt methods
• The run() method is the heart and soul of any thread which helps to thread
implementation
• It makes up the entire body of a thread
• The run() method can be initiated with the help of start() method.

Threads can be created by using two mechanisms :

1. Extending the Thread class


2. Implementing the Runnable Interface

1. By Extending Thread class


class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}

Output: thread is running…

2. By implementing Runnable interface


▪ Define a class that implements Runnable interface.
▪ The Runnable interface has only one method, run(), that is to be defined in the
method with code to be executed by the thread.
lass Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); t1.start();
}}

Output: thread is running…

Q 5) b) Explain applet and differentiate between applet and application. [9]

Explanation of Applet [ Marks]


What is Applet?
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at the client side. An applet is embedded in an HTML page using the
APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the website more dynamic and entertaining.
● Important points :
1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web browser
or an applet viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is
handled with various AWT methods, such as drawString().

The difference between Application and Applet:[5 Marks any 5 Points]

Parameters Java Application Java Applet

Definition Applications are just like a Java Applets are small Java programs that
program that can be executed are designed to be included with the
independently without using HTML web document. They require a
the web browser. Java-enabled web browser for
execution.

main () The application program The applet does not require the main()
method requires a main() method for method for its execution, instead init()
its execution. method is required.

Compilation The “javac” command is used Applet programs are compiled with
to compile application the “javac” command and run using
programs, which are then either the “appletviewer” command or
executed using the “java” the web browser.
command.

File access Java application programs Applets don’t have local disk and
have full access to the local file network access.
system and network.

Access level Applications can access all Applets can only access
kinds of resources available on browser-specific services. They don’t
the system. have access to the local system.

Installation First and foremost, the The Java applet does not need to be
installation of a Java installed beforehand.
application on the local
computer is required.

Execution Applications can execute the Applets cannot execute programs from
programs from the local
system. the local machine.

Program An application program is An applet program is needed to


needed to perform some tasks perform small tasks or part of them.
directly for the user.

Run It cannot run on its own; it It cannot start on its own, but it can be
needs JRE to execute. executed using a Java-enabled web
browser.

Connection Connectivity with other servers It is unable to connect to other servers.


with servers is possible.

Read and It supports the reading and It does not support the reading and
Write writing of files on the local writing of files on the local computer.
Operation computer.

Security Applications can access the Executed in a more restricted


system’s data and resources environment with tighter security.
without any security They can only use services that are
limitations. exclusive to their browser.

Restrictions Java applications are Applet programs cannot run on their


self-contained and require no own, necessitating the maximum level
additional security because of security.
they are trusted.

Q 6) a)Explain the concept of thread priority with the help of suitable examples. [9]

Concept of thread priority along with syntax of setPriority and getPriority method[04 marks]

Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.

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 highest priority is selected by the scheduler to be
executed first.
The default priority of a thread is 5. Thread class in Java also provides several priority constants to
define the priority of a thread. These are:

1. MIN_PRIORITY = 1

2. NORM_PRIORITY = 5

3. MAX_PRIORTY = 10

These constants are public, final, and static members of the Thread class.

Setter & Getter Method of Thread Priority

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of
the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method


updates or assigns the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum)
to 10 (maximum).

Example of priority of a Thread:

FileName: ThreadPriorityExample.java

// Importing the required classes

import java.lang.*;

public class ThreadPriorityExample extends Thread

// Method 1

// Whenever the start() method is called by a thread

// the run() method is invoked

public void run()

// the print statement

System.out.println("Inside the run() method");

}
// the main method

public static void main(String argvs[])

// Creating threads with the help of ThreadPriorityExample class

ThreadPriorityExample th1 = new ThreadPriorityExample();

ThreadPriorityExample th2 = new ThreadPriorityExample();

ThreadPriorityExample th3 = new ThreadPriorityExample();

// We did not mention the priority of the thread.

// Therefore, the priorities of the thread is 5, the default value

// 1st Thread

// Displaying the priority of the thread

// using the getPriority() method

System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 2nd Thread

// Display the priority of the thread

System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 3rd Thread

// // Display the priority of the thread

System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// Setting priorities of above threads by

// passing integer arguments

th1.setPriority(6);

th2.setPriority(3);

th3.setPriority(9);

// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 3

System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 9

System.out.println("Priority of the thread th3 is : " + th3.getPriority());

// Main thread

// Displaying name of the currently executing thread

System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());

System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

// Priority of the main thread is 10 now

Thread.currentThread().setPriority(10);

System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

Q 6) b)Write a java code using buffer Reader class to read names from users. [5]

// Java program to demonstrate BufferedReader


import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;

public class Test

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

//Enter data using BufferReader

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

// Reading data using readLine

String name = reader.readLine();

// Printing the read line

System.out.println(name);

OR

package com.javatpoint;

import java.io.*;

public class BufferedReaderExample{

public static void main(String args[])throws Exception{

InputStreamReader r=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");

String name=br.readLine();

System.out.println("Welcome "+name);

}
Q 6) c) Explain syntax of try and catch block . [4]

Java try-catch block


1. The try is used to define a block of code in which exceptions may occur.

2. One or more catch clauses matching a specific exception will handle the occurred
exception.

OR

public class TryCatchExample3 {

public static void main(String[] args) {

try

int data=50/0; //may throw exception

// if exception occurs, the remaining statement will not exceute

System.out.println("rest of the code");

// handling the exception

catch(ArithmeticException e)

System.out.println(e);
}

Q 7) a) Explain the Graphics class in java. List out and explain any three drawing methods
from graphics class. [9]

Explanation of the Graphics class in java[3 Marks]


• The Graphics class is the abstract base class.

• A Graphics object manages a graphics context and draws pixels on the screen that represent
text and other graphical objects (e.g., lines, ellipses, rectangles and other polygons).

• Graphics objects contain methods for drawing, font manipulation, color manipulation and
the like.
• Main feature in java is creating a graphical interface.
• Graphics in any language gives a wonderful look and feel to the users.
• Two packages that are mainly used to draw graphics.
○ Applet package
○ awt package

Listing out and Explanation of any three drawing methods from graphics class [2 Marks each]

• drawString(String str, int x, int y)

• Draws the text given by the specified string, using this graphics context's current font and
color.
• abstract void drawLine(int x1, int y1, int x2, int y2)

• Draws a line, using the current color, between the points (x1, y1)
and (x2, y2) in this graphics context's coordinate system.
• abstract void drawOval(int x, int y, int width, int height)
• Draws the outline of an oval.
• drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)

• Draws the outline of a circular or elliptical arc covering the specified rectangle.
• drawRect(int x, int y, int width, int height)
• Draws the outline of the specified rectangle.

Q 7) b) Create an application to create window in java deriving from the Frame class to
display message “Welcome to World of Java”. [8]
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("Welcome to world of Java"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

Q 8) a) Write a java program using Swing to display “Welcome to java”. [7]


import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JTextField b = new JTextField("Welcome to Java");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
Output:
Q 8) b) Explain the hierarchy of AWT. [5]
AWT classes
• The AWT classes are contained in the java.awt package.

• It is one of Java‟s largest packages.

Hierarchy Of AWT
The hierarchy of Java AWT classes are given below, all the classes are available in java.awt
package.

Component class

Component class is at the top of AWT hierarchy. It is an abstract class that encapsulates all the
attributes of a visual component. A component object is responsible for remembering the current
foreground and background colors and the currently selected text font.

Container
Container is a component in AWT that contains another component like button, text field, tables
etc. Container is a subclass of component class. Container class keeps track of components that
are added to another component.

Panel

Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or
border. It is a container that is used for holding components.

Window class

Window class creates a top level window. Window does not have borders and a menubar.

Frame

Frame is a subclass of Window and has resizing canvas. It is a container that contains several
different components like button, title bar, textfield, label etc. In Java, most of the AWT
applications are created using Frame window. Frame class has two different constructors,

Q 8) c) Write a code in java to open a file for reading. [5]

package practical;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader
("C:\\Users\\Lenovo\\Desktop\\javaprac\\3FileReader\\A.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
fr.close();
}
}

Output:

You might also like