OOPnotes
OOPnotes
// not accessible outside of its own package, with exception from subclasses of
its class (childs)
protected
Static (Class) fields belongs to the class, not to any object of the class;
Static fields can be considered as fields that belong to all the objects of the class (black
board)!
Instance fields belongs to the object of the class;
Instance fields are hot shared between the objects of the class!
Static (Class) methods are those methods that do not have an implicit parameter; i.e., they
do not operate on objects;
call a static method by its Object e.g Math.sqrt(4.5); or MyClass.MY_INT
Too many static methods are a sign of too little OOP!
Rules
// a static value that does not change and isn't bound to object init.
public static final int MY_INT = 0;
// Can only be assigned once, and can not be changed once assigned.
public final MY_INT = 0;
// Final method means that the method can not be overridden by subclasses.
public final void myFunction() {
// TODO: Add logic
}
Data Types
Type Casting
1. If byte, short, and int are used in a mathematical expression, Java always converts the
result into an int.
2. If a single long is used in the expression, the whole expression is converted to long.
3. If a float operand is used in an expression, the whole expression is converted to float.
4. If any operand is double, the result is promoted to double.
5. Boolean values cannot be converted to another type.
6. Conversion from float to int causes truncation of the fractional part which represents
the loss of precision. Java does not allow this.
7. Conversion from double to float causes rounding of digits that may cause some of the
value’s precision to be lost.
8. Conversion from long to int is also not possible. It causes dropping of the excess higher
order bits.
Widening Casting
Meaning: converting a smaller type to a larger type size. (automatically)
byte -> short -> char -> int -> long -> float -> double
int myInt = 9;
double myDouble = myInt; // Automatically casting int to double.
System.out.println(myInt); // 9
System.out.println(myDouble); // 9.0
Narrowing Casting
Meaning: converting a larger type to a smaller size type (manually)
double -> float -> long -> int -> char -> short -> byte
System.out.println(myDouble); // 9.78
System.out.println(myInt); // 9
// Output: 1
int intNum = Integer.parseInt("1");
// Output: 2.0
double doubNum = Double.parseDouble("2.0");
// Output: 2.0
float flNum = Float.parseFloat("2");
String IntToStrNum = intNum.toString();
String DoubToStrNum = doubNum.toString();
String FlToStrNum = flNum.toString();
Objects
// Returns a boolean that indiciates whether some other object is "equal to"
this one.
name.equals(Object obj);
Comparable
utilizes compareTo() method from the Comparable interface.
---------------------------------------
Main.java
---------------------------------------
ArrayList<Movie> molistvies = new ArrayList<Movie>();
list.add(new Movie("Force Awakens", 8.3, 2015));
list.add(new Movie("Star Wars", 8.7, 1977));
list.add(new Movie("Empire Strikes Back", 8.8, 1980));
list.add(new Movie("Return of the Jedi", 8.4, 1983));
Comparator
External to the element type we are comparing.
Seperate class that implements Comparator to compare by different members.
Collections.sort() also accepts Comparator as parameter.
Opens compare method
3 things to do:
---------------------------------------
RatingComparer.java
---------------------------------------
class RatingComparer implements Comparator<Movie> {
public int compare(Movie m1, Movie m2) {
if (m1.getRating() < m2.getRating()) return -1;
if (m1.getRating > m2.getRating()) return 1;
return 0;
}
}
---------------------------------------
NameComparer.java
---------------------------------------
class NameComparer implements Comparator<Movie> {
public int compare(Movie m1, Movie m2) {
return m1.getName.compareTo(m2.getName());
}
}
---------------------------------------
Main.java
---------------------------------------
ArrayList<Movie> list = new ArrayList<Movie>();
list.add(new Movie("Force Awakens", 8.3, 2015));
list.add(new Movie("Star Wars", 8.7, 1977));
list.add(new Movie("Empire Strikes Back", 8.8, 1980));
list.add(new Movie("Return of the Jedi", 8.4, 1983));
Interfaces
Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move() . So it specifies a set of
methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
Comparator and Comparable are two interface examples.
We can’t create instance (interface can’t be instantiated) of interface but we can make
reference of it that refers to the Object of its implementing class.
An interface can extends another interface or interfaces
All the methods are public and abstract. And all the fields are public, static, and final.
It is used to achieve multiple inheritance.
It is used to achieve loose coupling.
interface Vehicle {
// public, static and final
final String brand = "Audi";
@Override
public void changeGear(int newGear) {
gear = newGear;
}
@Override
public void speedUp(int inc) {
speed += inc;
}
@Override
public void applyBrakes(int dec) {
speed = speed - dec;
}
}
---------------------------------------
Bike.java
---------------------------------------
class Bike implements Vehicle {
// fields here
@Override
public void changeGear(int newGear) {
gear = newGear;
}
@Override
public void speedUp(int inc) {
speed += inc;
}
@Override
public void applyBrakes(int dec) {
speed = speed - dec;
}
}
---------------------------------------
Main.java
---------------------------------------
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
// Bicycle speed 2 and gear 2
New as of JDK 8+
Default Keyword
interface In1
{
final int a = 10;
default void display()
{
System.out.println("hello");
}
}
// Output: hello
Static Methods
You can now define static methods in interface which can be called independently without
an object.
Note: these methods are not inherited.
interface In1
{
final int a = 10;
static void display()
{
System.out.println("hello");
}
}
// Output: hello
Interface Casting
You can type cast from class to interface.
You can not cast from unrelated classes.
If you cast from Interface to Class than you need a cast to convert from an interface type to
a class type.
// Interface: Vehicle
// Classes: Bike and Bicycle
// This is possible
Bike bike = new Bike();
Vehicle x = bike;
// Interface: Vehicle
// Classes: Bike
Vehicle x = bike;
// speed: 3
x.speedUp(2);
Different Castings
When casting number types, you lose information and you tell the compiler that you agree
to the information loss: int x = (int) 2.4;
When casting object types, you take a risk of causing an exception, and you tell the compiler
that you agree to that risk: Bike nb = (Bike)fastest;
Controlling Casting
Use instanceof .
if (x instance of Bike) {
Bike b = (Bike)x;
}
The instanceof operator returns true if the object is an instance of the class. Otherwise, it
returns false.
Polymorphism
The word polymorphism means having many forms.
we can define polymorphism as the ability of a message to be displayed in more than one
form.
Example: A person at the same time can have different characteristic. Like a man at the
same time is a father, a husband, an employee. So the same person posses different
behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented
Programming. Polymorphism allows us to perform a single action in different ways.
polymorphism allows you to define one interface and have multiple implementations.
The word “poly” means many and “morphs” means forms, So it means many forms.
Method Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by
change in number of arguments or/and change in type of arguments.
class MultiplyFun {
// method with 2 parameters
static int multiply(int a, int b) {
// a = 2, b = 4 Output = 8
return a*b;
}
Runtime Polymorphism
It is also known as Dynamic Method Dispatch
It is a process in which a function call to the overridden method is resolved at Runtime.
This type of polymorphism is achieved by Method Overriding.
Late Binding
Method overriding, on the other hand, occurs when a derived class has a definition for one of
the member functions of the base class. That base function is said to be overridden.
class Parent {
void talk() {
System.out.println("parent");
}
}
a = new Daughter();
a.talk(); // Output: daughter
a = new Son();
a.talk(); // output: son
Measurable Interface
count++;
}
}
---------------------------------------
Main.java
---------------------------------------
DataSet bankData = new DataSet();
bankData.add(new BankAccount(0));
11: bankData.add(new BankAccount(10000));
12: bankData.add(new BankAccount(2000));
UML
You can convert from a class type to an interface type, provided the class implements the
interface
BankAccount account = new BankAccount(10000);
Measurable x = account; // OK
Coin dime = new Coin(0.1, "dime");
Measurable x = dime; // Also OK
Cannot convert between unrelated types
Measurable x = new Rectangle(5, 10, 20, 30); // ERROR
Because Rectangle doesn't implement Measurable
Casts
You can’t force classes that aren’t under your control to implement the interface (for
example class Rectangle);
You can measure an object in only one way.
Solution: let another object to carry out the measurements.
count++;
}
UML
Inside a method
class OuterClassName {
method signature {
...
class InnerClassName {
// methods
// fields
}
...
}
...
}
class OuterClassName {
// methods
// fields
accessSpecifier class InnerClassName {
// methods
// fields
}
...
}
class EnclosingClass {
...
static class StaticNestedClass {
...
}
}
A static nested class cannot refer directly to instance variables or methods defined in its
enclosing class. It can use them only through an object reference.
A static nested class can be independently instantiated without having creating an object of
the outer class.
class EnclosingClass {
...
class NonStaticNestedClass {
...
}
}
A inner class cannot be independently instantiated without having creating an object of the
outer class.
Generics
Generics are a facility of generic programming that were added to the Java programming
language in 2004 within version J2SE 5.0.
Generics were designed to extend Java's type system to allow "a type or method to operate on
objects of various types while providing compile-time type safety”.
What we get is “compile-time type safety”; i.e. the errors appear during program
development, not when they are used.
Generic Classes
A class is generic is generic if it declares one or more type variables. These type variables
are known as the type parameters of the class.
public T get() {
return this.t;
}
Generic Methods
A method is generic if it declares one or more type variables. These type variables are
known as the formal type parameters of the method.
Generic Interface
An interface is generic if it declares one or more type variables. These type variables are
known as its formal type parameters.
public interface MyInterface<T> {
void myMethod(T t);
}
interface implementation:
Pass the reference of the listener to the Timer constructor and then start:
Timer t calss the actionPerformed method of the listener object every interval
milliseconds!
if (count == 0) {
// output liftoff
}
count--;
}
}
OOP
To try to deal with the complexity of programs
To apply principles of abstraction to simplify the tasks of writing, testing, maintaining and
understanding complex programs
to reuse classes developed for one application in other applications instead of writing
new programs from scratch ("Why reinvent the wheel?")
Inheritance is a major technique for realizing these objectives
Inheritance
Inheritance is a OOP principle. It allows us to extend existing classes by adding
methods and fields.
The more general class is called a super class;
The more specialized class that inherits from the superclass is called subclass;
The subclass inherits behavior and the state of the super class;
An interface is not a class. It has not state and no behavior.
Inheritance occurs between classes not objects;
Single inheritance is when children inherit characteristics from only oneparent. Java
employs single inheritance!
Multiple inheritance is when children inherit characteristics from more than one
parent.
Assume that we have a class CheckingAccount with its own method deposit . deposit
overrides the method deposit from BankAccount .
A subclass inherits a method from a superclass, if it does not have a method that
overrides the superclass method.
The class SavingsAccount inherits the methods getBalance and deposit from
BankAccount .
A** subclass can have new methods of which the names or signatures differ those from the
superclass. These methods can be applied only of the objects of the subclass.**
The class SavingsAccount has a new method addInterest .
You can define new fields. In the class SavingsAccount the field interestRate is new.
If a new field balance is defined in CheckingAccount ,then an object of this class will have
two fields with the same name. The newly defined field shadows the field in herited from
the superclass.
Constructors in a subclass
The subclass constructor can call a superclass constructor using the keyword super. The call
has to be in the first line.
If the subclass constructor doesn’t call the super-class constructor, the default constructor
of the super-class is called implicitly.
Note that superclass references don't know the full story: anAccount.addInterest(); //
ERROR
Abstract Classes
An abstract class is a placeholder in a class hierarchy that represents a generic concept;
An abstract class cannot be instantiated;
We use the modifier abstract on the class header to declare a class as abstract;
An abstract class often contains abstract methods (like an interface does), though it doesn’t
have to;
The subclass of an abstract class must override the abstract methods of the parent, or it too
will be considered abstract;
An abstract method cannot be defined as final (because it must be overridden) or static
(because it has no definition yet)
The use of abstract classes is a design decision; it helps us establish common elements in a
class that is to general to instantiate
Usually concrete classes extend abstract ones, but the opposite is also possible.
Equals
public boolean equals(Obj obj) {
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
return true;
}
Clone
WARNING:
Shallow Copy
Swing
AWT (Abstract Windows Toolkit)
JavaFX
Swing
Show an empty Frame
Drawing Shapes
// draw a rectange
Rectangle box = new Rectangle(5, 10, 20, 30);
g2.draw(box);
g2.draw(box);
}
}
Point2D.Double(double x, double y)
Class Line2D.Double with constructors:
Class Color
By default, all shapes are drawn in black
To change the color, apply the method setColor on g2 parameter with factual parameter
an object of the class Color ;
Color(float red, float green, float blue) where red is the intensity of the red
color, green is the intensity of the green color, and blue is the intensity of the blue
color. red, green,and blue are float in the range [0.0, 1.0] .
There are predefined colors: Color.black , Color.green , etc.
Example: g2.setColor(Color.red);
BasicStroke
To draw thicker lines, supply a different stroke object to Graphics2D g2 parameter:
g2.setStroke(new BasicStroke(4.0F));
Drawing Strings
To draw a string use method drawString of the class Graphics2D:
Class Font
To change the font, apply the method setFont on g2 parameter with factual parameter an
object of the class Font;
where name is the font name such as Serif , SansSerif , Monspaced etc.,style is an
integer( Font.PLAIN , Font.BOLD , Font.ITALIC ), and size is the point size.
Example:
import javax.swing.JFrame;
public class CarViewer {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setTitle("Cars");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-------------
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
-------------
Reading Input
import javax.swing.JOptionPane;
class ReadingInput {
public static void main(String[] args) {
String intput = JOptionPane.showInputDialog("Enter Number: ");
int count = Integer.parseInt(input);
...
System.out.println("Number: " + input);
}
}
Event Handling
Mouse Spy
import java.awt.events.*;
-------
import javax.swing.*;
Mouse frame
public MouseComponent() {
box = new Rectangle(100, 100, 20, 30);
----
main {
MouseComponent mc = new MouseComponent();
JFrame frame = new JFrame();
frame.add(mc);
}
Adapter Class
Component Examples
Layout Management
Three useful layout managers: flow layout , border layout , grid layout .
Generally used as a window for hosting stand-alone applications, like an alert window
or notification window
Contains the title bar
JPanel: works as a container to host components
Flow Layout
Flow layout used by default by JPanel
arranges components from left to right
Starts a new row when no more room is left in current row.
Border Layout
The border layout groups components into 5 areas (CENTER, NORTH, SOUTH, WEST, EAST)
Border layout used by default by JFrame.
Use in panel using panel.add(component, BorderLayout.NORTH)
Grid Layout
The grid layout arranges components in a grid with a fixed number of rows and columns
All components are resized so that they all have the same width and height
Like the border layout, it expands each component to fill the entire allotted area
If not desirable, you need to place each component inside a panel
To create a grid layout, you supply the number of rows and columns in the constructor, then
add the components row by row, left to right
Choices
check box (selectbox)
Radio Buttons
Checkboxes
Comboboxes
If you have a lot of choices and little space you can use a combo box
A combination of a list and a text field
If the combo box is editable you can also type in your own selection
To make a combo box editable, call the setEditable method
setEditablemethodJComboBoxcombo = new JComboBox();
combo.addItem("Serif");
combo.addItem(" SansSerif");
...
String select = (String) combo.getSelectedItem();
Button Groups
Menus
At the top of the frame is a menu bar that contains the top-level menus
Each menu is a collection of menu items and submenus
When the user selects a menu item, the menu item sends an action event. Therefore, you
must add a listener to each menu item
You add action listeners only to menu items, not to menus or the menu bar
When the user clicks on a menu name and a submenu opens, no action event is sent
Timer Events
The Timer class in the javax.swing package generates a sequence of action events, spaced
at even time intervals
This is useful whenever you want to send continuous updates to a component
1. When you use a timer you specify the frequency of the events and an object of a class that
implements the ActionListener interface
2. Place whatever action you want to occur inside the actionPerformed method
3. Start the timer
Mouse Events
Mouse listeners are more complex than action listeners
A mouse listener must implement the MouseListenerinterface, which contains the following
5 methods
It often happens that a particular listener specifies actions only for one or two of the listener
methods. Nevertheless, all 5 methods of the interface must be implemented.
import java.util.Scanner;
Exception Handling
Traditional approach
Exceptions
Definition: An exceptionis an event that occurs during the execution of a program that
disruptsthe normal flow of instructions
void readFile() {
try {
openFile();
determineFileSize();
allocateMemory();
readFileIntoMemory();
closeFile();
}
catch (FileOpenFailed e) {}
catch (FileSizeFailed e) {}
catch (memoryAllFailed e) {}
catch (ReadFailed e) {}
catch (FileCloseFailed e) {}
finally{//always executed}
}
Advantages of exceptions
1. Separating error handling code from “regular" code
2. Propagating errors up the call stack
3. Grouping exceptions
The Java language requires that methods either catch or specify all exceptions that can be thrown
within the scope of that method!!!
Streams
Programs receive information from an external source or send out information to an
external destination. These two processes are realised with streams. A stream is an
abstraction of a sequence of bytes.
To receive information, a program opens a stream on an information source (a file, memory)
and reads the information serially, like this:
No matter where the information is coming from or going to and no matter what type of
data is being read or written, the algorithms for reading and writing data is pretty much
always the same.
java.io contains a set of stream classes that support algorithms for reading and writing.
These are divided into 2 classes based on the datae type: characters and bytes.
Character Streams
Reader and Writer are the abstract superclasses for character streams in java.io .
Reader (Writer) provides the API and partial implementation for readers (writers) -- streams
that read (write) 16-bit characters.
Subclasses of Reader and Writer implement specialized streams and are divided into two
categories: Those that read from or write to data sinks and those that perform some sort of
processing.
FileWriter
Constructors
Methods
Example FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";
System.out.println("Writing successful");
//close the file
fw.close();
}
}
FileReader
It defines the following basic operations of reading characters from any medium such as
memory or the filesystem:
You use a FileReader when we want to read text from a file using the system's default
character set.
Constructors
-----------
Main.java
-----------
String expectedText = "Hello, World!";
File file = new File(FILE_PATH);
try (FileReader fileReader = new FileReader(file)) {
String content = FileReaderExample.readAllCharactersOneByOne(fileReader);
Assert.assertEquals(expectedText, content);
}
Read Array of chars
Limitations of FileReader
FileWriter
Constructors
Note: Since the FileWriter is AutoCloseable, we've used try-with-resources so that we don't
have to close the FileWriter explicitly.
The FileWriter does not guarantee whether the FileWriterTest.txt file will be available
or be created. It is dependent on the underlying platform.
We must also make a note that certain platforms may allow only a single FileWriter instance
to open the file. In that case, the other constructors of the FileWriter class will fail if the file
involved is already open.
As we can see, we've used the two-argument constructor that accepts a file name and a
boolean flag append.
Passing the flag append as true creates a FileWriter that allows us to append text to
existing contents of a file.
BufferedReader
BufferedReader comes in handy if we want to read text from any kind of input source
whether that be files, sockets, or something else.
Simply: it enables us to minimize the number of I/O operations by reading chunks of
characters and storing them in an internal buffer.
While the buffer has data, the reader will read from it instead of directly from the underlying
stream.
Like most of the Java I/O classes, BufferedReader implements Decorator pattern, meaning
it expects a Reader in its constructor.
In this way, it enables us to flexibly extend an instance of a Reader implementation with
buffering functionality
BufferedReader reader =
new BufferedReader(new FileReader("src/main/resources/input.txt"));
FileReader reader =
new FileReader("src/main/resources/input.txt");
In addition to buffering, BufferedReader also provides some nice helper functions for
reading files line-by-line. So, even though it may appear simpler to use FileReader directly,
BufferedReader can be a big help.
Buffering a Stream
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
we are reading from System.in which typically corresponds to the input from the keyboard.
we could pass an input stream for reading from a socket, file or any imaginable type of
textual input.
The only prerequisite is that there is a suitable InputStream implementation for it.
BufferedReader vs Scanner
However, there are significant differences between these two classes which can make them
either more or less convenient for us, depending on our use case:
Initializing
BufferedReader reader =
new BufferedReader(new FileReader("src/main/resources/input.txt"));
Read Line-by-line
return content.toString();
}
// OR from java8+
int value;
while ((value = reader.read()) != -1) {
content.append((char) value);
}
return content.toString();
}
String result;
if (charsRead != -1) {
result = new String(chars, 0, charsRead);
} else {
result = "";
}
return result;
}
Skipping char
assertEquals("12345", result);
}
reader.reset();
result = reader.readLine();
}
Example PrintWriter
import java.io.*;
import java.util.Locale;
//Java program to demonstrate PrintWriter
class PrintWriterDemo {
Output:
true14.533GeeksforGeeks
java.io.PrintWriter@1540e19d
Geek
false
This is my GeeksforGeeks program
PrintWriterout = new PrintWriter("output.txt"); out.println(29.95);
out.println(new Rectangle(5,10,15,25));out.print("Hello, World!");out.close();
RandomAccessFile
Constructors
Methods
Example of RandomAccessFile
import java.io.*;
public class NewClass
{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;
// Writing to file
geek.writeUTF("Hello Geeks For Geeks");
// read() method :
System.out.println("Use of read() method : " + geek.read());
geek.seek(0);
// readBoolean() method :
System.out.println("Use of readBoolean() : " + geek.readBoolean());
// readByte() method :
System.out.println("Use of readByte() : " + geek.readByte());
geek.writeChar('c');
geek.seek(0);
// readChar() :
System.out.println("Use of readChar() : " + geek.readChar());
geek.seek(0);
geek.writeDouble(d);
geek.seek(0);
// read double
System.out.println("Use of readDouble() : " + geek.readDouble());
geek.seek(0);
geek.writeFloat(f);
geek.seek(0);
// readFloat() :
System.out.println("Use of readFloat() : " + geek.readFloat());
geek.seek(0);
// Create array upto geek.length
byte[] arr = new byte[(int) geek.length()];
// readFully() :
geek.readFully(arr);
Output:
@Test
public void whenWritingToSpecificPositionInFile_thenCorrect()
throws IOException {
int data1 = 2014;
int data2 = 1500;
Object Streams
Person() {
};
@Override
public String toString() {
return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
try {
FileOutputStream f = new FileOutputStream(new
File("myObjects.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
o.writeObject(p1);
o.writeObject(p2);
o.close();
f.close();
// Read objects
Person pr1 = (Person) oi.readObject();
Person pr2 = (Person) oi.readObject();
System.out.println(pr1.toString());
System.out.println(pr2.toString());
oi.close();
fi.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Output:
Name:John
Age: 30
Gender: Male
Name:Rachel
Age: 25
Gender: Female
// PRIVATE
FileOutputStream
@Test
public void givenWritingStringToFile_whenUsingFileOutputStream_thenCorrect()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
DataOutputStream
@Test
public void givenWritingToFile_whenUsingDataOutputStream_thenCorrect()
throws IOException {
String value = "Hello";
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new
BufferedOutputStream(fos));
outStream.writeUTF(value);
outStream.close();
assertEquals(value, result);
}
DataInputStream
@Test
public void whenReadWithDataInputStream_thenCorrect() throws IOException {
String expectedValue = "Hello, world!";
String file ="src/test/resources/fileTest.txt";
String result = null;
assertEquals(expectedValue, result);
}
FileClass
JFileChooserDialog
public static void main(String[] args) {
try {
FileWriterwriter = new FileWriter(args[0]);
PrintWriterout = new PrintWriter(writer);
out.println(29.95);
out.println(39.05);
writer.close();
FileReaderreader = new FileReader(args[0]);
BufferedReaderin = new BufferedReader(reader);
StringinputLine = in .readLine();
double x = Double.parseDouble(inputLine);
System.out.println(x);
inputLine = in .readLine();
x = Double.parseDouble(inputLine);
System.out.println(x);
reader.close();
} catch (Throwablee) {
System.out.println("ourError");
}
} // to run the program type "java readWriteio.txt"