Java Summer 23
Java Summer 23
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
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;
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();
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();
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();
}
}
}
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};
Fig. No. 1
Ans.
// Define the Exam interface
interface Exam {
// Sports marks are fixed as 20
int sportsMark = 20;
// 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);
}
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");
}
}
}
}
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);
}
}
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();
}
}