0% found this document useful (0 votes)
9 views17 pages

Java Notes(Unit III,IV)

This document covers key concepts in Java programming, including input/output operations with Scanner and Console classes, file handling through character and byte streams, serialization and deserialization, exception handling, and annotations. It also explains the applet lifecycle, thread lifecycle, and demonstrates examples for creating custom exceptions, merging files, and handling various exceptions. The document serves as a comprehensive guide for understanding essential Java programming techniques and concepts.

Uploaded by

andemhindu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views17 pages

Java Notes(Unit III,IV)

This document covers key concepts in Java programming, including input/output operations with Scanner and Console classes, file handling through character and byte streams, serialization and deserialization, exception handling, and annotations. It also explains the applet lifecycle, thread lifecycle, and demonstrates examples for creating custom exceptions, merging files, and handling various exceptions. The document serves as a comprehensive guide for understanding essential Java programming techniques and concepts.

Uploaded by

andemhindu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 17

JAVA NOTES(UNIT-III,IV)

UNIT-III
Scanner class, console class (main method)
The Scanner class and the Console class are used for input/output operations in
Java.

The Scanner class is used to read input from the user or a file. It is a class in the
java.util package and provides various methods to read different types of input
data, such as next() , nextInt() , nextDouble() , and more. Here is an
example of using the Scanner class to read a user's name from the console:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}

The Console class is used to read input and display output to the console. It is a
class in the java.io package and provides methods to read input without echoing it to
the console (such as readPassword() ), and to display output to the console
without a newline (such as format() ). Here is an example of using the Console
class to read a user's password from the console:
import java.io.Console;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("Console not available");
System.exit(1);
}
char[] password = console.readPassword("Enter your password: ");
System.out.println("Your password is: " + new String(password));
}
}

Q1.Copying contents from one file to another file (character & Byte Streams)
A.In Java, a stream is a sequence of data elements made available over time. Streams
are categorized as either character streams or byte streams, depending on the type of
data being processed.

Character Stream:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Byte stream:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally
{
if (in != null) {in.close();}
if (out != null) {out.close();}
}
}
}

Q2.Serialization and deserialization (Program)


A.
a) Serialization: Serialization is the process of converting an object's state to a byte
stream so that it can be easily saved to disk, transmitted over a network, or
manipulated in memory. The main purpose of serialization is to save the object's state
and then later recreate the object from the saved state. In Java, this is achieved by
implementing the Serializable interface.

Example program:

import java.io.*;
public class SerializationExample implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public SerializationExample(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) throws Exception {
SerializationExample object = new SerializationExample(1, "John");
// Serializing the object
FileOutputStream fos = new FileOutputStream("serialization.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
// Deserializing the object
FileInputStream fis = new FileInputStream("serialization.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
SerializationExample object2 = (SerializationExample) ois.readObject();
ois.close();
fis.close();
System.out.println("ID: " + object2.getId());
System.out.println("Name: " + object2.getName());
}
}

b) DeSerialization: Deserialization is the process of converting a stream of bytes into


an object in memory. This is the opposite of serialization, which is the process of
converting an object into a stream of bytes so that it can be stored or transmitted over
a network.

Here's an example of deserialization in Java:


import java.io.*;
class DeserializationExample {
public static void main(String [] args) {
Employee employee;
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
employee = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + employee.name);
System.out.println("Address: " + employee.address);
System.out.println("SSN: " + employee.SSN);
System.out.println("Number: " + employee.number);
}
}

Q3.Merging of two files


// Java program to merge two
// files into third file

import java.io.*;
public class FileMerge
{
public static void main(String[] args) throws IOException
{
// PrintWriter object for file3.txt
PrintWriter pw = new PrintWriter("file3.txt");
// BufferedReader object for file1.txt
BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
String line = br.readLine();
// loop to copy each line of
// file1.txt to file3.txt
while (line != null)
{
pw.println(line);
line = br.readLine();
}
br = new BufferedReader(new FileReader("file2.txt"));
line = br.readLine();
// loop to copy each line of
// file2.txt to file3.txt
while(line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush();
// closing resources
br.close();
pw.close();
System.out.println("Merged file1.txt and file2.txt into file3.txt");
}
}

Q4.Exception Handling and key words Related to Exception


A.Exception handling is a mechanism in Java that allows a program to handle errors
and exceptional situations gracefully, rather than crashing or terminating abruptly. The
Java language provides several keywords and constructs to handle exceptions, including:
1. try-catch: The try-catch block is used to catch and handle exceptions that are
thrown by a program. It consists of a try block that contains the code that may
throw an exception, and one or more catch blocks that handle the thrown
exception.
2. throw: The throw keyword is used to explicitly throw an exception from a method
or block of code.
3. throws: The throws keyword is used to declare that a method may throw a
particular exception, and is used in the method signature.
4. finally: The finally block is used to contain code that must be executed regardless
of whether an exception is thrown or not. It is typically used to clean up resources
such as files or database connections.
5. catch: The catch block is used to catch and handle exceptions that are thrown by
a program. It contains code that is executed if an exception is thrown.

public class Example {


public static void main(String[] args) {
try {
int x = 10 / 0; // this will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught exception: " + e);
} finally {
System.out.println("Finally block executed");
}
}
}
Other keywords related to exception handling in Java include:
1. try-with-resources: This is a special try block that is used for automatically closing
resources such as files or database connections.
2. assert: The assert keyword is used to test a condition and throw an AssertionError
if the condition is false.
3. Error: An Error is a serious problem that cannot be handled by a program, such as
running out of memory.
4. RuntimeException: A RuntimeException is an exception that is typically caused by
a programming error, such as dividing by zero.
5. Checked Exception: A Checked Exception is an exception that must be declared in
the method signature or caught in a try-catch block, and is typically caused by
external factors such as file I/O or network errors.

Q5.Nested try catch block


A.
public class Main{
public static void main(String args[])
{
// outer (main) try block
try {

//inner try block 1


try {
// inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };
//printing the array element out of its bounds
System.out.println(arr[10]);
}
// to handles ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// to handle ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}

Q6.Arithmetic Exception, Null Pointer Exception, Array Index Out of Bounds


Exception.
A.
public class ExceptionDemo {
public static void main(String[] args) {
// Arithmetic Exception
try {
int result = 10 / 0; // division by zero
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
}
// Null Pointer Exception
String str = null;
try {
System.out.println(str.length()); // accessing length of null string
} catch (NullPointerException e) {
System.out.println("Null Pointer Exception: " + e.getMessage());
}
// Array Index Out of Bounds Exception
int[] arr = {1, 2, 3};
try {
int num = arr[3]; // accessing element outside array size
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: " + e.getMessage());
}
}
}

Q7.Different between throw and Throws


A.
Q8.creating custom exception for validating votes
A.
class UnderAgeException extends Exception {
public UnderAgeException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
int age = 17;
try {
if (age < 18) {
throw new UnderAgeException("under 18 are not eligible to vote.");
}
else {
System.out.println("Valid vote!");
}
}
catch (UnderAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
UNIT-IV
Q1.What do you mean by Annotation's and their significance
A.Annotations are a way to add metadata to Java code. They provide additional
information about the code and can be used to control the behavior of the compiler
and the runtime environment.

Annotations are denoted by the "@" symbol followed by the annotation name, and can
include attributes or parameters. Some commonly used annotations in Java include:

@Override: Indicates that a method is intended to override a method in a


superclass.
@Deprecated: Marks a method or class as deprecated and informs users that it is
no longer recommended for use.
@SuppressWarnings: Suppresses compiler warnings for a specific code block or
element.
@FunctionalInterface: Indicates that an interface is intended to be a functional
interface with a single abstract method.
@Test: Used in JUnit testing to mark a method as a test method.

Annotations can also be used to create custom annotations with specific behaviors and
attributes. These custom annotations can be used to enforce coding standards,
document code, or automate tasks.

Q2.Applet Life cycle


A.An Applet is a special type of Java program that is designed to be run within a web
browser. An applet has a specific life cycle that consists of several methods that are
called at different stages in its execution. The most important life cycle methods are:

1. init - this method is called when the applet is first loaded.


2. start - this method is called after the init method and is used to start the applet's
execution.
3. paint - this method is called to paint the applet's graphics on the screen.
4. stop - this method is called when the applet is stopped, either because the user
navigates away from the page or because the applet has completed its execution.
5. destroy - this method is called when the applet is being removed from memory.

Q3.Passing parametres
A.Here's an example of an applet that displays a welcome message along with the
current date:
import java.applet.Applet;
import java.awt.Graphics;
import java.util.Date;
public class WelcomeApplet extends Applet {
public void init() {
setSize(400, 400);
}
public void paint(Graphics g) {
g.drawString("Welcome!", 150, 150);
g.drawString(new Date().toString(), 150, 170);
}
}
/*
<applet code="WelcomeApplet.class" width="400" height="400">
<param name="message" value="Hello, World!">
</applet>*/

Q4.Thread Life cycle


A.Thread life cycle in Java refers to the various states a thread goes through from its
creation to its termination. The different states of a thread are represented by different
constants defined in the Thread class. Here are the different states of a thread in the
order they occur:

1. New: A thread is in this state when it is first created using the new keyword but
has not yet been started using the start() method.
2. Runnable: A thread is in this state when the start() method has been called but the
thread has not yet been allocated CPU time by the scheduler.
3. Running: A thread is in this state when it has been allocated CPU time by the
scheduler and is currently executing.
4. Blocked: A thread is in this state when it is waiting for a monitor lock to be
released by another thread. This can occur when the thread calls a synchronized
method or block.
5. Waiting: A thread is in this state when it is waiting indefinitely for another thread
to perform a certain action. This can occur when the thread calls the wait() method.
6. Timed Waiting: A thread is in this state when it is waiting for a specified period of
time for another thread to perform a certain action. This can occur when the
thread calls the sleep() or join() methods with a timeout value.
7. Terminated: A thread is in this state when it has finished executing its run()
method and has terminated.

Q5.Creating of Thread by extending Thread class, Runnable ? (Example program)


A.Extending the Thread class: To create a multi-threaded application by extending the
Thread class, you need to follow these steps:
Create a class that extends the Thread class.
Override the run() method in the new class, this method will contain the code that
will be executed by the new thread.
Create an instance of the new class.
Call the start() method on the new class instance to start the new thread.

For example:

class MyThread extends Thread {


public void run() {
// Code to be executed by the new thread
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}

Implementing the Runnable interface: To create a multi-threaded application by


implementing the Runnable interface, you need to follow these steps:
Create a class that implements the Runnable interface.
Override the run() method in the new class, this method will contain the code that
will be executed by the new thread.
Create an instance of the new class.
Create a new instance of the Thread class and pass the new class instance as an
argument to the Thread class constructor.
Call the start() method on the Thread class instance to start the new thread.

For example:
class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the new thread
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}

Q6.Thread Priority
A.
public class ThreadPriorityDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread(), "Thread 1");
Thread t2 = new Thread(new MyThread(), "Thread 2");
// set priority of threads
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
// start threads
t1.start();
t2.start();
}
static class MyThread implements Runnable {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
}

Q7.Any 5 methods of Thread Class


A.
public class ThreadDemo implements Runnable {
private String threadName;
private int delay;
public ThreadDemo(String threadName, int delay) {
this.threadName = threadName;
this.delay = delay;
}
@Override
public void run() {
System.out.println(threadName + " started.");
try {
// Sleep for some time
Thread.sleep(delay);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " finished.");
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadDemo("Thread 1", 2000));
Thread t2 = new Thread(new ThreadDemo("Thread 2", 4000));
// Set the priority of threads
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
// Start the threads
t1.start();
t2.start();
// Check if the threads are alive
System.out.println(t1.getName() + " is alive: " + t1.isAlive());
System.out.println(t2.getName() + " is alive: " + t2.isAlive());
// Wait for the threads to finish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Check if the threads are alive after join
System.out.println(t1.getName() + " is alive: " + t1.isAlive());
System.out.println(t2.getName() + " is alive: " + t2.isAlive());
// Get the name of the current thread
System.out.println("Current thread: " + Thread.currentThread().getName());
}
}

Q8.Synchronization Program (Method and class)


A.
Synchronized:
The synchronized keyword in Java is used to define a block of code that can be
accessed by only one thread at a time. This is useful when you want to avoid conflicts
between multiple threads that access the same shared data.

Examples:

To synchronize a block of code:


public class Counter {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}

To synchronize a static method:


public class SynchronizedExample {
private static int count = 0;
public static synchronized void incrementCount() {
count++;
}
public static int getCount() {
return count;
}
}

To synchronize a class:
public class SynchronizedExample {
private static int count = 0;
public static void incrementCount() {
synchronized(SynchronizedExample.class) {
count++;
}
}
public static int getCount() {
return count;
}
}

Q9.Producer Consumer(Foint, wait,notifing)


A.
import java.util.LinkedList;
public class ProducerConsumer {
public static void main(String[] args) {
final PC pc = new PC();
// Create a producer thread
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Create a consumer thread
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// Wait for both threads to finish
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Producer method
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (this) {
// Wait until the list is not full
while (list.size() == capacity)
wait();
System.out.println("Producer produced-" + value);
// Insert the item into the list
list.add(value++);
// Notify the consumer that the list has changed
notify();
// Sleep for some time
Thread.sleep(1000);
}
}
}
// Consumer method
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
// Wait until the list is not empty
while (list.size() == 0)
wait();
// Remove the first item from the list
int val = list.removeFirst();
System.out.println("Consumer consumed-" + val);
// Notify the producer that the list has changed
notify();
// Sleep for some time
Thread.sleep(1000);
}
}
}
}
}

Made with❤️by Telegram @oxrogerthat

You might also like