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

Java Summer 23

Model Ans Paper
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java Summer 23

Model Ans Paper
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Java Summer 23

1. Attempt any FIVE of the following: 10


a) Define the terms with example
i) Class
ii) Object
Ans.Class: A class is a user defined data type which groups data members and its associated
functions together.
Object: It is a basic unit of Object Oriented Programming and represents the real life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods

b) Enlist any two access specifier with syntax.


Ans.Access specifiers (also known as access modifiers) are keywords that set the accessibility of
classes, methods, and other members. They control where the members of a class can be
accessed from. Here are four access specifiers in Java:
1. Public
 Description: Members declared as public can be accessed from any other class in any
package.
 Syntax:
public class MyClass {
public int myVariable;
public void myMethod() {
// method implementation
}
}
2. Private
 Description: Members declared as private can only be accessed within the same class.
They are not visible to any other class, even those in the same package.
 Syntax:
public class MyClass {
private int myVariable;
private void myMethod() {
// method implementation
}
}
3. Protected
 Description: Members declared as protected can be accessed within the same package
and by subclasses (even if they are in different packages).
 Syntax:
public class MyClass {
protected int myVariable;
protected void myMethod() {
// method implementation
}
}

c) Give a syntax to create a package and accessing package in java


Ans. Creating a Package:
package packageName;

public class ClassName {


// Class implementation
}
Accessing a Package:
import packageName.ClassName; // Import a specific class
// or
import packageName.*; // Import all classes from the package

public class Main {


public static void main(String[] args) {
ClassName obj = new ClassName();
obj.method(); // Call a method of the imported class
}
}

d) Give a syntax of following thread method


i) Notify ( )
ii) Sleep ( )
Ans.
i) notify()
 Description: The notify() method is used to wake up a single thread that is waiting on
the object's monitor. It must be called from within a synchronized block or method, and it
signals one waiting thread to wake up and compete for the lock.
 Syntax:
public final void notify()

ii) sleep()
 Description: The sleep(long millis) method is a static method of the Thread class that
causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds. It can throw InterruptedException.
 Syntax:
public static void sleep(long millis) throws InterruptedException

e) Give a syntax of 〈param〉 tag to pass parameters to an applet.


Ans.<applet code="YourAppletClassName.class" width="300" height="300">
<param name="parameterName1" value="parameterValue1">
<param name="parameterName2" value="parameterValue2">
<!-- Add more <param> tags as needed -->
</applet>

f) Define stream class and list types of stream class.


Ans.Definition of stream class:
An I/O Stream represents an input source or an output destination. A stream can represent many
different kinds of sources and destinations, including disk files, devices, other programs, and
memory arrays. Streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects. Java’s stream based I/O is built upon four abstract
classes:
InputStream, OutputStream, Reader, Writer.
Types of stream classes:
i. Byte stream classes
ii. Character stream classes

g) Give use of garbage collection in java.


Ans.Garbage collection in Java is an automatic memory management process that helps in
reclaiming memory by removing objects that are no longer in use. It plays a crucial role in
ensuring efficient memory management, preventing memory leaks, and enhancing the overall
performance of Java applications. Below are the key uses and benefits of garbage collection in
Java:
Uses of Garbage Collection in Java
1. Automatic Memory Management:
a. Java provides automatic garbage collection, which relieves developers from the
burden of manually managing memory allocation and deallocation. This helps to
simplify code and reduce the risk of memory-related errors.
2. Memory Leak Prevention:
a. By automatically reclaiming memory occupied by objects that are no longer
referenced, garbage collection helps prevent memory leaks, which can lead to
decreased performance and application crashes.
3. Efficient Resource Utilization:
a. Garbage collection optimizes memory usage by ensuring that memory is available
for new objects, allowing applications to utilize system resources more efficiently.
4. Object Lifetime Management:
a. The garbage collector tracks the lifecycle of objects in memory and identifies
when objects are no longer needed. This is particularly useful in long-running
applications where objects may be created and discarded frequently.
5. Performance Improvement:
a. While garbage collection has overhead, it can improve overall performance by
consolidating memory and reducing fragmentation. A well-implemented garbage
collector can help maintain application responsiveness.
6. Simplified Code:
a. With garbage collection, developers do not need to write complex memory
management code, making the application easier to develop, read, and maintain.
7. Handling Large Data Sets:
a. In applications that handle large amounts of data or numerous objects, garbage
collection helps manage memory effectively by cleaning up unused objects, which
is crucial for performance.

2. Attempt any THREE of the following: 12

a) Describe type casting in java with example.


Ans.The process of converting one data type to another is called
casting or type casting.
2. If the two types are compatible, then java will perform the
conversion automatically.
3. It is possible to assign an int value to long variable.
4. However, if the two types of variables are not compatible, the
type conversions are not implicitly allowed, hence the need for
type casting
There are two types of conversion:
1.Implicit type-casting:
2.Explicit type-casting:
1. Implicit type-casting:
Implicit type-casting performed by the compiler automatically; if
there will be no loss of precision.
Example:
int i = 3;
double f;
f = i;
output:
f = 3.0
Widening Conversion:
The rule is to promote the smaller type to bigger type to prevent
loss of precision, known as Widening Conversion.
2. Explicit type-casting:
• Explicit type-casting performed via a type-casting
operator in the prefix form of (new-type) operand.
• Type-casting forces an explicit conversion of type of a
value. Type casting is an operation which takes one
operand, operates on it and returns an equivalent value in
the specified type.
Syntax:
newValue = (typecast)value;
Example:
double f = 3.5;
int i;
i = (int)f; // it cast double value 3.5 to int 3.
Narrowing Casting: Explicit type cast is requires to Narrowing
conversion to inform the compiler that you are aware of the
possible loss of p

b) Differentiate between string and string buffer class(any four points)


Ans.
S. String StringBuffer
N
o.
1 String is immutable. It is mutable.
2 It is slow in terms of executing the It is fast in terms of executing the concatenation
concatenation task. task.
3 Here the length of the string class is Here the length can be modified whenever
static. required, as it is dynamic in behaviour.
4 It is less efficient. It is more efficient in nature as compared to the
string class.
5 String consumes more as compared to StringBuffer uses less memory as compared to
the stringbuffer. the string.
5 It utilises a string constant pool to store It prefers heap memory to store the objects.
the values.
6 It overrides both equal() and hashcode() It cannot override equal() and hashcode()
techniques of object class. methods.
c) Write a program to create a user defined exception in java.
Ans.
// Custom Exception Class
class InvalidAgeException extends Exception {
// Constructor that accepts a message
public InvalidAgeException(String message) {
super(message);
}
}

// Class to demonstrate the custom exception


public class UserDefinedExceptionExample {

// Method to set age


public static void setAge(int age) throws InvalidAgeException {
// Check if the age is invalid
if (age < 0) {
// Throw the custom exception with a message
throw new InvalidAgeException("Age cannot be negative: " + age);
} else {
System.out.println("Age set to: " + age);
}
}

public static void main(String[] args) {


try {
setAge(25); // Valid age
setAge(-5); // Invalid age, this will trigger the exception
} catch (InvalidAgeException e) {
// Catch the custom exception and print the error message
System.err.println("Caught Exception: " + e.getMessage());
}
}
}
Output:
Age set to: 25
Caught Exception: Age cannot be negative: -5

d) Write a program for reading and writing character to and from the given files using
character stream classes.
Ans.
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;

public class CharacterStreamExample {


public static void main(String[] args) {
String filePath = "example.txt"; // File to write and read characters

// Writing characters to the file


try (FileWriter writer = new FileWriter(filePath)) {
writer.write("Hello, this is a sample text.\n");
writer.write("This text is written using FileWriter.");
System.out.println("Characters written to the file successfully.");
} catch (IOException e) {
System.err.println("An error occurred while writing to the file: " + e.getMessage());
}

// Reading characters from the file


try (FileReader reader = new FileReader(filePath)) {
int character;
System.out.println("\nReading characters from the file:");
while ((character = reader.read()) != -1) {
System.out.print((char) character); // Print the character read from the file
}
} catch (IOException e) {
System.err.println("An error occurred while reading from the file: " + e.getMessage());
}
}
}

3. Attempt any THREE of the following: 12

a) Write a program to print all the Armstrong numbers from 0 to 999.


Ans.
public class ArmstrongNumbers {
public static void main(String[] args) {
System.out.println("Armstrong numbers from 0 to 999:");

for (int number = 0; number <= 999; number++) {


int originalNumber = number; // Store the original number
int sum = 0; // Initialize sum to 0

// Calculate the sum of cubes of the digits


while (originalNumber > 0) {
int digit = originalNumber % 10; // Get the last digit
sum += digit * digit * digit; // Add the cube of the digit to sum
originalNumber /= 10; // Remove the last digit
}

// Check if the sum is equal to the original number


if (sum == number) {
System.out.println(number); // Print the Armstrong number
}
}
}
}

b) Explain the applet life cycle with neat diagram.


Ans.

Below is the description of each applet life cycle method:


init(): The init() method is the first method to execute when the applet is executed. Variable
declaration and initialization operations are performed in this method.
start(): The start() method contains the actual code of the applet that should run. The start()
method executes immediately after the init() method. It also executes whenever the applet is
restored, maximized or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The stop() method executes when
the applet is minimized or when moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is closed or when the tab
containing the webpage is closed. stop() method executes just before when destroy() method is
invoked. The destroy() method removes the applet object from memory.
paint(): The paint() method is used to redraw the output on the applet display area. The paint()
method executes after the execution of start() method and whenever the applet or browser is
resized.
The method execution sequence when an applet is executed is:
ï‚· init()
ï‚· start()
ï‚· paint()
The method execution sequence when an applet is closed is:
ï‚· stop()
ï‚· destroy()

c) Describe the package in java with suitable example.


Ans.Java provides a mechanism for partitioning the class namespace into more manageable
parts. This mechanism is the package. The package is both naming and visibility controlled
mechanism. Package can be created by including package as the first statement in java source
code. Any classes declared within that file will belong to the specified package. Package defines a
namespace in which classes are stored.
The syntax for defining a package is:
package pkg;
Here, pkg is the name of the package
eg : package
mypack;
Packages are mirrored by directories. Java uses file system directories to store packages. The
class files of any classes which are declared in a package must be stored in a directory which has
same name as package name. The directory must match with the package name exactly. A
hierarchy can be created by separating package name and sub package name by a period(.) as
pkg1.pkg2.pkg3; which requires a directory structure as pkg1\pkg2\pkg3.
Syntax:
To access package In a Java source file, import statements
occur immediately following the package statement (if
it exists) and before any class definitions.
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class volume
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}

d) Enlist types of Byte stream class and describe input stream class and output stream
class.
Ans.byte streams are used to perform input and output operations on binary data (i.e., data in
raw byte form). Byte streams are part of the java.io package and are primarily used for handling
binary data such as images, audio files, or any other data that isn't text.
Types of Byte Stream Classes
Byte stream classes can be categorized into two main types:
1. Input Stream Classes: These classes are used to read data from a source (like a file or
network).
2. Output Stream Classes: These classes are used to write data to a destination (like a file
or network).
Input Stream Classes
1. FileInputStream: Reads bytes from a file.
2. ByteArrayInputStream: Reads bytes from a byte array.
3. BufferedInputStream: Provides buffering for another input stream to improve
performance.
4. DataInputStream: Allows reading Java primitive data types from an underlying input
stream.
Output Stream Classes
1. FileOutputStream: Writes bytes to a file.
2. ByteArrayOutputStream: Writes bytes to a byte array, which can grow dynamically.
3. BufferedOutputStream: Provides buffering for another output stream to improve
performance.
4. DataOutputStream: Allows writing Java primitive data types to an underlying output
stream.

InputStream Class
The InputStream class is an abstract class that serves as the superclass for all classes
representing an input stream of bytes. It provides methods to read bytes, arrays of bytes, and to
skip bytes.
Methods of InputStream
read(): Reads the next byte of data from the input stream. It returns an integer value
representing the byte read (0 to 255) or -1 if the end of the stream has been reached.
int byteData = inputStream.read();

read(byte[] b): Reads a certain number of bytes from the input stream into the byte array b. It
returns the number of bytes read or -1 if the end of the stream has been reached
int bytesRead = inputStream.read(byteArray);

skip(long n): Skips over and discards n bytes of data from the input stream.
long bytesSkipped = inputStream.skip(n);

close(): Closes the input stream and releases any system resources associated with it.
inputStream.close();

OutputStream Class:The OutputStream class is an abstract class that


serves as the superclass for all classes representing an output stream of
bytes. It provides methods to write bytes, arrays of bytes, and to flush the
stream.

Methods of OutputStream

write(int b): Writes the specified byte to the output stream. The byte is given as an integer
value, where the higher-order byte is ignored.
outputStream.write(byteData);

write(byte[] b): Writes b.length bytes from the byte array b to the output stream.
outputStream.write(byteArray);

write(byte[] b, int off, int len): Writes len bytes from the specified byte array starting at offset
off to the output stream.
outputStream.write(byteArray, off, len);

flush(): Flushes the output stream and forces any buffered output bytes to be written out.
outputStream.flush();

close(): Closes the output stream and releases any system resources associated with it.
outputStream.close();

4. Attempt any THREE of the following: 12

a) Describe any four features of java.


Ans.
1.Object Oriented:In Java, everything is an Object. Java can be easily extended since it is based
on the Object model.
2.Platform Independent: Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
3.Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java,
it would be easy to master.
4.Secure: With Java's secure feature it enables to develop virus-free, tamper free systems.
Authentication techniques are based on public-key encryption.
5.Architecture-neutral: Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of Java
runtime system.
6.Multithreaded: With Java's multithreaded feature it is possible to write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
7.Interpreted: Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.

b) Explain any four methods of vector class with example.


Ans.The Vector class in Java is part of the java.util package and implements a dynamic array that
can grow as needed. It allows for the storage of objects and provides various methods to
manipulate the stored elements. Here are four key methods of the Vector class explained in
detail, along with a code example demonstrating their usage:
Key Methods of the Vector Class
1.add(E e):
Description: Appends the specified element to the end of the vector.
Syntax:
vector.add(element);
get(int index):
Description: Returns the element at the specified position in the vector.
Syntax:
E element = vector.get(index);
remove(int index):
 Description: Removes the element at the specified position in the vector. Shifts any
subsequent elements to the left (subtracts one from their indices).
 Syntax:
E removedElement = vector.remove(index);
size():
 Description: Returns the number of elements in the vector.
 Syntax:
int size = vector.size();
Example:
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Create a Vector to store Integer elements
Vector<Integer> vector = new Vector<>();

// 1. Adding elements to the Vector


vector.add(10);
vector.add(20);
vector.add(30);
vector.add(40);
System.out.println("Vector after adding elements: " + vector);

// 2. Getting an element at a specific index


int elementAtIndex1 = vector.get(1); // Getting the element at index 1
System.out.println("Element at index 1: " + elementAtIndex1);

// 3. Removing an element from the Vector


int removedElement = vector.remove(2); // Removing the element at index 2
System.out.println("Removed element: " + removedElement);
System.out.println("Vector after removing an element: " + vector);

// 4. Getting the size of the Vector


int size = vector.size(); // Getting the size of the Vector
System.out.println("Size of the Vector: " + size);
}
}

c) Describe interface in java with suitable example.


Ans.Interface is similar to a class.It consist of only abstract methods and final variables. To
implement an interface a class must define each of the method declared in the interface.It is
used to achieve fully abstraction and multiple inheritance in
interface Salary
{
double Basic Salary=10000.0;
void Basic Sal();
}
class Employee
{
String Name;
int age;
Employee(String n, int b)
{
Name=n;
age=b;
}
void Display()
{
System.out.println("Name of Employee
:"+Name);
System.out.println("Age of Employee :"+age);
}
}
class Gross_Salary extends Employee implements Salary
{
double HRA,TA,DA;
Gross_Salary(String n, int b, double h,double t,double d)
{
super(n,b);
HRA=h;
TA=t;
DA=d;
}
public void Basic_Sal()
{
System.out.println("Basic Salary
:"+Basic_Salary);
}
void Total_Sal()
{
Display();
Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA +
HRA;
System.out.println("Total Salary :"+Total_Sal);
}
}
class EmpDetails
{
public static void main(String args[])
{
Gross_Salary s=new
Gross_Salary("Sachin",20,1000,2000,7000);
s.Total_Sal();
}
}

d) Write an applet program for following graphics method.


i) Drawoval ( )
ii) Drawline ( )
Ans.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*
<applet code="GraphicsExample" width=400 height=400>
</applet>
*/
public class GraphicsExample extends Applet {
@Override
public void paint(Graphics g) {
// Set color for the oval
g.setColor(Color.BLUE);
// Draw an oval (ellipse)
g.drawOval(50, 50, 200, 100); // x, y, width, height
// Set color for the line
g.setColor(Color.RED);
// Draw a line
g.drawLine(50, 50, 250, 150); // x1, y1, x2, y2
}
}

e) Enlist any four methods of file input stream class and give syntax of any two methods.
Ans.
Methods of FileInputStream
1. read():
Reads the next byte of data from the input stream. The byte is returned as an integer in the
range 0 to 255 or -1 if the end of the stream has been reached.
Syntax:
int byteData = fileInputStream.read();
read(byte[] b):
 Reads up to b.length bytes of data from the input stream into an array of bytes.
Syntax:
int bytesRead = fileInputStream.read(b);
skip(long n):
 Skips over and discards n bytes of data from the input stream.
Syntax:
long bytesSkipped = fileInputStream.skip(n);
close():
 Closes the input stream and releases any system resources associated with it.
Syntax:
fileInputStream.close();

Example:
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Specify the path to your file
// Using FileInputStream to read data from a file
try (FileInputStream fileInputStream = new FileInputStream(filePath)) {
// Using read() method to read a single byte
int byteData;
while ((byteData = fileInputStream.read()) != -1) {
// Print the byte read as a character
System.out.print((char) byteData);
}
System.out.println("\n-----");
// Reset the stream to read again (not possible in a real stream, for illustration)
// You would generally need to create a new FileInputStream instance.
// Using read(byte[] b) method to read bytes into a buffer
byte[] buffer = new byte[10]; // Buffer to hold bytes
int bytesRead;
FileInputStream fileInputStream2 = new FileInputStream(filePath);
while ((bytesRead = fileInputStream2.read(buffer)) != -1) {
// Print the bytes read
System.out.print(new String(buffer, 0, bytesRead));
}

} catch (IOException e) {
e.printStackTrace();
}
}
}

5. Attempt any TWO of the following: 12

a) Write a program to copy all elements of one array into another array.
Ans.
public class ArrayCopyExample {
public static void main(String[] args) {
// Define the source array
int[] sourceArray = {1, 2, 3, 4, 5};

// Create a destination array of the same size as the source array


int[] destinationArray = new int[sourceArray.length];

// Copy elements from source array to destination array


for (int i = 0; i < sourceArray.length; i++) {
destinationArray[i] = sourceArray[i];
}

// Display the elements of the destination array


System.out.println("Elements of the destination array:");
for (int value : destinationArray) {
System.out.print(value + " ");
}
}
}
b) Write a program to implement the following inheritance.
Refer Fig. No. 1.

Fig. No. 1
Ans.
// Define the Exam interface
interface Exam {
// Sports marks are fixed as 20
int sportsMark = 20;

// Method to calculate total marks including sports


int calculateTotalMarks();
}

// Student class implementing the Exam interface


class Student implements Exam {
// Data members of the student
int rollNo;
String studentName;
int m1, m2, m3; // Marks for three subjects

// Constructor to initialize student details


public Student(int rollNo, String studentName, int m1, int m2, int m3) {
this.rollNo = rollNo;
this.studentName = studentName;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}

// Implement the calculateTotalMarks method from Exam interface


@Override
public int calculateTotalMarks() {
// Total marks = sum of subject marks + sports marks
return m1 + m2 + m3 + sportsMark;
}
}

// Result class that inherits from Student and displays the result
class Result extends Student {
// Constructor to initialize student details and pass to parent constructor
public Result(int rollNo, String studentName, int m1, int m2, int m3) {
super(rollNo, studentName, m1, m2, m3);
}

// Method to display the student's result


public void display() {
System.out.println("Student Roll No: " + rollNo);
System.out.println("Student Name: " + studentName);
System.out.println("Marks in Subject 1: " + m1);
System.out.println("Marks in Subject 2: " + m2);
System.out.println("Marks in Subject 3: " + m3);
System.out.println("Sports Marks: " + sportsMark);
System.out.println("Total Marks (including sports): " + calculateTotalMarks());
}
}

// Main class to test the implementation


public class Main {
public static void main(String[] args) {
// Creating an object of Result class and initializing student details
Result student1 = new Result(101, "John Doe", 85, 90, 88);

// Displaying the result of the student


student1.display();
}
}

c) Write a program to print even and odd number using two threads with delay of 1000ms
after each number.
Ans.
class EvenThread extends Thread {
public void run() {
for (int i = 0; i <= 10; i += 2) { // Print even numbers from 0 to 10
System.out.println("Even: " + i);
try {
Thread.sleep(1000); // Delay of 1000 ms
} catch (InterruptedException e) {
System.out.println("EvenThread interrupted");
}
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) { // Print odd numbers from 1 to 10
System.out.println("Odd: " + i);
try {
Thread.sleep(1000); // Delay of 1000 ms
} catch (InterruptedException e) {
System.out.println("OddThread interrupted");
}
}
}
}
public class EvenOddThreads {
public static void main(String[] args) {
EvenThread evenThread = new EvenThread(); // Create even thread
OddThread oddThread = new OddThread(); // Create odd thread

evenThread.start(); // Start the even thread


oddThread.start(); // Start the odd thread
}
}

6. Attempt any TWO of the following: 12


a) Explain thread life cycle with neat diagram.
Ans.Life cycle of thread includes following states :
1.Newborn
2. Runnable
3. Running
4. Blocked
5. Dead

Thread should be in any one state of above and it can be move


from one state to another by different methods and ways.
Newborn state: When a thread object is created it is said to be in a new born state. When the
thread is in a new born state it is not scheduled running from this state it can be scheduled for
running by start() or killed by stop(). If put in a queue it moves to runnable state.
Runnable State: It means that thread is ready for execution and is waiting for the availability of
the processor i.e. the thread has joined the queue and is waiting for execution. If all threads have
equal priority, then they are given time slots for execution in round robin fashion. The thread that
relinquishes control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
Running State: It means that the processor has given its time to the thread for execution. The
thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.
Blocked state: A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
1) suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
2) wait(): If a thread requires to wait until some event occurs, it can be done using wait method
and can be scheduled to run again by notify().
3) sleep(): We can put a thread to sleep for a specified time period using sleep(time) where time
is in ms. It re-enters the runnable state as soon as period has elapsed /over
Dead State: Whenever we want to stop a thread form running further we can call its stop().The
statement causes the thread to move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop method may be used when the
premature death is required.

b) Write a program to generate following output using


drawline ( ) method. Refer Fig. No. 2.

Fig. No. 2
Ans.
import java.awt.*;
import javax.swing.*;
public class TriangleDrawing extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Set color for drawing
g.setColor(Color.BLACK);
// Coordinates of the three points of the triangle
int x1 = 150, y1 = 50; // Top vertex
int x2 = 100, y2 = 150; // Bottom-left vertex
int x3 = 200, y3 = 150; // Bottom-right vertex
// Draw lines to form a triangle
g.drawLine(x1, y1, x2, y2); // Line from top to bottom-left
g.drawLine(x2, y2, x3, y3); // Line from bottom-left to bottom-right
g.drawLine(x3, y3, x1, y1); // Line from bottom-right to top
}
// Main method to set up the JFrame and panel
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Triangle using drawLine()");
TriangleDrawing panel = new TriangleDrawing();
// Set size, default close operation and add the panel
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
// Make the frame visible
frame.setVisible(true);
}
}

c) Explain constructor with its type. Give an example of parameterized constructor.


Ans.Constructor:A constructor is a special member which initializes an object immediately upon
creation.It has the same name as class name in which it resides and it is
syntactically similar to any method. When a constructor is not defined, java executes a default
constructor which initializes all numeric members to zero and other types to null or spaces.
Once defined, constructor is automatically called immediately after the object is created before
new operator completes.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
4. Constructor with no arguments or No-Arg Constructor or Non-Parameterized constructor.

Parameterized constructor: When constructor method is defined with parameters inside it,
different value sets can be provided to different constructor with the same name.
Example
class Student {
int roll_no;
String name;
Student(int r, String n) // parameterized constructor
{
roll_no = r;
name=n;
}
void display()
{
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[])
{
Student s = new Student(20,"ABC"); // constructor
with parameters
s.display();
}
}

You might also like