Java Notes(Unit III,IV)
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();}
}
}
}
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());
}
}
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");
}
}
Annotations are denoted by the "@" symbol followed by the annotation name, and can
include attributes or parameters. Some commonly used annotations in Java include:
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.
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>*/
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.
For example:
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);
}
}
}
}
Examples:
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;
}
}