0% found this document useful (0 votes)
15 views21 pages

Display Even Numbers in Java

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

Display Even Numbers in Java

Model Ans Paper
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Summer 23

1. Attempt any FIVE of the following: 10


a) Define the terms with example
i) Class
ii) Object
[Link]: 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.


[Link] 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 [Link]; // 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();
[Link](); // 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="[Link]" 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.


[Link] 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.


[Link] 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.


[Link] 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:
[Link] type-casting:
[Link] 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 {
[Link]("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
[Link]("Caught Exception: " + [Link]());
}
}
}
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 [Link];
import [Link];
import [Link];

public class CharacterStreamExample {


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

// Writing characters to the file


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

// Reading characters from the file


try (FileReader reader = new FileReader(filePath)) {
int character;
[Link]("\nReading characters from the file:");
while ((character = [Link]()) != -1) {
[Link]((char) character); // Print the character read from the file
}
} catch (IOException e) {
[Link]("An error occurred while reading from the file: " + [Link]());
}
}
}

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) {
[Link]("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) {
[Link](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.


[Link] 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()
{
[Link]("Volume is:"+(l*b*h));
}
}
Source file:
import [Link];
class volume
{
public static void main(String args[])
{
Box b=new Box();
[Link]();
}
}

d) Enlist types of Byte stream class and describe input stream class and output stream
class.
[Link] 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 [Link] 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 = [Link]();

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 = [Link](byteArray);

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

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

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.
[Link](byteData);

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

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

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

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

4. Attempt any THREE of the following: 12

a) Describe any four features of java.


Ans.
[Link] Oriented:In Java, everything is an Object. Java can be easily extended since it is based
on the Object model.
[Link] 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.
[Link]: Java is designed to be easy to learn. If you understand the basic concept of OOP Java,
it would be easy to master.
[Link]: With Java's secure feature it enables to develop virus-free, tamper free systems.
Authentication techniques are based on public-key encryption.
[Link]-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.
[Link]: 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.
[Link]: 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.


[Link] Vector class in Java is part of the [Link] 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
[Link](E e):
Description: Appends the specified element to the end of the vector.
Syntax:
[Link](element);
get(int index):
Description: Returns the element at the specified position in the vector.
Syntax:
E element = [Link](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 = [Link](index);
size():
 Description: Returns the number of elements in the vector.
 Syntax:
int size = [Link]();
Example:
import [Link];
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


[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]("Vector after adding elements: " + vector);

// 2. Getting an element at a specific index


int elementAtIndex1 = [Link](1); // Getting the element at index 1
[Link]("Element at index 1: " + elementAtIndex1);

// 3. Removing an element from the Vector


int removedElement = [Link](2); // Removing the element at index 2
[Link]("Removed element: " + removedElement);
[Link]("Vector after removing an element: " + vector);

// 4. Getting the size of the Vector


int size = [Link](); // Getting the size of the Vector
[Link]("Size of the Vector: " + size);
}
}

c) Describe interface in java with suitable example.


[Link] is similar to a [Link] consist of only abstract methods and final variables. To
implement an interface a class must define each of the method declared in the [Link] 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()
{
[Link]("Name of Employee
:"+Name);
[Link]("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()
{
[Link]("Basic Salary
:"+Basic_Salary);
}
void Total_Sal()
{
Display();
Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA +
HRA;
[Link]("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 [Link];
import [Link];
import [Link];
/*
<applet code="GraphicsExample" width=400 height=400>
</applet>
*/
public class GraphicsExample extends Applet {
@Override
public void paint(Graphics g) {
// Set color for the oval
[Link]([Link]);
// Draw an oval (ellipse)
[Link](50, 50, 200, 100); // x, y, width, height
// Set color for the line
[Link]([Link]);
// Draw a line
[Link](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 = [Link]();
read(byte[] b):
 Reads up to [Link] bytes of data from the input stream into an array of bytes.
Syntax:
int bytesRead = [Link](b);
skip(long n):
 Skips over and discards n bytes of data from the input stream.
Syntax:
long bytesSkipped = [Link](n);
close():
 Closes the input stream and releases any system resources associated with it.
Syntax:
[Link]();

Example:
import [Link];
import [Link];
public class FileInputStreamExample {
public static void main(String[] args) {
String filePath = "[Link]"; // 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 = [Link]()) != -1) {
// Print the byte read as a character
[Link]((char) byteData);
}
[Link]("\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 = [Link](buffer)) != -1) {
// Print the bytes read
[Link](new String(buffer, 0, bytesRead));
}

} catch (IOException e) {
[Link]();
}
}
}

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[[Link]];

// Copy elements from source array to destination array


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

// Display the elements of the destination array


[Link]("Elements of the destination array:");
for (int value : destinationArray) {
[Link](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) {
[Link] = rollNo;
[Link] = 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() {
[Link]("Student Roll No: " + rollNo);
[Link]("Student Name: " + studentName);
[Link]("Marks in Subject 1: " + m1);
[Link]("Marks in Subject 2: " + m2);
[Link]("Marks in Subject 3: " + m3);
[Link]("Sports Marks: " + sportsMark);
[Link]("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


[Link]();
}
}

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
[Link]("Even: " + i);
try {
[Link](1000); // Delay of 1000 ms
} catch (InterruptedException e) {
[Link]("EvenThread interrupted");
}
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) { // Print odd numbers from 1 to 10
[Link]("Odd: " + i);
try {
[Link](1000); // Delay of 1000 ms
} catch (InterruptedException e) {
[Link]("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

[Link](); // Start the even thread


[Link](); // Start the odd thread
}
}

6. Attempt any TWO of the following: 12


a) Explain thread life cycle with neat diagram.
[Link] cycle of thread includes following states :
[Link]
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 [Link].*;
import [Link].*;
public class TriangleDrawing extends JPanel {
@Override
public void paintComponent(Graphics g) {
[Link](g);
// Set color for drawing
[Link]([Link]);
// 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
[Link](x1, y1, x2, y2); // Line from top to bottom-left
[Link](x2, y2, x3, y3); // Line from bottom-left to bottom-right
[Link](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
[Link](400, 400);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](panel);
// Make the frame visible
[Link](true);
}
}

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


[Link]:A constructor is a special member which initializes an object immediately upon
[Link] 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()
{
[Link]("Roll no is: "+roll_no);
[Link]("Name is : "+name);
}
public static void main(String a[])
{
Student s = new Student(20,"ABC"); // constructor
with parameters
[Link]();
}
}

Common questions

Powered by AI

Byte streams handle input and output operations on binary data in Java, crucial for data such as images or audio files. They are classified into Input Stream Classes (e.g., FileInputStream, ByteArrayInputStream) and Output Stream Classes (e.g., FileOutputStream, ByteArrayOutputStream) based on their operation of reading or writing binary data .

The package system in Java allows partitioning the class namespace into more manageable parts, acting as both a naming and visibility control mechanism. A package is created by including a package statement as the first line in the Java source file, with classes in that file belonging to the specified package name. These classes need to be stored in a directory matching the package name exactly. To access classes in a package, they must be imported using import statements .

Java ensures program security through multiple layers, including language-level type safety, runtime security checks, and security policies configurable by administrators. Java's secure class loading and its restriction on pointer arithmetic help prevent unauthorized access and modifications to data, making Java applications less susceptible to buffer overflows and memory corruption .

InputStream and OutputStream classes are part of the Java IO package, used for handling binary data. InputStream classes read data from a source, with methods like read(), read(byte[] b), skip(long n), and close(). OutputStream classes write data to a destination, with methods like write(int b), write(byte[] b, int off, int len), flush(), and close().

A parameterized constructor in Java allows initialization of an object with specific values. For instance, in class Student, the constructor Student(int r, String n) initializes the student’s roll number and name. When a Student object is created with values (20, "ABC"), these parameters are passed to the constructor, setting the initial state of the object .

The Java thread lifecycle includes states like Newborn, Runnable, Running, Blocked, and Dead. Thread manipulation occurs through methods like start() to move a thread from Newborn to Runnable, yield() to voluntarily relinquish control, suspend() and resume() to pause and continue execution, wait() and notify() for inter-thread communication, and stop() to terminate a thread .

An applet's lifecycle in Java includes the methods init(), start(), paint(), stop(), and destroy(). The execution sequence when an applet is executed is init(), start(), and paint(). When an applet is closed, the sequence is stop() and destroy().

Interface implementation in Java affects class design by requiring a class to implement all methods declared in the interface, promoting abstraction and enabling multiple inheritance. For example, the Gross_Salary class implements the Salary interface, mandating it to define the Basic_Sal() method, thus keeping the class design consistent and abstract .

Java's object-oriented nature allows it to create programs that are structured and can be easily extended. This facilitates code reuse and easier maintenance. Java being platform-independent means its bytecode can be executed on any machine with a Java Virtual Machine (JVM), making Java applications highly portable .

FileInputStream methods enhance file handling by allowing the reading of bytes from a file. Key methods include read(), which reads a single byte or an array of bytes, skip(long n), which skips over n bytes, and close(), which closes the input stream, releasing any system resources .

You might also like