You are on page 1of 52

AOOP NOTES:

UNIT 1:
Introducing JavaFX GUI Programming
JavaFX Basic Concepts:
✓ JavaFX simplifies rendering of objects because it handles repainting automatically
✓ JavaFX elements are contained in packages that begin with javafx prefix
✓ javafx.application
✓ javafx.stage
✓ javafx.scene
✓ javafx.scene.layout

Stage and Scene Classes:


✓ A stage is a container for scenes
✓ A scene is a container for the items that comprise the scene
✓ All JavaFX applications have at least one stage and one scene
✓ These elements are encapsulated in JavaFX API by Stage and Scene classes
✓ To create JavaFX application, add at least one Scene object to a Stage
✓ Stage is a top-level container
✓ All JavaFX applications automatically have access to one Stage called the primary
stage
✓ Primary stage is supplied by run-time when a JavaFX application is started
✓ Scene is a container for the items that comprise the scene
✓ Items include controls such as push buttons, check boxes, text and graphics
✓ To create a scene, we need to add those elements to an instance of Scene
Nodes and Scene Graphs:
✓ Individual elements of a scene are called as nodes
✓ E.g., push button control is a node
✓ Nodes can also consist of group of nodes
✓ A node can have a child node
✓ A node with a child node is called a parent node or branch node
✓ Nodes without children are terminal nodes and are called leaves
✓ Collection of all nodes in a scene creates a scene graph, which comprises a tree
✓ There is one special type of node in the scene graph called the root node
✓ Root node is the top-level node and is the only node in the scene graph that does
not have a parent
✓ Thus, all nodes except root node have parents
✓ All nodes either directly or indirectly descend from the root node
✓ Base class for all nodes is Node
✓ Sub-classes of Node: Parent, Group, Region and Control

Layouts:
✓ In JavaFX layout panes manage the process of placing elements in a scene
✓ Layout panes are packaged in javafx.scene.layout

We need to import javafx.application.Application class in every JavaFX application. This provides


the following life cycle methods for JavaFX application.

o public void init()


o public abstract void start(Stage primaryStage)
o public void stop()

in order to create a basic JavaFX application, we need to:

1. Import javafx.application.Application into our code.


2. Inherit Application into our class.
3. Override start() method of Application class.
init() method
✓ init() method is called when the application begins execution
✓ It is used to perform various initializations
✓ init() method cannot be used to create a stage or build a scene
✓ If no initializations are required, this method need not be overridden because an
empty, default version is provided

start() and stop() methods:


✓ start() method is called after init()
✓ This is where the application begins
✓ It can be used to construct and set the scene
✓ Stage object reference is passed to start() method
✓ This object reference is the stage provided the run-time system and is the primary
stage
✓ start() method is abstract and must be overridden by the application
✓ When application is terminated, stop() method is called
✓ Any clean-up or shutdown tasks can be handled inside this method
✓ If no clean-ups are required, this method need not be overridden because an
empty, default
version is provided

Launching a JavaFX Application:


✓ To start JavaFX application, launch() method defined by Application class must be
called
✓ public static void launch(String ... args)
✓ When launch() is called, it causes the application to be constructed, followed by
calls to init()
and start()
✓ The launch() method will not return until after the application has terminated
✓ Two versions of launch() method are available
✓ In first version, launch() starts subclass of Application from which launch() is called
✓ In second version, launch() lets us specify a class other than the enclosing class to
start
✓ JavaFX applications that have been packaged by using javafxpackager tool need not
include a call to launch()

JavaFX Application Skeleton


// A JavaFX application skeleton.
import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.scene.layout.*;
public class JavaFXSkel extends Application {
public static void main(String[] args) {
System.out.println("Launching JavaFX
application.");

// Start the JavaFX application by calling


launch().
launch(args);
}
// Override the init() method.
public void init() {
System.out.println("Inside the init() method.");
}
// Override the start() method.
public void start(Stage myStage) {
System.out.println("Inside the start()
method.");
// Give the stage a title.
myStage.setTitle("JavaFX Skeleton.");
// Create a root node. In this case, a flow layout
pane
// is used, but several alternatives exist.
FlowPane rootNode = new FlowPane();

// Create a scene.
Scene myScene = new Scene(rootNode, 300,
200);
// Set the scene on the stage.
myStage.setScene(myScene);
// Show the stage and its scene.
myStage.show();
}

LABEL:
A label just displays a text message
✓ JavaFX label is an instance of Label class packaged in javafx.scene.control
✓ Label inherits Labeled and Control classes
✓ Labeled class provides features that are common to all labelled elements
✓ Control class provides features that are related to controls

Event Handling in JavaFX:


✓ Event class packaged in javafx.event is base class for JavaFX events
✓ Event inherits java.util.EventObject
✓ JavaFX uses delegation event model to handle events
✓ To handle an event, we must first register the handler that acts as a listener for the
event
✓ When the event occurs, the listener is called
✓ It must then respond to the event and return
✓ Events are handled by implementing EventHandler interface packaged in
javafx.event
✓ interface EventHandler<T extends Event>
✓ T → type of the event that the handler will handle
✓ void handle(T eventObj)

JavaFX TextField
example where the user is shown the two text boxes and prompted to fill its user-id and password.

1. package application;  
2. import javafx.application.Application;  
3. import javafx.scene.Scene;  
4. import javafx.scene.control.Button;  
5. import javafx.scene.control.Label;  
6. import javafx.scene.control.TextField;  
7. import javafx.scene.layout.GridPane;  
8. import javafx.stage.Stage;  
9. public class TextFieldTest extends Application {  
10.   
11.       
12. public static void main(String[] args) {  
13. launch(args);     
14. }  
15.   
16. @Override  
17. public void start(Stage primaryStage) throws Exception {  
18.     // TODO Auto-generated method stub  
19.     Label user_id=new Label("User ID");  
20.     Label password = new Label("Password");  
21.     TextField tf1=new TextField();  
22.     TextField tf2=new TextField();  
23.     Button b = new Button("Submit");  
24.     GridPane root = new GridPane();  
25.     root.addRow(0, user_id, tf1);  
26.     root.addRow(1, password, tf2);  
27.     root.addRow(2, b);  
28.     Scene scene=new Scene(root,800,200);  
29.     primaryStage.setScene(scene);  
30.     primaryStage.setTitle("Text Field Example");  
31.     primaryStage.show();  
32. }  
33. }  

Output:

Getting Text field Data


TextField class provides an instance method getText() to retrieve the textfield data. It returns
String object which can be used to save the user details in database.

Play Video
Play

Unmute

Current Time 0:12

Duration 4:57

Loaded: 100.00%

 

Fullscreen
1. package application;  
2. import javafx.application.Application;  
3. import javafx.scene.Scene;  
4. import javafx.scene.control.Button;  
5. import javafx.scene.control.Label;  
6. import javafx.scene.control.TextField;  
7. import javafx.scene.layout.GridPane;  
8. import javafx.stage.Stage;  
9. public class TextFieldExample extends Application {  
10.   
11.       
12. public static void main(String[] args) {  
13. launch(args);     
14. }  
15.   
16. @Override  
17. public void start(Stage primaryStage) throws Exception {  
18.     // TODO Auto-generated method stub  
19.     Label user_id=new Label("User ID");  
20.     Label password = new Label("Password");  
21.     TextField tf1=new TextField();  
22.     TextField tf2=new TextField();  
23.     Button b = new Button("Submit");  
24.     b.setOnAction(e->System.out.println("You entered: User_ID: "+tf1.getText()+""+"Password: 
"+tf2.getText()));  
25.     GridPane root = new GridPane();  
26.     root.addRow(0, user_id, tf1);  
27.     root.addRow(1, password, tf2);  
28.     root.addRow(2, b);  
29.     Scene scene=new Scene(root,300,200);  
30.     primaryStage.setScene(scene);  
31.     primaryStage.setTitle("Text Field Example");  
32.     primaryStage.show();  
33. }  
34. }  

Output:

JAVA FX REG FORM:


import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class RegistrationForm extends Application {


public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Registration Form");

// Create grid pane


GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));

// Create form labels


Label nameLabel = new Label("Full Name:");
Label emailLabel = new Label("Email:");
Label passwordLabel = new Label("Password:");

// Create form text fields


TextField nameField = new TextField();
TextField emailField = new TextField();
TextField passwordField = new TextField();
// Add labels and text fields to grid
grid.add(nameLabel, 0, 0);
grid.add(nameField, 1, 0);
grid.add(emailLabel, 0, 1);
grid.add(emailField, 1, 1);
grid.add(passwordLabel, 0, 2);
grid.add(passwordField, 1, 2);

// Create submit button


Button submitButton = new Button("Submit");
grid.add(submitButton, 1, 4);

// Create scene and add to stage


Scene scene = new Scene(grid, 300, 275);
primaryStage.setScene(scene);

// Show stage
primaryStage.show();
}
}

PROGRAM TO FIND MIN MAX AND ASC ORDER OF AN ARRAY LIST USING STREAMS:
public static void main(String[] args) {
// Initialize ArrayList with sample values
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(5);
arrayList.add(1);
arrayList.add(3);
arrayList.add(8);
arrayList.add(2);

// Find minimum value using streams


int minValue = arrayList.stream().min(Integer::compareTo).get();
System.out.println("Minimum value: " + minValue);

// Find maximum value using streams


int maxValue = arrayList.stream().max(Integer::compareTo).get();
System.out.println("Maximum value: " + maxValue);

// Sort ArrayList in ascending order


Collections.sort(arrayList);
System.out.println("Sorted ArrayList: " + arrayList);
}

CONCATENATE TWO STRINGS USING L.E:


public static void main(String[] args) {
// Initialize list of strings
List<String> stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add(" ");
stringList.add("World");

// Concatenate strings using lambda expression


String concatenatedString = stringList.stream().reduce("", (a, b) -> a + b);
System.out.println("Concatenated String: " + concatenatedString);
}

Q]write a java program using lambda expressions to


compare two strings and changing the case of
characters of both strings and also compare the
characters stored at each index
Here is an example of a Java program that uses lambda expressions to compare two strings and change the case
of the characters of both strings and also compare the characters stored at each index:

import java.util.function.Function;

public class Main {


public static void main(String[] args) {
String s1 = "Hello";
String s2 = "WORLD";

// Using lambda expressions to define the function to change the case of a string
Function<String, String> toUpperCase = (str) -> str.toUpperCase();
Function<String, String> toLowerCase = (str) -> str.toLowerCase();

// Using the lambda expressions to change the case of the strings


s1 = toUpperCase.apply(s1);
s2 = toLowerCase.apply(s2);

// Comparing the characters of the strings


for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
System.out.println("Different characters at index " + i + ": " + s1.charAt(i) + "
vs " + s2.charAt(i));
}
}
}
}
This program defines two lambda expressions, one to change a string to uppercase and another to change
a string to lowercase. Then, it applies these lambda expressions to the two input strings and compare the
characters stored at each index.
Q.Write a java program to compare the 2 string using
bounded type and wild card character the programme
should print appropriate messages
Here's an example of a Java program that compares two strings using a bounded type and a
wildcard character, and prints appropriate messages:

import java.util.ArrayList;

import java.util.List;

public class Main {

public static void main(String[] args) {

List<String> list1 = new ArrayList<>();

list1.add("Hello");

list1.add("world");

List<String> list2 = new ArrayList<>();

list2.add("HELLO");

list2.add("WORLD");

compare(list1, list2);

public static <T extends CharSequence> void compare(List<? extends T> list1, List<? extends T> list2) {

if (list1.size() != list2.size()) {

System.out.println("Both lists are of different sizes");

return;

for (int i = 0; i < list1.size(); i++) {

T str1 = list1.get(i);

T str2 = list2.get(i);

if (!str1.toString().equalsIgnoreCase(str2.toString())) {

System.out.println(str1 + " and " + str2 + " are not equal.");

} else {

System.out.println(str1 + " and " + str2 + " are equal.");

}
}

In this program, the compare method is defined with two type parameters T that are bounded by
the CharSequence class and are using wildcard characters ?. This means that the method can only be
used with lists of subtypes of CharSequence, such as String .

In the main method, the compare method is used to compare two lists of strings. The method
compares the elements of both lists and prints appropriate messages when the elements are not
equal.

This way it demonstrates that the type parameter T is bounded by the CharSequence class and using
wildcard characters ?, so it only works with subtypes of CharSequence and it compares the elements
of both lists and prints appropriate messages when the elements are not equal.

CountDownLatch vs CyclicBarrier vs Phaser


The  CountDownLatch  is :
 Created with a fixed number of threads
 Cannot be reset
Allows threads to wait( CountDownLatch#await() ) or continue with its

execution( CountDownLatch#countDown() ).
On the other hand, the  CyclicBarrier  :
 Can be reset.
 Does not a provide a method for the threads to advance. The threads have to wait till all the
threads arrive.
 Created with fixed number of threads.
Now, the  Phaser  has following properties :
 Number of threads need not be known at Phaser creation time. They can be added
dynamically.
 Can be reset and hence is, reusable.
 Allows threads to wait( Phaser#arriveAndAwaitAdvance() ) or continue with its
execution( Phaser#arrive() ).
 Supports multiple Phases(, hence the name phaser).
We will try to understand how the  Phaser  Class can be used with an example. In this example, we are
creating a three threads, which will wait for the arrival all the threads being created. Once all the
threads have arrived(marked by  arriveAndAwaitAdvance()  method) the Phaser allows them through the
barrier.

PROGRAM:
package com.javacodegeeks.examples;

import java.util.concurrent.Phaser;
public class PhaserExample

public static void main(String[] args) throws InterruptedException

Phaser phaser = new Phaser();

phaser.register();//register self... phaser waiting for 1 party (thread)

int phasecount = phaser.getPhase();

System.out.println("Phasecount is "+phasecount);

new PhaserExample().testPhaser(phaser,2000);//phaser waiting for 2 parties

new PhaserExample().testPhaser(phaser,4000);//phaser waiting for 3 parties

new PhaserExample().testPhaser(phaser,6000);//phaser waiting for 4 parties

//now that all threads are initiated, we will de-register main thread

//so that the barrier condition of 3 thread arrival is meet.

phaser.arriveAndDeregister();

Thread.sleep(10000);

phasecount = phaser.getPhase();

System.out.println("Phasecount is "+phasecount);

private void testPhaser(final Phaser phaser,final int sleepTime)

phaser.register();

new Thread(){

@Override

public void run()

try

System.out.println(Thread.currentThread().getName()+" arrived");

phaser.arriveAndAwaitAdvance();//threads register arrival to the phaser.

Thread.sleep(sleepTime);

}
catch (InterruptedException e)

e.printStackTrace();

System.out.println(Thread.currentThread().getName()+" after passing barrier");

}.start();

WORKING OF PHASER:
A Phaser is a reusable synchronization barrier in the Java Concurrent package. It is similar to a
CyclicBarrier and a CountDownLatch, but provides more flexibility and control over the execution
of concurrent threads.

A Phaser works by dividing a set of threads into multiple "parties". Each party is required to reach
the barrier point (or "phase") before the next phase can begin. The Phaser class provides methods
for registering, deregistering, and awaiting parties, as well as methods for controlling the flow of
execution.

For example, consider a Phaser used to coordinate the execution of three tasks in parallel:

import java.util.concurrent.Phaser;

public class Main {


public static void main(String[] args) {
Phaser phaser = new Phaser(3); // 3 parties
new Task(phaser, "Task 1").start();
new Task(phaser, "Task 2").start();
new Task(phaser, "Task 3").start();
}
}

class Task extends Thread {


private Phaser phaser;

public Task(Phaser phaser, String name) {


this.phaser = phaser;
setName(name);
}

public void run() {


System.out.println(getName() + " starting phase 1");
phaser.arriveAndAwaitAdvance(); // party arrives and waits for others to arrive
System.out.println(getName() + " starting phase 2");
phaser.arriveAndAwaitAdvance(); // party arrives and waits for others to arrive
System.out.println(getName() + " starting phase 3");
}
}

The output of this program will be something like this:

Task 1 starting phase 1


Task 2 starting phase 1
Task 3 starting phase 1
Task 1 starting phase 2
Task 2 starting phase 2
Task 3 starting phase 2
Task 1 starting phase 3
Task 2 starting phase 3
Task 3 starting phase 3
Task 1 starting phase 1 Task 2 starting phase 1 Task 3 starting phase 1 Task 1 starting phase 2 Task 2 starting phase 2 Task 3
starting phase 2 Task 1 starting phase 3 Task 2 starting phase 3 Task 3 starting phase 3

As you can see all the tasks are starting phase 1 at the same time, and once all the parties have arrived,
Phaser moves to the next phase, and all parties are released to proceed.

Phasers are useful in situations where you need to coordinate the execution of multiple threads and you need
more control over the execution flow than what is provided by a CyclicBarrier or a CountDownLatch.
Q.The program should print the name of the thread in
the phaser and registered and unregistered parties and
phase level
Sure, here's an example of a program that demonstrates the use of a Phaser, including printing the name of the
thread in the Phaser, registered and unregistered parties, and the current phase level:

import java.util.concurrent.Phaser;

public class Main {

public static void main(String[] args) {

Phaser phaser = new Phaser(1); // 1 initial party

new Task(phaser, "Task 1").start();

new Task(phaser, "Task 2").start();

new Task(phaser, "Task 3").start();

while (!phaser.isTerminated()) {

System.out.println("Thread " + Thread.currentThread().getName() + ":


Phase: " + phaser.getPhase()

+ ", Registered Parties: " + phaser.getRegisteredParties()

+ ", Arrived Parties: " + phaser.getArrivedParties()

+ ", Unarrived Parties: " + phaser.getUnarrivedParties());

phaser.arriveAndAwaitAdvance();

System.out.println("All parties have finished, Phaser is terminated.");

}
class Task extends Thread {

private Phaser phaser;

public Task(Phaser phaser, String name) {

this.phaser = phaser;

setName(name);

phaser.register();

public void run() {

System.out.println(getName() + " starting phase 1");

phaser.arriveAndAwaitAdvance(); // party arrives and waits for others to arrive

System.out.println(getName() + " starting phase 2");

phaser.arriveAndAwaitAdvance(); // party arrives and waits for others to arrive

System.out.println(getName() + " starting phase 3");

phaser.arriveAndDeregister();

In this program, the main method creates a Phaser with 1 initial party. Three tasks are created,
started, and registered with the Phaser. Each task represents a party, which calls the
arriveAndAwaitAdvance() and arriveAndDeregister() method on the Phaser when it reaches a barrier
point. The arriveAndAwaitAdvance() method tells the Phaser that the party has arrived and is waiting
for the other parties to arrive. Once all parties have arrived, the Phaser moves to the next phase,
and all parties are released to proceed.

The output of this program will be something like this:

Task 1 starting phase 1

Task 2 starting phase 1


Task 3 starting phase 1

Thread main: Phase: 0, Registered Parties: 4, Arrived Parties: 1, Unarrived Parties:


3

Task 1 starting phase 2

Task 2 starting phase 2

Task 3 starting phase 2

Thread main: Phase: 1, Registered Parties: 4, Arrived Parties: 4, Unarrived Parties:


0

Task 1 starting phase 3

Task 2 starting phase 3

Task 3 starting phase 3

Thread main: Phase: 2, Registered Parties: 4, Arrived Parties: 3, Unarrived Parties:


1

All parties have finished, Phaser is terminated.

Q. Write java program to illustrate the working of


countdown latch mechanism in the concurrent utility to print
the even number between 1 to 10 and odd numbers between
11 to 20
A CountDownLatch is a synchronization mechanism in the Java Concurrent package. It allows one
or more threads to wait for a set of operations performed by other threads to complete.

Here's an example of a Java program that illustrates the use of a CountDownLatch to print even
numbers between 1 to 10 and odd numbers between 11 to 20:

import java.util.concurrent.CountDownLatch;

public class Main {


public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
Thread evenThread = new Thread(new EvenPrinter(latch));
Thread oddThread = new Thread(new OddPrinter(latch));

evenThread.start();
oddThread.start();
latch.await(); // main thread waits for evenThread and oddThread to complete

System.out.println("All tasks completed");


}
}

class EvenPrinter implements Runnable {


private CountDownLatch latch;

public EvenPrinter(CountDownLatch latch) {


this.latch = latch;
}

public void run() {


for (int i = 2; i <= 10; i += 2) {
System.out.println("Even number: " + i);
}
latch.countDown(); // decrement the latch count
}
}

class OddPrinter implements Runnable {


private CountDownLatch latch;

public OddPrinter(CountDownLatch latch) {


this.latch = latch;
}

public void run() {


for (int i = 11; i <= 20; i += 2) {
System.out.println("Odd number: " + i);
}
latch.countDown(); // decrement the latch count
}
}

In this example, the main method creates a CountDownLatch with a count of 2. Two threads are
created, one for printing even numbers and the other for printing odd numbers. The main thread
calls the await() method on the CountDownLatch, which causes it to wait until the count reaches
zero.

The two worker threads, evenThread and oddThread, perform their respective operations and then
call the countDown() method on the CountDownLatch, which decrements the count. Once both
threads have finished and the count reaches zero, the main thread is released from the await() call
and continues execution.

The output of this program will be something like this:

Even number: 2

Even number: 4
Even number: 6

Even number: 8

Even number: 10

Odd number: 11

Odd number: 13

Odd number: 15

Odd number: 17

Odd number: 19

All tasks completed

Q. Write a java program to fetch content length , All inet


addresses, response code , response message , header key and
values ,host , filename , external form ,expiration date and
content type of a given URL.
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;

public class Main {


public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.com");
URLConnection connection = url.openConnection();

// Fetching the content length


int contentLength = connection.getContentLength();
System.out.println("Content Length: " + contentLength);

// Fetching all Inet addresses


InetAddress[] addresses = InetAddress.getAllByName(url.getHost());
for (InetAddress address : addresses) {
System.out.println("Inet Address: " + address);
}

// Fetching the response code


int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println("Response Code: " + responseCode);

// Fetching the response message


String responseMessage = ((HttpURLConnection) connection).getResponseMessage();
System.out.println("Response Message: " + responseMessage);

// Fetching header keys and values


Map<String, List<String>> headerFields = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : headerFields.entrySet())
}

import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;

public class Main {


public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.com");
URLConnection connection = url.openConnection();

// Fetching header keys and values


Map<String, List<String>> headerFields = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) {
System.out.println("Header Key: " + entry.getKey());
System.out.println("Header Value: " + entry.getValue());
}

// Fetching the host


String host = url.getHost();
System.out.println("Host: " + host);

// Fetching the file name


String file = url.getFile();
System.out.println("File Name: " + file);

// Fetching the external form


String externalForm = url.toExternalForm();
System.out.println("External Form: " + externalForm);

// Fetching the expiration date


long expiration = connection.getExpiration();
System.out.println("Expiration: " + new Date(expiration));

// Fetching the content type


String contentType = connection.getContentType();
System.out.println("Content Type: " + contentType);
}
}

Q. write a java Program to build an RMI application that


returns the domain name from the given URL
Server side:
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.net.URL;

public class DomainNameServer extends UnicastRemoteObject implements DomainName {

public DomainNameServer() throws RemoteException {


super();
}

public String getDomainName(String url) throws Exception {


URL aURL = new URL(url);
return aURL.getHost();
}

public static void main(String[] args) {


try {
LocateRegistry.createRegistry(1099);
DomainNameServer server = new DomainNameServer();
Naming.rebind("rmi://localhost:1099/domainNameService", server);
System.out.println("Server ready");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client Side:
import java.rmi.Naming;
public class DomainNameClient {
public static void main(String[] args) throws Exception {
DomainName domainName = (DomainName)
Naming.lookup("rmi://localhost:1099/domainNameService");
String domain = domainName.getDomainName("http://www.example.com");
System.out.println("Domain name: " + domain);
}
}

In this example, the DomainNameServer class creates an RMI server that implements the DomainName interface. The
interface has a single method, getDomainName(), that takes a URL as a parameter and returns the domain name
using the URL class. The server exports the object and binds it to the RMI registry so that it can be located by
clients.

The DomainNameClient class creates an RMI client that looks up the DomainName object on the RMI registry

Q. Write a java program to develop client and server


applications using socket programming.

Server Side:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server running on port 8080");

while (true) {
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, client!");
out.close();
socket.close();
}
}
}

Client Side:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String serverResponse = input.readLine();
System.out.println("Server: " + serverResponse);
input.close();
socket.close();
}
}

Q. Write a java program to develop client and server


applications using socket programming to display the
cgpa for given usn the application should send the
result back to the client.

Server Side:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Server {


private static HashMap<String, Double> cgpaList = new HashMap<>();

public static void main(String[] args) throws IOException {


ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("Server started...");

// Populate the CGPA list


cgpaList.put("1MS17IS001", 8.5);
cgpaList.put("1MS17IS002", 7.5);
cgpaList.put("1MS17IS003", 9.0);

while (true) {
Socket socket = serverSocket.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

// Read the USN from the client


String usn = dis.readUTF();
System.out.println("Received USN: " + usn);

// Lookup the CGPA for the USN


Double cgpa = cgpaList.get(usn);

// Send the CGPA to the client


dos.writeDouble(cgpa);
dos.flush();

// Close the socket


socket.close();
}
}
}

Client Side:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class Client {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8000);
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in);
System.out.print("Enter USN: ");
String usn = scanner.nextLine();

// Send the USN to the server


dos.writeUTF(usn);
dos.flush();

// Read the CGPA

Java program that demonstrates how to implement a student database using information such as
name, USN, and CGPA, with the corresponding datatype varchar(20), varchar(10) and double, and
display the content in a table format using JDBC:

import java.sql.*;

public class StudentDatabase {

public static void main(String[] args) {


Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Connect to the database


connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_db",
"root", "password");

// Create a statement
statement = connection.createStatement();

// Execute the query


resultSet = statement.executeQuery("SELECT name,usn,cgpa FROM student");
// Print the results in a table format
System.out.println("Name\tUSN\tCGPA");
while (resultSet.next()) {
String name = resultSet.getString("name");
String usn = resultSet.getString("usn");
double cgpa = resultSet.getDouble("cgpa");
System.out.println(name + "\t" + usn + "\t" + cgpa);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
OR
import java.sql.*;

public class StudentDatabase {

public static void main(String[] args) {


Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Connect to the database


connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_db",
"root", "password");

// Create a statement
statement = connection.createStatement();

// Execute the query to create table


statement.execute("CREATE TABLE student (name VARCHAR(20), usn VARCHAR(10),
cgpa DOUBLE)");
System.out.println("Table created successfully");

// Insert data into the table


statement.execute("INSERT INTO student (name, usn, cgpa) VALUES ('John Doe',
'1MS17IS001', 8.5)");
statement.execute("INSERT INTO student (name, usn, cgpa) VALUES ('Jane Smith',
'1MS17IS002', 7.5)");
statement.execute("INSERT INTO student (name, usn, cgpa) VALUES ('Bob Johnson',
'1MS17IS003', 9.0)");
System.out.println("Data inserted successfully");

// Execute the query to retrieve data


resultSet = statement.executeQuery("SELECT name, usn, cgpa FROM student");

// Print the results in a table format


System.out.println("Name\tUSN\tCGPA");
while (resultSet.next()) {
String name = resultSet.getString("name");
String usn = resultSet.getString("usn

JDBC EX:
import java.sql.*;

public class connectionEx {


public static void main(String[] args){
final String driver="com.mysql.jdbc.Driver";
final String url="jdbc:mysql://localhost:3306/logindb";
final String user="root";
final String password="";

try{
//Step1: load the driver
Class.forName(driver);

//Step2: Connect to the DB in the driver


Connection conn=DriverManager.getConnection
(url, user, password);

if(conn==null){
System.out.println("Error!!");
}
else{
System.out.println("Connected!!!");
}
//Step3: Create a STMT obj for handling query
//Do it using CONN obj
Statement stmt=conn.createStatement();

//Step4: Execute the query using STMT obj


//Store the result in ResultSet or int
//select query return ResultSet otherwise int

//ResultSet rs=stmt.executeUpdate(sql);
/*while(rs.next()){
System.out.println(rs.getString(1)+" "+
rs.getString(2));
}*/

//close the connection


conn.close();
}catch(Exception e){
System.out.println(e);
}

insertQuery
import java.sql.*;

public class insertQuery {


public static void main(String[] args) {
final String url="com.mysql.jdbc.Driver";
final String dbURL="jdbc:mysql://localhost/employeeDB";
final String user="root";
final String password="";
try{
Class.forName(url);

Connection conn=DriverManager.getConnection
(dbURL, user, password);

Statement stmt=conn.createStatement();
String sql="insert into employee values(2,'xyz')";
String sql1="update employee set id=3 where name='xyz'";
String sql2="delete from employee where id=1";
stmt.executeUpdate(sql2);
conn.close();
}catch(Exception e){
System.out.println(e);
}
}

printBooks:
import java.sql.*;
public class printBooks {
public static void main(String[] args) {
final String url="com.mysql.jdbc.Driver";
final String dbURL="jdbc:mysql://localhost/bookDB";
final String user="root";
final String password="";
try{
Class.forName(url);

Connection conn=DriverManager.getConnection
(dbURL, user, password);

Statement stmt=conn.createStatement();

String sql="insert into book values(2,'c',200)";


String sql1="select title from book where id=1";

String sql2="update book set id=3 where price=200";

int res=stmt.executeUpdate(sql);
int res1=stmt.executeUpdate(sql2);
if(res<0 || res1<0) {
System.out.println("Insertion cannot be done");
System.exit(0);
}

ResultSet rs=stmt.executeQuery(sql1);

while(rs.next()) {
System.out.println(rs.getString(1));
}

}catch(Exception e) {
System.out.println(e);
}
}
}

SELECT EX:
import java.sql.*;
class selectEx{
public static void main(String args[]){
final String url="jdbc:mysql://localhost:3306/logindb";
final String user="root";
final String pwd="";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.
getConnection(url,user,pwd);
Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from person");


while(rs.next())
System.out.println(rs.getString(1)+"
"+rs.getString(2));

con.close();
}catch(Exception e){ System.out.println(e);
}
}
}

Open with

selectQuery:

import java.sql.*;

public class selectQuery {


public static void main(String[] args) {
final String url="com.mysql.jdbc.Driver";
final String dbURL="jdbc:mysql://localhost/employeeDB";
final String user="root";
final String password="";
try{
Class.forName(url);

Connection conn=DriverManager.getConnection
(dbURL, user, password);

Statement stmt=conn.createStatement();
String sql="select * from employee";

ResultSet rs=stmt.executeQuery(sql);

while(rs.next()){
System.out.println(rs.getInt(1)+" "
+rs.getString(2));
}
conn.close();
}catch(Exception e){
System.out.println(e);
}

The Lifecycle of a JSP Page


The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator.
The JSP translator is a part of the web server which is responsible for translating the JSP page into
Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet are performed on JSP later like initialization,
committing response to the browser and destroy.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it by .jsp extension.
We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps
directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP
page. We will learn scriptlet tag later.

1. <html>  
2. <body>  
3. <% out.print(2*5); %>  
4. </body>  
5. </html>  

It will print 10 on the browser.

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple JSP?


No, there is no need of directory structure if you don't have class files or TLD files. For example,
put JSP files in a folder directly and deploy that folder. It will be running fine. However, if you are
using Bean class, Servlet or TLD file, the directory structure is required.

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-
INF folder or in any directory.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are three types
of scripting elements:

o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <%  java source code %>  
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.

Play Video

1. <html>  
2. <body>  
3. <% out.print("welcome to jsp"); %>  
4. </body>  
5. </html>  

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp. The index.html file gets the
username from the user and the welcome.jsp file prints the username with the welcome message.

File: index.html

1. <html>  
2. <body>  
3. <form action="welcome.jsp">  
4. <input type="text" name="uname">  
5. <input type="submit" value="go"><br/>  
6. </form>  
7. </body>  
8. </html>  

File: welcome.jsp

1. <html>  
2. <body>  
3. <%  
4. String name=request.getParameter("uname");  
5. out.print("welcome "+name);  
6. %>  
7. </form>  
8. </body>  
9. </html>  

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So you
need not write out.print() to write data. It is mainly used to print the values of variable or method.

Syntax of JSP expression tag


1. <%=  statement %>  
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>  
2. <body>  
3. <%= "welcome to jsp" %>  
4. </body>  
5. </html>  
Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar class. The getTime() is
an instance method of Calendar class, so we have called it after getting the instance of Calendar
class by the getInstance() method.
index.jsp

1. <html>  
2. <body>  
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>  
4. </body>  
5. </html>  
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The index.html file gets the
username and sends the request to the welcome.jsp file, which displays the username.

File: index.jsp

1. <html>  
2. <body>  
3. <form action="welcome.jsp">  
4. <input type="text" name="uname"><br/>  
5. <input type="submit" value="go">  
6. </form>  
7. </body>  
8. </html>  

File: welcome.jsp

1. <html>  
2. <body>  
3. <%= "Welcome "+request.getParameter("uname") %>  
4. </body>  
5. </html>  

JSP Declaration Tag


1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method

The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.

So it doesn't get memory at each request.


Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%!  field or method declaration %>  
Difference between JSP Scriptlet tag and Declaration tag
Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare The jsp declaration tag can declare variables as well as methods.
variables not methods.

The declaration of scriptlet tag is The declaration of jsp declaration tag is placed outside the
placed inside the _jspService()
_jspService() method.
method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.

index.jsp
1. <html>  
2. <body>  
3. <%! int data=50; %>  
4. <%= "Value of the variable is:"+data %>  
5. </body>  
6. </html>  

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of given
number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag
to call the declared method.

index.jsp
1. <html>  
2. <body>  
3. <%!   
4. int cube(int n){  
5. return n*n*n*;  
6. }  
7. %>  
8. <%= "Cube of 3 is:"+cube(3) %>  
9. </body>  
10. </html>  

Registration Form Example Using JavaFX


import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class App extends Application {


private StackPane root = new StackPane();
private Stage stage;

@Override
public void init() {
Button button = new Button("OPEN");
VBox vBox = new VBox();

vBox.setSpacing(8);
vBox.setPadding(new Insets(10,10,10,10));
vBox.getChildren().addAll(
new Label("Your Name"),
new TextField(),
new Label("Your Username"),
new TextField(),
new Label("Your Password"),
new PasswordField(),
new Label("Confirm Password"),
new PasswordField(),
new Button("REGISTER"));
root.getChildren().addAll(vBox);

button.setOnAction(actionEvent-> {
if(stage!=null){
stage.requestFocus();
return;
}
stage = new Stage();
StackPane stackPane = new StackPane();
stage.setScene(new Scene(stackPane, 200,200));
stage.show();
});
}

@Override
public void start(Stage primaryStage) {
Scene scene = new Scene(root,400,600);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setTitle("Registration Example JavaFX");
primaryStage.setAlwaysOnTop(true);
}

public static void main(String[] args) {


launch(args);
}
}

Q. write a java program to develop the application to display


the following attribute using servlets display max age of the
cookie, display the cookie name,get the cookie value , setting
the name of the cookie , setting the value to the cookie and
displaying the same
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Create a new cookie


Cookie cookie = new Cookie("testCookie", "Hello World");
// Set the max age of the cookie
cookie.setMaxAge(60*60*24); // 1 day
// Add the cookie to the response
response.addCookie(cookie);

// Get the cookie name


String cookieName = cookie.getName();
// Get the cookie value
String cookieValue = cookie.getValue();

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Cookie Name: " + cookieName + "</h3>");
out.println("<h3>Cookie Value: " + cookieValue + "</h3>");
}
}

OR

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Create a new cookie


Cookie cookie = new Cookie("testCookie", "Hello World");
// Set the max age of the cookie
cookie.setMaxAge(60*60*24); // 1 day
// Add the cookie to the response
response.addCookie(cookie);

// Get the cookie name


String cookieName = cookie.getName();
// Get the cookie value
String cookieValue = cookie.getValue();
// Get the max age of the cookie
int maxAge = cookie.getMaxAge();

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Cookie Name: " + cookieName + "</h3>");
out.println("<h3>Cookie Value: " + cookieValue + "</h3>");
out.println("<h3>Max Age: " + maxAge + "</h3>");

Q. Write a java program to develop web applications to


display the students list who is having scored less than
20 marks in cie using servlets
import java.io.*;
import java.util.ArrayList;
import javax.servlet.*;
import javax.servlet.http.*;

public class StudentServlet extends HttpServlet {


private ArrayList<Student> studentList;

public void init() {


// Initialize the student list
studentList = new ArrayList<>();
studentList.add(new Student("John Doe", "1MS17IS001", 15));
studentList.add(new Student("Jane Smith", "1MS17IS002", 18));
studentList.add(new Student("Bob Johnson", "1MS17IS003", 22));
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<h2>Students with Less than 20 marks in CIE</h2>");


out.println("<table border='1'>");
out.println("<tr><th>Name</th><th>USN</th><th>CIE Marks</th></tr>");

// Iterate through the student list and display only those with less than 20 marks in CIE
for (Student student : studentList) {
if (student.getCieMarks() < 20) {
out.println("<tr>");
out.println("<td>" + student.getName() + "</td>");
out.println("<td>" + student.getUsn() + "</td>");
out.println("<td>" + student.getCieMarks() + "</td>");
out.println("</tr>");
}
}
}
a Java program that demonstrates how to use JavaServer Pages (JSP) to display a list of students
who scored less than 20 marks in CIE:

<%@ page import="java.util.ArrayList" %>


<%@ page import="com.example.Student" %>

<html>
<head>
<title>Students with Less than 20 marks in CIE</title>
</head>
<body>
<h2>Students with Less than 20 marks in CIE</h2>
<table border="1">
<tr>
<th>Name</th>
<th>USN</th>
<th>CIE Marks</th>
</tr>
<%
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student("John Doe", "1MS17IS001", 15));
studentList.add(new Student("Jane Smith", "1MS17IS002", 18));
studentList.add(new Student("Bob Johnson", "1MS17IS003", 22));

// Iterate through the student list and display only those with less than 20 marks in
CIE
for (Student student : studentList) {
if (student.getCieMarks() < 20) {
%>
<tr>
<td><%= student.getName() %></td>
<td><%= student.getUsn() %></td>
<td><%= student.getCieMarks() %></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>

In this example, a JSP page is used to display a table of students with less than 20 marks in CIE. The student data
is stored in an ArrayList of Student objects, which is initialized in the JSP page using scriptlet tags. The JSP page
uses a for loop to iterate through the student list, displaying only those students with less than 20 marks in CIE.

Note that JSP is a technology that is depreciated, JavaServer Faces (JSF) is recommended for building web
applications in Java.

Q
Here's an example of a Java program that demonstrates how to use a generic functional interface
and lambda expressions to find the reverse of a given string and the factorial of a given number:

import java.util.function.Function;

public class ReverseFactorial {

public static void main(String[] args) {

// Function to find the reverse of a string

Function<String, String> reverseString = (str) -> {

StringBuilder sb = new StringBuilder(str);

return sb.reverse().toString();
};

// Function to find the factorial of a number

Function<Integer, Integer> factorial = (num) -> {

int result = 1;

for (int i = 1; i <= num; i++) {

result *= i;

return result;

};

String inputString = "Hello World";

System.out.println("Original String: " + inputString);

System.out.println("Reversed String: " + reverseString.apply(inputString));

int inputNumber = 5;

System.out.println("Input Number: " + inputNumber);

System.out.println("Factorial: " + factorial.apply(inputNumber));

Q.

Here's an example of a Java program that demonstrates


how to use a CyclicBarrier to create three tasks (T1, T2, T3)
that read and sort n/3 integers in sequence of occurrences
from a file "integers.txt", and then sort and write the entire
list of sorted integers into another file "sortedIntegers.txt":
import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.util.ArrayList;
import java.util.Collections;

import java.util.List;

import java.util.Random;

import java.util.concurrent.BrokenBarrierException;

import java.util.concurrent.CyclicBarrier;

public class SortingTasks {

public static void main(String[] args) throws Exception {

// Create a file named "integers.txt" and insert n random integers into it

int n = 100;

File file = new File("integers.txt");

BufferedWriter writer = new BufferedWriter(new FileWriter(file));

Random random = new Random();

for (int i = 0; i < n; i++) {

writer.write(random.nextInt(100) + " ");

writer.close();

// Create a list to store the sorted integers

List<Integer> sortedIntegers = Collections.synchronizedList(new ArrayList<>());

// Create a CyclicBarrier with a party count of 3 and a barrier action

CyclicBarrier barrier = new CyclicBarrier(3, () -> {

// Sort and write the entire list of sorted integers into another file named "sortedIntegers.txt"

Collections.sort(sortedIntegers);

try {

BufferedWriter sortedWriter = new BufferedWriter(new FileWriter(new File("sortedIntegers.txt")));

for (Integer num : sortedIntegers) {

sortedWriter.write(num + " ");

sortedWriter.close();

} catch (Exception e) {

e.printStackTrace();
}

});

// Create three tasks T1, T2, and T3

BufferedReader reader = new BufferedReader(new FileReader(file));

for (int i = 0; i < 3; i++)

You might also like