CSCI 431-001 Java Language Programmingksuweb.kennesaw.edu/~mkang9/teaching/CS7455/02.Java... ·...

Preview:

Citation preview

JAVA REVIEW

Dr. Mingon Kang

Computer Science, Kennesaw State University

Review

Programming Style

Variables

Classes

Arrays

OOP

Encapsulation

Inheritance

Polymorphism

Abstracts

Files

Interfaces

Programming Style

Indentation

Good

if (nInput < nMax)

{

if (nInput > nMin)

if (nInput > nMedian)

cout << nInput;

}

else

{

cout << nInput;

}

Programming Style

Indentation

Wrong

if (nInput < nMax)

{

if (nInput > nMin)

if (nInput > nMedian)

cout << nInput;

}

else

{

cout << nInput;

}

Programming Style

Comments

Coding Style Conventions https://msdn.microsoft.com/en-us/library/aa378932(VS.85).aspx

Hungarian Notation

https://msdn.microsoft.com/en-us/library/aa260976(VS.60).aspx

E.g., nInput, cType, szName[], *pName

Blank space both side of operators

E.g., int a = 2; (0)

int a= 2; (X)

Javadoc

Generate Java code documentation in HTML format from Java source code

http://www.tutorialspoint.com/java/java_documentation.htm

/**

* The HelloWorld program implements an application that

* simply displays "Hello World!" to the standard output.

*

* @author Mingon Kang

* @version 1.0

* @since 2016-08-01

*/

public class HelloWorld

{

public static void main(String[] args)

{

System.out.println("Hello World!");

}

}

Variables

A name used to refer to a certain location in

memory

Requires that variables must be declared with the

variable type before it is used.

Primitive Types

Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

Fundamentals of Computer Systems

Bit: zero or one

Morse Code, Punched Card, Electrical Switch, Two distinct Voltage or current levels

1 Byte = 8 bits

historically for a single character

A unit to access a memory

Data can be accessed 8 bits or multiples of 8 bits at a time

char in Java takes 2 bytes for Unicode

16 bit vs 32 bits vs 64 bits computers?

Processor registers (small amount of storage in a CPU)

Data, Address, General purpose, Conditional, and so on..

Data representation

Integer (in C/C++)

2 bytes in 16 bits systems

4 bytes in 32/64 bits systems

Unsigned integer: 0 ~ 2𝑛 − 1

Signed integer (two's complement): −2𝑛−1 ~ 2𝑛−1− 1

Integer: http://en.wikipedia.org/wiki/Integer_(computer_science)

Two’s complement: http://en.wikipedia.org/wiki/Two%27s_complement

Data representation

Character (1byte in C/C++)

ASCII code (American Standard Code for Information Interchange)

ASCII code Table: http://www.ascii-code.com/

DEC OCT HEX BIN SymbolHTML

NumberHTML Name Description

32 040 20 00100000 &#32; Space

33 041 21 00100001 ! &#33;Exclamation

mark

35 043 23 00100011 # &#35; Number

36 044 24 00100100 $ &#36; Dollar

37 045 25 00100101 % &#37;Procenttecke

n

Data representation

48 060 30 00110000 0 &#48; Zero

49 061 31 00110001 1 &#49; One

50 062 32 00110010 2 &#50; Two

51 063 33 00110011 3 &#51; Three

65 101 41 01000001 A &#65;Uppercase

A

66 102 42 01000010 B &#66;Uppercase

B

97 141 61 01100001 a &#97Lowercase

a

98 142 62 01100010 b &#98;Lowercase

b

Unicode

Unicode (2 bytes)

A character set used by the Java language that includes all the ASCII characters plus many of the characters used in languages with a different alphabet from English

Express most of the world's writing systems

http://unicode-table.com/en/#control-character

Data representation

Float: single-precision floating-point format

A bit for sign (0: positive, 1: negative)

8 bits for exponent

23 bits for fraction

http://en.wikipedia.org/wiki/Single-precision_floating-point_format

Data representation

Double: double-precision floating-point format

http://en.wikipedia.org/wiki/Double-precision_floating-point_format

Classes

Most important component of object-oriented

programming

Every program is a class in JAVA

Every library consists of classes

Programmer-defined type

Consists of “Fields” and “Methods”

Classes

Model real world objects

State and Actions

For example

Human (Name, DOB, Gender, … : Running, Sleeping,…)

Cars (Model name, Manufacturer, Current speed, Current

gear, … : Going forward, Applying brake, Changing gear,

…)

Students (Name, CWID, … : Adding/Dropping classes,

Applying graduation…)

Primitive type values vs. Class Type values

A primitive type value is a single piece of data

A class type value can have multiple data and

actions

Can have multiple different data

Can have methods that represent actions.

Classes

Model real world objects

State and Actions

For example

Human (Name, DOB, Gender, … : Running, Sleeping,…)

Cars (Model name, Manufacturer, Current speed, Current

gear, … : Going forward, Applying brake, Changing gear,

…)

Students (Name, CWID, … : Adding/Dropping classes,

Applying graduation…)

Classes

Objects

Often use object and instance word interchangeably

A unique copy of a class

Share the blueprint of a class, but has unique member

data

Read: http://java67.blogspot.com/2014/11/difference-between-

instance-and-object-in-java.html

Classes

Create an object of a class

Use new operator

Combined as follows:

Human objMingonKang;

objMingonKang = new Human();

Human objMingonKang = new Human();

Instance variables and Methods

In order to refer to a particular instance variables

(fields) or methods, preface it with its object name

as follows:

Human objMingonKang;

objMingonKang = new Human();

System.out.print(objMingonKang.strName);

objMingonKang.greet();

Arrays

A data structure for a collection of data that is all

of the same data type.

The data type can be either primitive data types or

classes.

Multiple values, but one variable name

Creating Arrays

Creating one-dimensional arrays

DataType[] array_name;

DataType[] array_name = new DataType[LENGTH];

E.g.

double[] score;

Score = new double[5];

or

double[] score = new double[5];

Initializing Arrays

Arrays are automatically initialized to null

Can be initialized when declared

The array size is automatically set to the number of the

given values.

int[] CWID = {500100, 500101, 500102};

Arrays and References

A variable of an array type holds a reference.

Arrays are objects

A variable of an array type holds the address of

where the array objects is stored in memory

2012 Pearson Addison-Wesley

Arrays as Parameters

Arrays can be used as parameters to methods

Array parameters behave like objects of a class

A method can change the values stored in the indexed

variables of the array.

A method with an array parameter have to specify the

data type of the array

Arrays as Parameters

public class Sample{

public static void example(double[] a){

a[0] = 1;

}

public static void main(String[] args)

{

double[] a = new double[5];

Sample.example(a);

System.out.println(a[0]);

}

}

Array assignment

Assignment operator =

Copy the memory address

double[] a = new double[5];

double[] b = new double[5];

a = b; // what is it doing?

Array assignment

Copy each element one by one using for loop

for (i = 0; (i < a.length) && (i < b.length); i++)

b[i] = a[i];

Array comparison

Equality operator ==

Compare whether they are stored in the same location

in the memory

double[] a = new double[5];

double[] b = new double[5];

a == b; // what is it doing?

Multidimensional Arrays

Two-dimensional arrays

Three-dimensional arrays

Even higher-dimensional arrays

Simply use as many square brackets as there are

indices

Multidimensional Arrays

Syntax

Example)

double[][] grades = new double[100][10];

int[][] images = new int[100][200];

Person[][] p = new Person[10][100];

double[][][] grades = new double[10][20][30];

Multidimensional Arrays

A two-dimensional array is an array of arrays

The variable ‘a’ contains a reference to a one-

dimensional array of size 5 with a base type of char[]

‘a[i]’ contains a reference to a one-dimensional array

of size 12.

Pearson Addison-Wesley

char[][] a = new char[5][12];

Multidimensional Arrays

A two-dimensional array is an array of arrays

Pearson Addison-Wesley

‘length’ in Multidimensional Arrays

The instance variable ‘length’ in multidimensional

arrays

char[][] a = new char[5][12];

a.length // 5

a[0].length // 12

Ragged Arrays

Each row in a two-dimensional array need not have

the same number of elements Ragged Arrays

double[][] a = new double[5][];

a[0] = new double[5];

a[1] = new double[10];

a[2] = new double[4];

Inheritance

Three main programming mechanisms that constitute

object-oriented programming (OOP)

Encapsulation

Inheritance

Polymorphism

Inheritance

Examples of inheritance

Bicycle -> Mountain Bike, Racing bicycle

Student -> high school student, undergraduate student,

graduate student

User -> Administrator, normal user, child account

Employees -> hourly employees, salaried employees

A class hierarchy

2012 Pearson Addison-Wesley

Inheritance

Inheritance allows a class (derived class) to use the

properties and methods of another class (base

class)

The base class is first defined and compiled, and

then more specialized version of the class (derived

class) are defined by adding instance variables

and methods

The new class: derived class, subclass, or child class

The original class: base class, superclass, or parent class

Inheritance

A derived class automatically has all the instance

variables and methods that the base class has.

Can have additional instance variable and methods

as well

Codes can be reused without having to copy it into

the definitions of the derived classes

2012 Pearson Addison-Wesley

Inheritance

The Java Platform Class Hierarchy

The object class (defined in the java.lang

package) defines and implements behaviors commons

to all classes.

E.g., Hierarchy for package java.util

http://docs.oracle.com/javase/7/docs/api/java/util/packa

ge-tree.html

Inheritance

Syntax

public class ParentClass{

}

public class ChildClass extends ParentClass{

}

Inheritance

// A class to display the attributes of the vehicle

class Vehicle

{

String color;

int speed;

int size;

void attributes() {

System.out.println("Color : " + color);

System.out.println("Speed : " + speed);

System.out.println("Size : " + size);

}

}

http://beginnersbook.com/2013/03/inheritance-in-java/

Inheritance

// A subclass which extends for vehicle

class Car extends Vehicle {

int CC;

int gears;

void attributescar() {

System.out.println("Color of Car : " + color);

System.out.println("Speed of Car : " + speed);

System.out.println("Size of Car : " + size);

System.out.println("CC of Car : " + CC);

System.out.println("No of gears of Car : " +

gears);

}

}

http://beginnersbook.com/2013/03/inheritance-in-java/

Inheritance

public class Test {

public static void main(String[] args) {

Car b1 = new Car();

b1.color = "Blue";

b1.speed = 200 ;

b1.size = 22;

b1.CC = 1000;

b1.gears = 5;

b1.attributescar();

}

}

http://beginnersbook.com/2013/03/inheritance-in-java/

Inheritance

// A class to display the attributes of the vehicle

class Vehicle {

String color;

private int size;

public int getSize() {

return size;

}

public void setSize(int i) {

size = i;

}

}

http://beginnersbook.com/2013/03/inheritance-in-java/

Inheritance

// A subclass which extends for vehicle

class Car extends Vehicle {

int CC;

int gears;

int color;

void attributescar() {

// Error due to access violation

//System.out.println("Size of Car : " + size);

}

}

http://beginnersbook.com/2013/03/inheritance-in-java/

Inheritance

public class Test {

public static void main(String[] args) {

Car b1 = new Car();

b1.color = 500; b1.setSize(22);

b1.CC = 1000; b1.gears = 5;

System.out.println("Color of Car : " + b1.color);

System.out.println("Size of Car : " +

b1.getSize());

System.out.println("CC of Car : " + b1.CC);

System.out.println("No of gears of Car : " +

b1.gears);

}

}

http://beginnersbook.com/2013/03/inheritance-in-java/

Method Overriding

A derived class inherits methods from the base class,

but it can change or override an inherited method.

In order to override a method definition, a new

definition of the method is simply placed in the class

definition, just like any other method that is added to

the derived class

2012 Pearson Addison-Wesley

Method Overriding

A method can only be written in Subclass

The argument list should be exactly the same as

that of the overridden method

The return type should be the same or a subtype of

the return type declared in the original overridden

method in the super class

http://crunchify.com/java-method-overriding-examples-and-concepts-overriding-rules/

Method Overriding

class Company{

public void address(){

System.out.println(“Address of Company”);

}

}

Class eBay extends Company{

public void address(){

System.out.println(“Address of eBay”);

}

}

http://crunchify.com/java-method-overriding-examples-and-concepts-overriding-rules/

Method Overriding

public class CompnayTest{

public static void main(String[] args){

// Company reference and object

Company a = new Company();

// Company reference but eBay object

Company b = new eBay();

a.address();

b.address();

}

}

http://crunchify.com/java-method-overriding-examples-and-concepts-overriding-rules/

Changing the Access Permission of an Overridden Method

The access permission of an overridden method can

be changed from private in the base class to public

(or some other more permissive access) in the

derived class

However, the access permission of an overridden

method can not be changed from public in the base

class to a more restricted access permission in the

derived class

2012 Pearson Addison-Wesley

Changing the Access Permission of an Overridden Method

Given the following method header in a base case:

private void doSomething()

The following method header is valid in a derived class:

public void doSomething()

However, the opposite is not valid

Given the following method header in a base case:

public void doSomething()

The following method header is not valid in a derived class:

private void doSomething()

2012 Pearson Addison-Wesley

The final modifier

If the modifier final is placed before the

definition of a method, then that method may not

be redefined in a derived class

It the modifier final is placed before the

definition of a class, then that class may not be used

as a base class to derive other classes

2012 Pearson Addison-Wesley

The super constructor

A derived class uses a constructor from the base class to initialize all the data inherited from the base class

In order to invoke a constructor from the base class, it uses a special syntax:

public derivedClass(int p1, int p2, double p3)

{

super(p1, p2);

instanceVariable = p3;

}

In the above example, super(p1, p2); is a call to the base class constructor

2012 Pearson Addison-Wesley

The super constructor

A call to the base class constructor can never use the

name of the base class, but uses the keyword super

instead

A call to super must always be the first action taken

in a constructor definition

An instance variable cannot be used as an argument

to super

2012 Pearson Addison-Wesley

The super constructor

If a derived class constructor does not include an invocation of super, then the no-argument constructor of the base class will automatically be invoked

This can result in an error if the base class has not defined a no-argument constructor

Since the inherited instance variables should be initialized, and the base class constructor is designed to do that, then an explicit call to super should always be used

2012 Pearson Addison-Wesley

The this constructor

Within the definition of a constructor for a class, this can be used as a name for invoking another constructor in the same class

The same restrictions on how to use a call to super apply to the this constructor

If it is necessary to include a call to both super and this, the call using this must be made first, and then the constructor that is called must call super as its first action

2012 Pearson Addison-Wesley

The this constructor

Often, a no-argument constructor uses this to invoke an explicit-value constructor No-argument constructor (invokes explicit-value constructor using this

and default arguments):

public ClassName()

{

this(argument1, argument2);

}

Explicit-value constructor (receives default values):

public ClassName(type1 param1, type2 param2)

{

. . .

}

2012 Pearson Addison-Wesley

class Shape {

private int length;

private int breadth;

// default Constructor

Shape() {

length = 0;

breadth = 0;

}

// Parameterized Constructor

Shape(int len, int bdth) {

length = len;

breadth = bdth;

}

void showattributes() {

System.out.println("length : " + length);

System.out.println("breadth : " + breadth);

}

} http://beginnersbook.com/2013/03/inheritance-in-java/

// A subclass which extends for shape

class Rectangle extends Shape {

private String type;

// default Constructor

Rectangle() {

type = null;

}

// Parameterized Constructor

Rectangle(String ty, int len, int bdth) {

super(len,bdth);

type = ty;

}

void showattributes() {

// showattributes() of class Shape is called

super.showattributes();

System.out.println("type : " + type);

}

} http://beginnersbook.com/2013/03/inheritance-in-java/

public class Test {

public static void main(String args[]) {

Rectangle rect = new Rectangle("Blue",5,7);

// showattributes() in rectangle is called

rect.showattributes();

}

}

http://beginnersbook.com/2013/03/inheritance-in-java/

Protected Access

If a method or instance variable is modified by protected(rather than public or private), then it can be accessed

by name

Inside its own class definition

Inside any class derived from it

In the definition of any class in the same package

The protected modifier provides very weak protection compared to the private modifier

It allows direct access to any programmer who defines a suitable derived class

Therefore, instance variables should normally not be marked protected

2012 Pearson Addison-Wesley

Access Levels

Modifier Class Package Subclass World

Public Y Y Y Y

Protected Y Y Y N

package

(No modifier)Y Y N N

private Y N N N

Multiple supers

JAVA does not allow to use multiple supers.

It is only valid to use super to invoke a method from a direct parent

Repeating super will not invoke a method from some other ancestor class

For example, if the Employee class were derived from the class Person, and the HourlyEmployee class were derived form the class Employee , it would not be possible to invoke the toString method of the Person class within a method of the HourlyEmployee class

super.super.toString() // ILLEGAL!

2012 Pearson Addison-Wesley

The class object

Every class is a descendent of the class Object in

Java

Even though a class is defined that is not explicitly a

derived class of another class, it is still automatically

a derived class of the class Object

The class Object is in the package java.lang which

is always imported automatically.

2012 Pearson Addison-Wesley

The class object

Every Java class can call methods of the class

Object

E.g., equals and toString methods

Default implementation of equals() class provided by

java.lang.Object compares memory location and only

return true if two reference variable are pointing to

same memory location i.e. essentially they are same

object.

2012 Pearson Addison-Wesley

Overriding the equals method

public boolean equals(Object otherObject)

{

if(otherObject == null)

return false;

if(getClass() != otherObject.getClass())

return false;

Car otherCar = (Car)otherObject;

return (color.equals(otherCar.color) &&

speed == otherCar.speed && size == otherCar.size &&

CC == otherCar.CC && gears == otherCar.gears);

}

OOP

Three main programming mechanisms that constitute

object-oriented programming (OOP)

Encapsulation

Inheritance

Polymorphism

Encapsulation

To hide the implementation details from users

In Java, a mechanism of wrapping the data and

code acting one the data together.

The variables of a class will be hidden from other class

with access modifiers.

Then, the variables can be accessed only through the

methods of their current class. Data hiding

http://beginnersbook.com/2013/05/encapsulation-in-java/

Encapsulation

Conventional Approach

Declare the variables of a class as private

Provide public setter/getter methods to modify and

view the variables values

http://www.tutorialspoint.com/java/java_encapsulation.htm

Encapsulation

Benefits of Encapsulation:

The fields of a class can be made read-only or write-

only

A class can have total control over what is stored in its

fields.

The users of a class do not know how the class stores its

data.

A class can change the data type of a field and users

of the class do not need to change any of their code.

http://www.tutorialspoint.com/java/java_encapsulation.htm

Polymorphism

Literally means

a state of having many shapes

The capacity to take on different forms

In Java, process objects of various types and classes

through a single/uniform interface.

http://www.sitepoint.com/quick-guide-to-polymorphism-in-java/

Polymorphism

Example:

In Pac-man game

Two objects: Pac-man and Ghost

Both pac-mans and ghosts can be derived from a

PacManObject class that defines basic behaviors of the

objects: Move()

However, Pac-man and Ghost may have different details in

the Move() method.

Pac-man eats pac-dots, while ghosts do not

Method Overloading

One solution for polymorphism

Overloaded Methods

public class Pacman {

public void move() {

System.out.println("Pacman::move()");

}

public void move(boolean eatPacdots){

if (eatPacdots) eatPacdots();

}

}

Method Overloading

One solution for polymorphism

Overloaded Methods

public class PacmanGame {

public static void main(String[] args) {

Pacman pacman = new Pacman();

pacman.move();

pacman.move(true);

}

}

Method Overriding

A variable is declared as superclass but is created

with child class.

Java decides what method to call during runtime

public class PacmanObject {

public void move() {

System.out.println(“PacmanObject:Move()”);

}

}

public class Ghost extends PacmanObject {

}

Method Overriding

A variable is declared as superclass but is created

with child class.

Java decides what method to call during runtime

public class Pacman extends PacmanObject {

public void move() {

super.move();

System.out.println("Pacman::move()");

}

public void move(boolean eatPacdots){

super.move();

if (eatPacdots) eatPacdots();

}

}

Method Overriding

A variable is declared as superclass but is created

with child class.

Java decides what method to call during runtime

public class PacmanGame {

public static void main(String[] args){

// obj is declared as an PacmanObject

PacmanObject obj1 = new Pacman();

PacmanObject obj2 = new Ghost();

obj1.move();

obj2.move();

}

}

Method Overriding

A variable is declared as superclass but is created

with child class.

Java decides what method to call during runtime

public class PacmanGame {

public static void main(String[] args){

PacmanObject[2] objs;

objs[0] = new Pacman();

objs[1] = new Ghost();

for (int i = 0; i < objs.length; i++)

objs[i].move();

}

}

Method Binding

Process to decide what method to call

Two types

Static Polymorphism (early binding)

Compile time polymorphism

Private, final, and static methods

Method overloading

Dynamic polymorphism (late binding)

Runtime binding

Method overriding

Method Binding

class Top {

public String f(Object o) {return "Top";}

}

class Sub extends Top {

public String f(String s) {return "Sub";}

public String f(Object o) {return "SubObj";}

}

http://stackoverflow.com/questions/5658553/question-about-java-overloading-dynamic-binding

Method Binding

public class Test {

public static void main(String[] args) {

Sub sub = new Sub();

Top top = sub;

String str = "Something";

Object obj = str;

System.out.println(top.f(obj));

System.out.println(top.f(str));

System.out.println(sub.f(obj));

System.out.println(sub.f(str));

}

}

http://stackoverflow.com/questions/5658553/question-about-java-overloading-dynamic-binding

Method Binding

Sub sub = new Sub(); // Ref: Sub, Act: Sub

Top top = sub; // Ref: Top, Act: Sub

String str = "Something"; // Ref: String, Act: String

Object obj = str; // Ref: Object, Act: String

top.f(obj); // Top.f(Object) at compile-time

// Sub.f(Object) at run-time

top.f(str); // Top.f(Object) at compile-time

// Sub.f(Object) at run-time

sub.f(obj);

sub.f(str); // Static Binding (overloading)

http://stackoverflow.com/questions/5658553/question-about-java-overloading-dynamic-binding

Abstract classes

An abstract class contains abstract methods

Abstract method

The method has a head, but no method body

The method is implemented in the subclass.

Postpone the definition of a method until a subclass

is defined

Abstract classes

For example, sort classes

variables and methods in common

Different algorithms in a sort method

Sort

Selection Sort Insertion Sort Bubble Sort Quick Sort

Abstract Methods

Define methods without method body

Cannot be private

Use ‘abstract’ modifier in its both class and method

heading

public abstract class ClassName

{

public abstract void methodName(…);

}

Abstract classes

Cannot instantiate, but only can be sub-classed

If a derived class of an abstract class adds to or

does not define all of the abstract methods, then it

is abstract class too (but with abstract modifier)

Abstract classes

An object of an abstract class cannot be created

However, the abstract class can be used a reference

variable

Files

Two types: Text file and Binary file

Text file (ASCII file)

The file data contains only ASCII values

Designed to be read by human beings

Binary file

Consist of a sequence of binary values

Designed to be read by programs

More efficient to process than text files

Streams

Stream in Java

Object that enables the flow of data between a

program and I/O device

Input Stream

Data flows into a program

Generally from the keyboard or a file

Output Stream

Data flows out of a program

Generally flow to a screen or to a file

Streams

System.in: input stream

System.out: output stream

Scanner keyboard = new Scanner(System.in)

System.out.println(“Output Stream”);

Text Files

Reading text files

BufferedReader stream class

Writing text files

PrintWriter stream class

Read a Text File

BufferedReader

Stream class that read a text file

Methods: read(…) and readLine(…)

Need to import a set of followings

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.FileNotFoundException;

import java.io.IOException;

Read a Text File

No constructor that takes a file name directly.

Use FileReader class that convert the file name

to an object for the constructor’s parameter

BufferedReader reader;

reader = new BufferedReader(new

FileReader(FileName));

Path Names

If only a file name is used as an argument, it

assumes that the file is in the same directory or

folder as the one in which the program is run

If it is not in the same directory, the full or relative

path name have to be given.

Path Names

Path names are specified depends on the operation systems

UNIX

“/user/etc/data/data.txt”

Windows

“C:\\data\\data.txt”

Reference

http://www.mkyong.com/java/how-to-construct-a-file-path-in-java/

Read a Text File

read() method

Read a single character and returns a value of integer

type

Need a type cast

readLine() method

Check FileRead1.java and FileRead2.java

char next = (char)reader.read();

Exception Handling

When performing file I/O, many exceptional

situations may be thrown.

Many of these exception classes are subclasses of

the class IOException

Exception Handling

BufferedReader object may throw two kinds of

exceptions

FileNotFoundException

IOException

Both exceptions should be handled

Exception Handling

Opening a file should be placed inside a try

block

try{

}

catch(FileNotFoundException e){

}

catch(IOException e){

}

Write a text file

PrintWriter

Stream class that write to a text file

Import of

import java.io.PrintWriter;

import java.io.FileOutputStream;

import java.io.FileNotFoundException;

Write a text file

Connect to the file FileName

Check JAVA document of PrintWriter

PrintWriter writer;

writer = new PrintWriter(new

FileOutputStream(FileName));

For appending:

writer = new PrintWriter(new

FileOutputStream(FileName, true));

Write a text file

May throw FileNotFoundException that

means the file could not be created for some

reasons

When a program finishes writing, it should close the

stream connection by

outputStreamName.close()

Write a text file

When writing to a file, the data is buffered rather

than physically writing to the file as soon as

possible.

The data is saved in a temporary space

When enough data is received in the buffer, the

flush() method is invoked, the buffered data is

physically written to the file all at once

The close() method invokes the method flush.

Binary Files

Reading binary files

ObjectInputStream stream class

Writing binary files

ObjectOutputStream stream class

Write a Binary File

ObjectOutputStream

Stream class that write a binary file

Import of followings

import java.io.ObjectOutputStream;

import java.io.FileOutStream;

import java.io.IOException;

Write a Binary File

Connect to a binary file

The constructor for FileOutputStream may throw a FileNotFoundException

The constructor for ObjectOutputStream may throw an IOException

ObjectOutputStream outputFile = new

ObjectOutputStream(new

FileOutputStream(FileName));

Write a Binary File

ObjectOutputStream methods

writeInt

writeDouble

writeChar

writeBoolean

write

flush

close

Read a Binary File

ObjectInputStream

Stream class that read a binary file

Import of followings:

import java.io.ObjectInputStream;

import java.io.FileInputStream;

import java.io.IOException;

Read a Binary File

Connect to a binary file

The constructor for FileInputStream may throw a FileNotFoundException

The constructor for ObjectInputStream may throw an IOException

ObjectInputStream inputFile = new

ObjectInputStream(new

FileInputStream(FileName));

Read a Binary File

ObjectInputStream methods

readInt

readDouble

readChar

readBoolean

close

Read a Binary File

If the file contains multiple types, each item type

must be read in exactly the same order it was

written to the file

RandomAccessFile

Read and write to the same file

Enable us to random access to particular parts of a

file

A random access file consists of a sequence of

numbered bytes (like an array)

seek() method: move a cursor in a file

Good in very large files

RandomAccessFile

Two constrcutors

RandomAccessFile(File file, String mode)

RandomAccessFile(String name, String mode)

RandomAccessFile

Mode

“r”: reading only

“rw”: both reading and writing to the file

“rws”: flushes the contents of the file and metadata (e.g. the modification date of the file)

“rwd”: flushes the contents of the file, but metadata might not change until the file is closed.

“rw” only flushes when flush() is invoked and doesn't change metadata until closing the file.

“rwd” is much slower for writes than “rw”, and “rws” is slower again

Binary I/O of objects

After interface subject, with serialization

Reference

http://www.mkyong.com/tutorials/java-io-tutorials/

Interfaces

Reference type (not a class)

Collection of abstract methods

Interface declaration

An interface is implicitly abstract

Each methods is also implicitly abstract

Abstract keyword is not necessary

Methods are implicitly public

public interface Interface_name

{

// any final, static fields

// any abstract methods

}

Interface declaration

public interface Human

{

public void eat();

public void sleep();

}

Implementing interfaces

A class implements an interface

Like signing a contract , agree to perform the specific

behaviors of the interface.

The class can declare itself as abstract when not

specifying the interface

A class uses implements keyword to implement an

interface

Implementing interfaces

public class Me implements Human

{

public void eat(){

System.out.println(“I eat”);

}

public void sleep(){

System.out.println(“I sleep”);

}

public static void main(String[] args)

{

Me m = new Me();

m.eat();

m.sleep();

}

}

Default Method

Java8 introduces “Default Method”, which allows

developer to add new methods to the interface

without breaking the existing implementation of

these interface

Although concrete class fails to provide an

implementation for the method, it provides

flexibility to allow to use default method.

Default Method

public interface oldInterface {

public void existingMethod();

default public void newDefaultMethod() {

System.out.println("New default method");

}

}

public class oldInterfaceImpl implements oldInterface

{

public void existingMethod() {

// existing implementation is here…

}

public static void main(String[] args)

{

oldInterfaceImpl o = new oldInterfaceImpl();

o.newDefaultMethod();

}

Interfaces

A class can implement more than one interface at a

time

A class can extend only one class, but implement

many interfaces

An interface can extend another interface, similarly

to the way that a class can extend another class.

http://www.tutorialspoint.com/java/java_interfaces.htm

Extending Interfaces

public interface Sports

{

public void setHomeTeam(String name);

public void setVisitingTeam(String name);

}

public interface Football extends Sports

{

public void homeTeamScored(int points);

public void visitingTeamScored(int points);

public void endOfQuarter(int quarter);

}

http://www.tutorialspoint.com/java/java_interfaces.htm

Extending Interfaces

public interface Hockey extends Sports

{

public void homeGoalScored();

public void visitingGoalScored();

public void endOfPeriod(int period);

public void overtimePeriod(int ot);

}

Extending Multiple Interfaces

Interface can extend more than one parent

interface

public interface Hockey extends Sports, Event

{

}

Interface vs Class

Interface is NOT a class

Essentially a type that can be satisfied by any class

that implements the interface.

Abstract classes are meant to be inherited from

Strong relationship between the two classes

The relationship between the interface and the class

implementing the interface is not necessarily strong

http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/

Interface vs Class

Interfaces are a good substitute for multiple

inheritance

Abstract class can have some implementation code,

while an interface cannot provide any method

definitions

http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/

The Serializable interface

An object can be represented as a sequence of

bytes that includes the object's data

In order to make a class serializable, simply add

implements Serializable to the heading of the class

definition

public class SomeClass implements Serializable

The Serializable interface

Classes that require special handling during the

serialization and deserialization process must

implement special methods with these exact

signatures:

• private void writeObject(java.io.ObjectOutputStream out) throws IOException

• private void readObject(java.io.ObjectInputStream in) throws IOException,

ClassNotFoundException;

• private void readObjectNoData() throws ObjectStreamException;

Recommended