Practical 7 Gtu
Practical 7 Gtu
Index
(Progressive Assessment Sheet)
Total
Object Oriented Programming-I (3140705)
Experiment No: 7
Date: 27/03/2024
CO mapped: CO-4
Objectives:
To showcase proficiency in reading data from and writing data to files in various formats
using programming languages, demonstrating the ability to implement reliable and
efficient file I/O operations, which are essential for tasks such as data storage, retrieval,
and processing in software applications.
Background:
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operations fast. The java.io package contains all the classes
required for input and output operations.
Practical questions:
1. Write a program that removes all the occurrences of a specified string from a text file. For
example, invoking java Practical7_1 John filename removes the string John from the
specified file. Your program should read the string as an input.
Code: import java.io.*;
if (args.length < 2) {
System.out.println("Usage: java RemoveStringFromFile string_to_remove
filename");
return;
}
try (
}
}
OUTPUT:
2. Write a program that will count the number of characters, words, and lines in a file. Words
are separated by whitespace characters. The file name should be passed as a command-line
argument.
Code: import java.io.*;
OUTPUT:
Conclusion:
The experiment successfully demonstrated proficiency in reading data from and writing
data to files in a text format using Java. The provided code achieved the following objectives:
These functionalities showcase essential file I/O operations crucial for data storage, retrieval, and
processing in software applications.
Object Oriented Programming-I (3140705)
Quiz:
Answer: File I/O refers to the process of reading data from and writing data to files on a
storage device. It's fundamental in software development for several reasons:
• Data Persistence: Programs can store data beyond their execution, enabling
features like user preferences, application state, and historical records.
• Data Sharing: Data can be exchanged between programs or transferred across
systems by storing it in files.
• Data Processing: Large datasets can be efficiently processed by reading them
from files, manipulating the information, and potentially writing the results back to
a file.
2. What are the common modes for opening files, and how do they differ (e.g., read, write,
append)?
Answer: There are primary modes for opening files, each controlling how data can be
accessed:
• Read (r): Opens a file for reading existing content. Attempts to write to the file
will result in an error.
• Write (w): Creates a new file or overwrites an existing one. Any existing data will
be lost.
• Append (a): Opens a file for writing data at the end of the existing content. If the
file doesn't exist, it will be created.
3. Describe the concept of file streams and how they are used in file I/O operations.
Answer: File streams represent a flow of data between a program and a file. They act as
an abstraction layer, simplifying file I/O operations. There are two main types of streams:
• Input Streams: Used for reading data from a file. The experiment utilizes
FileReader and BufferedReader for this purpose.
• Output Streams: Used for writing data to a file. The experiment uses FileWriter
and BufferedWriter as examples.
Answer: The provided Java code demonstrates the following I/O stream classes:
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Object Oriented Programming-I (3140705)
Experiment No: 8
Date: 03/04/2024
CO mapped: CO-5
Objectives:
Background:
Every user interface considers the following three main aspects –
UI elements − These are the core visual elements that the user eventually sees and interacts with.
JavaFX provides a huge list of widely used and common elements varying from basic to complex,
which we will cover in this practical.
Layouts − They define how UI elements should be organized on the screen and provide a final
look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout
chapter.
Behavior − These are events that occur when the user interacts with UI elements.
JavaFX provides several classes in the package javafx.scene.control. To create various GUI
components (controls), JavaFX supports several controls such as date picker, button text field, etc.
Each control is represented by a class; you can create a control by instantiating its respective
class.
btn.setOnAction(new ClickHandler(label));
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
Practical questions:
1. Write a program that displays five texts vertically, as shown in Figure. Set a random color
and opacity for each text and set the font of each text to Times Roman, bold, italic, and 22
pixels.
Object Oriented Programming-I (3140705)
Code:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.text.*;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
2. Write a program that uses a bar chart to display the percentages of the overall grade
represented by projects, quizzes, midterm exams, and the final exam, as shown in Figure
Object Oriented Programming-I (3140705)
b. Suppose that projects take 20 percent and are displayed in red, quizzes take 10 percent
and are displayed in blue, midterm exams take 30 percent and are displayed in green, and
the final exam takes 40 percent and is displayed in orange. Use the Rectangle class to
display the bars. Interested readers may explore the JavaFXBarChart class for further
study.
Code:
\
package org.example.practical8_1;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.layout.StackPane;
import javafx.geometry.Pos;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.geometry.Insets;
3. Write a program that displays a rectanguloid, as shown in Figure a. The cube should grow
and shrink as the window grows or shrinks.
Object Oriented Programming-I (3140705)
Code:
package org.example.practical8_1;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import java.util.ArrayList;
@Override
public void start(Stage primaryStage) {
pane.getChildren().addAll(shapes);
Scene scene = new Scene(pane, 400, 400);
scene.xProperty().add(scene.yProperty());
primaryStage.setTitle("Welcome to Java");
primaryStage.setScene(scene);
primaryStage.show();
}
Object Oriented Programming-I (3140705)
}
OUTPUT:
Conclusion:
This hands-on approach provided a solid foundation for crafting user-friendly, responsive, and
feature-rich GUIs for Java applications. We explored essential concepts like UI elements, layouts,
and event handling, laying the groundwork for further exploration of advanced JavaFX controls
and functionalities.
Quiz:
1. Explain the evolution of Java GUI technologies since awt,swing and JavaFX.
Answer:
• AWT (Abstract Window Toolkit): The original Java GUI toolkit, introduced in 1995.
It provided basic UI components like buttons, labels, and text fields. However, AWT
relied heavily on the native OS look and feel, leading to inconsistencies across platforms.
• Swing (Java Foundation Classes): Released in 1998, Swing built upon AWT, offering
richer UI components written entirely in Java. This ensured a more consistent look and
feel across different operating systems. Swing remains a powerful and widely used toolkit.
Object Oriented Programming-I (3140705)
• JavaFX: Introduced in 2008 by Sun Microsystems (now Oracle), JavaFX aimed to be a
modern replacement for Swing. It utilizes hardware acceleration for smoother animations
and effects. JavaFX also embraces modern UI design principles and integrates well with
multimedia features.
2. What is the purpose of a TextField control, and how can it be used to collect user input?
Answer: A TextField control is a single-line input field that allows users to enter text data.
It's ideal for collecting user input such as names, email addresses, or short descriptions.
4. What are the primary layout controls in JavaFX, and how do they impact the arrangement
of UI components?
Answer: JavaFX offers several layout controls to arrange UI components within a scene:
These layout controls impact the arrangement by defining the position and sizing behavior
of child elements within them. For instance, an HBox ensures all child elements share the
same height and are placed side-by-side.
Object Oriented Programming-I (3140705)
Answer: Cascading Style Sheets (CSS) is used to define the visual appearance of JavaFX
UI controls. You can separate the styling information from the Java code, promoting better
code organization and maintainability.
• Applying CSS:
1. Create a CSS file with styles for various control classes (e.g., .button,
.text-field).
2. In your Java code, set the style property of the control object with the
desired CSS class name. This links the control to the corresponding styles
defined in the CSS file.
By using CSS, you can control properties like fonts, colors, backgrounds, borders,
padding, and margins, allowing for customization of the look and feel of your JavaFX
application.
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Object Oriented Programming-I (3140705)
Experiment No: 9
Date: 24/04/2024
CO mapped: CO-5
Objectives:
Background:
Code:
\
package org.example.practical9;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
Object Oriented Programming-I (3140705)
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.CheckBox;
import javafx.geometry.Pos;
import javafx.geometry.Insets;
import java.util.List;
import java.util.ArrayList;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
@Override
public void start(Stage primaryStage) {
text.setFont(Font.font(50));
StackPane paneForText = new StackPane(text);
paneForText.setPadding(new Insets(20, 5, 20, 5));
OUTPUT-1:
OUTPUT-2:
2. Write a program that displays a moving text, as shown in Figure. The text moves from left
to right circularly. When it disappears in the right, it reappears from the left. The text
freezes when the mouse is pressed and moves again when the button is released.
Code:
package org.example.practical9;
import javafx.application.Application;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.scene.Scene;
Object Oriented Programming-I (3140705)
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;
pane.setOnMousePressed(e -> {
pt.pause();
});
pane.setOnMouseReleased(e -> {
pt.play();
});
OUTPUT-1:
Object Oriented Programming-I (3140705)
OUTPUT-2:
■ Get the number of iamges and image’s file-name prefix from the user. For example, if the
user enters n for the number of images and L for the image prefix, then the files are L1.gif,
L2.gif, and so on, to Ln.gif. Assume that the images are stored in the image directory, a
subdirectory of the program’s class directory. The animation displays the images one after the
other.
■ Allow the user to specify an audio file URL. The audio is played while the animation runs.
Code:
package org.example.practical9;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.control.Button;
Object Oriented Programming-I (3140705)
import javafx.scene.control.TextField;
import javafx.scene.control.Label;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
import javafx.util.Duration;
@Override
public void start(Stage primaryStage) {
final int COLUMN_COUNT = 27;
tfSpeed.setPrefColumnCount(COLUMN_COUNT);
tfPrefix.setPrefColumnCount(COLUMN_COUNT);
tfNumberOfImages.setPrefColumnCount(COLUMN_COUNT);
tfURL.setPrefColumnCount(COLUMN_COUNT);
btStart.setOnAction(e -> {
if (tfURL.getText().length() > 0) {
Object Oriented Programming-I (3140705)
MediaPlayer mediaPlayer = new MediaPlayer(
new Media(tfURL.getText()));
mediaPlayer.play();
}
if (tfSpeed.getText().length() > 0)
animation.setRate(Integer.parseInt(tfSpeed.getText()));
animation.play();
});
OUTPUT:
Conclusion:
Quiz:
1. How does event handling work in Java, and what is the event-driven programming model?
• Events: These are signals that something has happened within the program or the
user's environment (e.g., button click, key press, window resize).
• Event Sources: Objects that generate events (e.g., buttons, text fields, windows).
• Event Listeners: Objects that wait for and handle specific events from event
sources.
• Event Handlers: Methods within listeners that define the actions to be taken when
an event occurs.
2. What is the role of the java.awt.event and javafx.event packages in Java event handling?
Answer:
• java.awt.event: This package provides interfaces and classes for handling events in the
Abstract Window Toolkit (AWT) components like buttons, text fields, and windows. It's
used for traditional desktop applications.
• javafx.event: This package provides interfaces and classes for handling events in
JavaFX applications. It offers a more modern and declarative approach to event handling
compared to AWT.
Answer: These are specific event types within the Java event handling system:
4. What are the primary libraries or frameworks for creating animations in Java, and which
one do you prefer?
Answer: There are several options for animation in Java, but here are two popular ones:
• JavaFX: (Preferred) Built-in with Java, JavaFX offers a rich set of animation
classes and APIs for creating smooth and efficient animations. It integrates well
with JavaFX applications.
• Swing: A part of the Java AWT library, Swing provides some animation
capabilities, but it can be less versatile and more complex compared to JavaFX.
Object Oriented Programming-I (3140705)
5. How to set the cycle count of an animation to infinite?
Answer: There are two ways to achieve an infinite cycle count depending on the
animation library you're using:
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Object Oriented Programming-I (3140705)
Experiment No: 10
Date: 01/05/2024
CO mapped: CO-4
Objectives:
b) Learning recursion and generics is crucial for building efficient algorithms and writing
more versatile and type-safe code in software development. Achieving this objective will
help you become a more proficient and well-rounded programmer.
Background:
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called the recursive method.
Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the
code stable by detecting the bugs at compile time. Before generics, we can store any type of
object in the collection, i.e., non-generic. Now generics force the java programmer to store a
specific type of object.
Practical questions:
1. Write a recursive method that converts a decimal number into a binary number as a string.
The method header is: public static String dec2Bin(int value)
• Write a test program that prompts the user to enter a decimal number and displays its
binary equivalent.
Code: import java.util.Scanner;
public class Practical10_1{
2. Write the following method that returns a new ArrayList. The new list contains the non-
duplicate elements from the original list.
if (!isDuplicate) {
uniqueList.add(element);
}
}
return uniqueList;
}
}
}
OUTPUT:
Conclusion:
By working through these practical exercises, we gained valuable insights into the power
and versatility of recursion and generics. These concepts are fundamental for building efficient
algorithms, writing clean and reusable code, and becoming a more proficient programmer.
Quiz:
1. What is recursion in Java, and how does it differ from iteration in solving problems?
Iteration, on the other hand, uses loops (like for or while) to solve problems by repeatedly
executing a block of code until a certain condition is met.
Object Oriented Programming-I (3140705)
The choice between recursion and iteration depends on the problem. Recursion can be
more elegant for problems that can be naturally divided into subproblems of the same
type. Iteration is often more efficient for simple repetitive tasks.
Advantages
• Reads like natural language for problems that have a recursive structure.
• Can lead to more concise and elegant code.
Disadvantages
• Can be less efficient than iteration for simple problems due to function call
overhead.
• Can be difficult to debug due to the nested nature of calls.
• Can lead to stack overflow errors if not implemented carefully.
3. What are generics in Java, and why are they used for creating parameterized types?
Generics allow you to write code that can work with different data types without
compromising type safety. They are implemented using parameterized types, which are
placeholders for specific data types that are specified when the generic code is used.
For example, a generic ArrayList can store any type of object, but once you create a
specific ArrayList of integers, it can only hold integers.
A generic class is a class that can be parameterized with one or more types. These
types are specified using angle brackets ( <>) and act as placeholders for the actual data
types that will be used when the class is instantiated.
Object Oriented Programming-I (3140705)
Restrictions of generic programming:
• Generics cannot be used for primitive data types like int or float.
• You cannot create arrays of generic types.
5. Can you provide an example of a generic class in Java, such as a generic ArrayList?
import java.util.ArrayList;
public GenericExample() {
myList = new ArrayList<>();
}
In this example, GenericExample is a generic class that can hold elements of any
type. The type parameter <T> allows us to specify the type of elements that this class will
work with. Inside the class, we use an ArrayList<T> to store elements of type T. The
addItem method adds an element to the list, and the getList method returns the list.
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty: