[go: up one dir, main page]

0% found this document useful (0 votes)
6 views24 pages

adavajava2

The document outlines a series of Java programming exercises focused on concepts such as generics, threading, synchronization, and file I/O. Each exercise includes coding phases, testing phases, and implementation phases, with specific examples of code and expected outputs. Additionally, it includes rubrics for evaluation and sections for student and faculty signatures.

Uploaded by

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

adavajava2

The document outlines a series of Java programming exercises focused on concepts such as generics, threading, synchronization, and file I/O. Each exercise includes coding phases, testing phases, and implementation phases, with specific examples of code and expected outputs. Additionally, it includes rubrics for evaluation and sections for student and faculty signatures.

Uploaded by

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

School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


write a program in java to demonstrate the use of generics by
defining a generic class that can handle different types of dataCoding Phase: Pseudo Code /
Flow Chart / Algorithm
// Define a generic class Box
public class Box<T> {
// T stands for "Type"
private T value;

// Constructor to initialize the value


public Box(T value) {
this.value = value;
}

// Getter method to retrieve the value


public T getValue() {
return value;
}

// Setter method to set the value


public void setValue(T value) {
this.value = value;
}

// Method to display the value type


public void displayType() {
System.out.println("The type of value is: " + value.getClass().getName());
}
}

public class Main {


public static void main(String[] args) {
// Creating a Box for Integer type
Box<Integer> integerBox = new Box<>(123);
System.out.println("Integer value: " + integerBox.getValue
integerBox.displayType(); // Output the type of data inside the box

// Creating a Box for String type


Box<String> stringBox = new Box<>("Hello, Generics!");
System.out.println("String value: " + stringBox.getValue
stringBox.displayType(); // Output the type of data inside the box

// Creating a Box for Double type


Box<Double> doubleBox = new Box<>(45.67);
System.out.println("Double value: " + doubleBox.getValue

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
Main.java:31: error: ')' or ',' expected
System.out.println("Integer value: " + integerBox.getValue
^
Main.java:36: error: ')' or ',' expected
System.out.println("String value: " + stringBox.getValue
^
Main.java:41: error: ')' or ',' expected
System.out.println("Double value: " + doubleBox.getValue
^
3 errors

[Done] exited with code=1 in 0.568 seconds

* Implementation Phase: Final Output (no error)


public class Main {
public static void main(String[] args) {
// Creating a Box for Integer type
Box<Integer> integerBox = new Box<>(123);
System.out.println("Integer value: " + integerBox.getValue());
integerBox.displayType(); // Output the type of data inside the box

// Creating a Box for String type


Box<String> stringBox = new Box<>("Hello, Generics!");
System.out.println("String value: " + stringBox.getValue());
stringBox.displayType(); // Output the type of data inside the box

// Creating a Box for Double type


Box<Double> doubleBox = new Box<>(45.67);
System.out.println("Double value: " + doubleBox.getValue());
doubleBox.displayType(); // Output the type of data inside the box
}}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* OUTPUT:
Integer value: 123
The type of value is: java.lang.Integer
String value: Hello, Generics!
The type of value is: java.lang.String
Double value: 45.67
The type of value is: java.lang.Double

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


create a program in java create a method using generics
printArray method which provides a generic way to print the elements of the array..
* Coding Phase: Pseudo Code / Flow Chart / Algorithm
public class GenericPrintArray {

// Generic method to print elements of an array


public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}

public static void main(String[] args) {


// Integer array
Integer[] intArray = {1, 2, 3, 4, 5};
System.out.println("Integer Array:");
printArray(intArray); // Calling generic method with Integer array

// String array
String[] strArray = {"Hello", "World", "Generics"};
System.out.println("\nString Array:");
printArray(strArray); // Calling generic method with String array

// Double array
Double[] doubleArray = {1.1, 2.2, 3.3, 4.4};
System.out.println("\nDouble Array:");
printArray(doubleArray); // Calling generic method with Double array
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
NO ERROR

* Implementation Phase: Final Output (no error)


Integer Array:
1
2
3
4
5

String Array:
Hello
World
Generics

Double Array:
1.1
2.2
3.3
4.4

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


Implement a thread by creating a class that implements the
Runnable interface. The thread should print "Hello, World!" 5 times..
* Coding Phase: Pseudo Code / Flow Chart / Algorithm
class HelloWorldRunnable implements Runnable {

@Override
public void run() {
// Print "Hello, World!" 5 times
for (int i = 0; i < 5; i++) {
System.out.println("Hello, World!");
try {
Thread.sleep(500); // Sleep for 500 milliseconds to slow down the output
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
// Create an instance of the Runnable class
Runnable helloRunnable = new HelloWorldRunnable

// Create a thread and pass the Runnable to the constructor


Thread = new Thread(helloRunnable);

// Start the thread


thread.start();
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
[Running] cd "c:\Users\sahu0\OneDrive\Desktop\JAVA\Genericjava\" && javac
ThreadDemo.java && java ThreadDemo
ThreadDemo.java:23: error: '(' or '[' expected
Thread = new Thread(helloRunnable);
^
1 error

[Done] exited with code=1 in 0.49 seconds

* Implementation Phase: Final Output (no error)


public class ThreadDemo {
public static void main(String[] args) {
// Create an instance of the Runnable class
Runnable helloRunnable = new HelloWorldRunnable();

// Create a thread and pass the Runnable to the constructor


Thread thread = new Thread(helloRunnable);

// Start the thread


thread.start();
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* OUTPUT:
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


Write a Java program using the Thread class to demonstrate
thread synchronization. Create two threads that attempt to update the same shared resource,
and use synchronization to prevent data inconsistency.
* Coding Phase: Pseudo Code / Flow Chart / Algorithm
class SharedResource {
// Shared resource variable
private int counter = 0;

// Synchronized method to update the shared resource


public synchronized void increment() {
// Adding a small delay to simulate some processing time
try {
Thread.sleep(50); // Simulate some work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

// Increment the counter


counter++;
System.out.println(Thread.currentThread().getName() + " incremented counter to: " +
counter);
}

// Method to get the current value of the counter


public int getCounter() {
return counter;
}
}

class IncrementThread extends Thread {


private SharedResource sharedResource;

// Constructor to pass the shared resource


public IncrementThread(SharedResource sharedResource) {
this.sharedResource = sharedResource;
}

@Override
public void run() {
// Thread tries to increment the shared resource counter
for (int i = 0; i < 5; i++) {
sharedResource.increment();
}
}
}

public class ThreadSynchronizationDemo {


public static void main(String[] args) {
*As applicable according to the experiment.
Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
NO ERROR

* Implementation Phase: Final Output (no error)


Thread-0 incremented counter to: 1
Thread-1 incremented counter to: 2
Thread-0 incremented counter to: 3
Thread-1 incremented counter to: 4
Thread-0 incremented counter to: 5
Thread-1 incremented counter to: 6
Thread-0 incremented counter to: 7
Thread-1 incremented counter to: 8
Thread-0 incremented counter to: 9
Thread-1 incremented counter to: 10
Final counter value: 10

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


Write a program using java to Write Data to a File Using
BufferedOutputStream in Java?"
* Coding Phase: Pseudo Code / Flow Chart / Algorithm
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToFileWithBufferedOutputStream {


public static void main(String[] args) {
// Define the file path to which we want to write the data
String filePath = "output.txt";

// The data to be written to the file (as a byte array)


String data = "Hello, this is a test message written using
BufferedOutputStream.";

// Convert the string data to a byte array


byte[] dataBytes = data.getBytes();

// Create a BufferedOutputStream to write to the file


try (BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(new FileOutputStream(filePath))) {
// Write the byte array to the file
bufferedOutputStream.write(dataBytes);

// Optional: flush the stream to ensure all data is written


bufferedOutputStream.flush();

System.out.println("Data successfully written to the file: " + filePath);


} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
NO ERROR

* Implementation Phase: Final Output (no error)


Hello, this is a test message written using
BufferedOutputStream.

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


write a program in java how to read data from a file using
BufferedInputStream in java.
* Coding Phase: Pseudo Code / Flow Chart / Algorithm
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadFromFileWithBufferedInputStream {


public static void main(String[] args) {
// Define the file path from which we want to read data
String filePath = "output.txt"; // Replace with your file path

// Create a BufferedInputStream to read from the file


try (BufferedInputStream bufferedInputStream = new
BufferedInputStream(new FileInputStream(filePath))) {
int byteRead;

// Read the file byte by byte until the end of the file is reached
while ((byteRead = bufferedInputStream.read()) != -1) {
// Convert the byte to a character and print it
System.out.print((char) byteRead);
}
System.out.println(); // For a newline after printing the content

} catch (IOException e) {
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();
}
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
NO ERROR

* Implementation Phase: Final Output (no error)


Hello, this is a test message read using BufferedInputStream.

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


write a program in java How to Copy the Contents of One File to
Another Using FileInputStream and FileOutputStream
* Coding Phase: Pseudo Code / Flow Chart / Algorithm
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileExample {


public static void main(String[] args) {
// Specify the source and destination file paths
String sourceFile = "source.txt"; // Replace with the path of your source file
String destinationFile = "destination.txt"; // Replace with the path of your
destination file

// Initialize FileInputStream and FileOutputStream


try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile)) {

// Buffer to hold data temporarily


byte[] buffer = new byte[1024]; // 1 KB buffer

int bytesRead;
// Read from the source file and write to the destination file
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead); // Write the read bytes to the destination
file
}

System.out.println("File copied successfully!");

} catch (IOException e) {
System.out.println("An error occurred during file copy.");
e.printStackTrace();
}
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
[Running] cd "c:\Users\sahu0\OneDrive\Desktop\JAVA\Genericjava\" && javac
CopyFileExample.java && java CopyFileExample
An error occurred during file copy.
java.io.FileNotFoundException: source.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:152)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:106)
at CopyFileExample.main(CopyFileExample.java:12)

[Done] exited with code=0 in 0.849 seconds

* Implementation Phase: Final Output (no error)


// Initialize FileInputStream and FileOutputStream
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile)) {

// Buffer to hold data temporarily


byte[] buffer = new byte[1024]; // 1 KB buffer

int bytesRead;
// Read from the source file and write to the destination file
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead); // Write the read bytes to the destination
file
}

System.out.println("File copied successfully!");

} catch (IOException e) {
System.out.println("An error occurred during file copy.");
e.printStackTrace();
}
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* OUTPUT:
Hello, this is a test file.
This file is being copied to another file using FileInputStream and
FileOutputStream.

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Academic Year: ...................... Subject Name: ........................................................... Subject Code: ..........................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


write a program in java to Read Keyboard Input Using DataInputStream

* Coding Phase: Pseudo Code / Flow Chart / Algorithm

import java.io.*;

public class KeyboardInputUsingDataInputStream {


public static void main(String[] args) {
// Create a DataInputStream to read from the keyboard
DataInputStream inputStream = new DataInputStream(System.in);

try {
// Prompt the user for input
System.out.print("Enter a line of text: ");

// Read the input as a string from the keyboard


String userInput = inputStream.readLine();

// Print the entered input


System.out.println("You entered: " + userInput);
} catch (IOException e) {
// Handle potential IOExceptions
System.out.println("Error reading input: " + e.getMessage());
} finally {
try {
// Close the input stream
inputStream.close();
} catch (IOException e) {
System.out.println("Error closing input stream: " + e.getMessage());
}
}
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
NO ERROR

* Implementation Phase: Final Output (no error)


Enter a line of text: Hello, how are you today?
You entered: Hello, how are you today?

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


write a program in java to read data from a text file and write the
same to another text file using FileReader and FileWriter.
* Coding Phase: Pseudo Code / Flow Chart / Algorithm

import java.io.*;
public class FileCopyExample {
public static void main(String[] args) {
// Source file (input file)
String sourceFile = "source.txt";
// Destination file (output file)
String destinationFile = "destination.txt";

// Create FileReader and FileWriter objects


FileReader fileReader = null;
FileWriter fileWriter = null;

try {
// Initialize FileReader to read from the source file
fileReader = new FileReader(sourceFile);
// Initialize FileWriter to write to the destination file
fileWriter = new FileWriter(destinationFile);

// Variable to store the data read from the file


int character;

// Read and write data character by character


while ((character = fileReader.read()) != -1) {
fileWriter.write(character); }

System.out.println("File copied successfully!");

} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the resources to avoid memory leaks
try {
if (fileReader != null) {
fileReader.close(); }
if (fileWriter != null) {
fileWriter.close(); }
} catch (IOException e) {

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
[Running] cd "c:\Users\sahu0\OneDrive\Desktop\JAVA\Genericjava\" && javac
CopyFileExample.java && java CopyFileExample
An error occurred during file copy.
java.io.FileNotFoundException: source.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:152)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:106)
at CopyFileExample.main(CopyFileExample.java:12)

[Done] exited with code=0 in 0.849 seconds

* Implementation Phase: Final Output (no error)


System.out.println("File copied successfully!");

} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the resources to avoid memory leaks
try {
if (fileReader != null) {
fileReader.close();
}
if (fileWriter != null) {
fileWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* OUTPUT:
Example content for source.txt:
kotlin
Copy code
Hello, this is the content of the source file.
We will copy this content to another file.

css
Copy code
Reading from source file and writing to destination file...
Hello, this is the content of the source file.
We will copy this content to another file.
File copied successfully!

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
School: ............................................................................................................. Campus: .......................................................

Semester: ............... Program: ........................................ Branch: ......................... Specialization: ..........................

Date: .....................................

(Learning by Doing and Discovery)


Explain the stages of the servlet lifecycle. When is the
init() method called, and what is its purpose?
Coding Phase: Pseudo Code / Flow Chart / Algorithm
* import java.io.*;
* import javax.servlet.*;
* import javax.servlet.http.*;
*
* @WebServlet("/example")
* public class ExampleServlet extends HttpServlet {
*
* // The init() method is called once when the servlet is loaded into memory
* @Override
* public void init() throws ServletException {
* // Initialization logic: e.g., setting up resources or configuration
* System.out.println("Servlet is being initialized.");
* }
*
* @Override
* protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
* // Print a message for the GET request
* response.getWriter().println("Hello, Servlet World!");
* System.out.println("GET request processed.");
* }
* @Override
* public void destroy() {
* // Cleanup logic: e.g., closing resources
* System.out.println("Servlet is being destroyed.");
* }}

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.
* Testing Phase: Compilation of Code (error detection)
NO ERROR

* Implementation Phase: Final Output (no error)


rust
GET request processed.
Hello, Servlet World!

csharp
Servlet is being destroyed.

Rubrics
Concept 10
Planning and Execution/ 10
Practical Simulation/ Programming
Result and Interpretation 10
Record of Applied and Action Learning 10
Viva 10
Total 50

Signature of the Student:

Signature of the Faculty:

*As applicable according to the experiment.


Two sheets per experiment (10-20) to be used.

You might also like