1 / 49

Java Review I

Java Review I. Class in Java. Classes are the most important language feature that make object-oriented programming ( OOP ) possible. Combination of both attributes and behaviors Can be used to generate many objects with the same behaviors Information hidden and encapsulation

ronda
Download Presentation

Java Review I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Review I

  2. Class in Java • Classes are the most important language feature that make object-oriented programming (OOP) possible. • Combination of both attributes and behaviors • Can be used to generate many objects with the same behaviors • Information hidden and encapsulation • Programming in Java consists of defining a number of classes • Every program is a class • All helping software consists of classes • All programmer-defined types are classes • Classes are central to Java • All classes inherit from the Object class

  3. How to define a class in Java? How did we do that in C++? How should we do that in Java? public class class_name { public member func1 public member func2 … protected member var1 private member var2 … } class class_name { public: //member func. … private: // attribute list }; No semi-column!

  4. How to define a class in Java? How did we do that in C++? How should we do that in Java? public class class_name { public member func1 public member func2 … protected member var1 private member var2 … } class class_name { public: //member func. … private: // attribute list }; No semi-column! How do different access modifiers affect the access of members?

  5. One Example package One; public class DayOfYear { public DayOfYear() {month = day = 1;} public DayOfYear(intmonthVal, intdayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } private int month, day; } package Two; public class TestDemo { public static void main() { DayOfYear date1(3,18), examdate(); System.out.print(“date1.month=“ +date1.month+ ”, date1.day=“ +date1.day); examdate.input(3,20); examdate.output(); } } What will be the output of this code?

  6. One Example package One; public class DayOfYear { public DayOfYear() {month = day = 1;} public DayOfYear(intmonthVal, intdayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } private int month, day; } package Two; public class TestDemo { public static void main() { DayOfYear date1(3,18), examdate(); System.out.print(“date1.month=“ +date1.month+ ”, date1.day=“ +date1.day); examdate.input(3,20); examdate.output(); } } Compiling error! Why?

  7. One Example package One; public class DayOfYear { public DayOfYear() {month = day = 1;} public DayOfYear(intmonthVal, intdayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } private int month, day; } package Two; public class TestDemo { public static void main() { DayOfYear date1(3,18), examdate(); System.out.print(“date1.month=“ +date1.month+ ”, date1.day=“ +date1.day); examdate.input(3,20); examdate.output(); } } Compiling error! Why? Default access is “package access!” How to create objects?

  8. One Example public class DayOfYear { public DayOfYear() {} public DayOfYear(intmonthVal, intdayVal) {month = monthVal; day = dayVal; } void input(int m, int d) {month = m; day = d;} public void output() { System.out.println(“month=“ +month+ ”, day=“ +day); } private int month=1, day=1; } public class TestDemo { public static void main() { DayOfYear date1, examdate; date1=new DayOfYear(); examdate=new DayOfYear(); date1.output(); examdate.input(3,20); examdate.output(); } } How about this example?

  9. Constructor Do you know the role of constructor? How many constructors can a class have? When will a constructor be called? When will an object be created? Do you need a destructor in Java?

  10. Exercise Given the following definition public class YourClass { private intinformation = 0; private char moreInformation = ‘’; public YourClass( intnewInfo, char moreNewInfo) { <Details not shown.> } public void doStuff() { <Details not shown.> } } Which of the following are legal? YourClassanObject = new YourClass(42, 'A'); YourClassanotherObject = new YourClass(); anotherObject.doStuff(); YourClassoneMoreObject; oneMoreObject.doStuff(); oneMoreObject.YourClass(99, 'B');

  11. Exercise Given the following definition public class YourClass { private intinformation = 0; private char moreInformation = ‘’; public YourClass( intnewInfo, char moreNewInfo) { <Details not shown.> } public void doStuff() { <Details not shown.> } } Which of the following are legal? YourClassanObject = new YourClass(42, 'A'); YourClassanotherObject = new YourClass(); anotherObject.doStuff(); YourClassoneMoreObject; oneMoreObject.doStuff(); oneMoreObject.YourClass(99, 'B');

  12. Java Inheritance • Inheritance is one of the main techniques of object-oriented programming (OOP). • It enables potentially infinite reuse of resources. • It can be used to enhance and improve the previous programs for the changing requirements In one sentence, inheritance allows us to create new class from the existing classes without doing much repeated work.

  13. Java Inheritance public class Employee { public // constructor list public // member functions private string name, ssn; private double netPay; } public class HourlyEmployeeextends Employee { public // constructor list // new member functions private double wageRate; private double hours; }

  14. Java Inheritance • The phrase extends BaseClass must be added to the derived class definition. • The derived class inherits all the public methods, all the public and private instance variables, and all the public and private static variables from the base class. • The code is reused without having to explicitly copy it, unless the creator of the derived class redefines one or more of the base class methods • The derived class can add more instance variables, static variables, and/or methods

  15. Overriding a method public class Derived extends Base { public HourlyEmployeefunc() { …… return HourlyEmployee(); } privateint val3; private double val4; } public class Base { public Employee func() { … return Employee(); } private int val1; private string val2; } Need to have the same function signatures! Can the return type of the overriding method be modified? Can we change the access modifier of a method?

  16. Overriding a method public class Derived extends Base { public HourlyEmployeefunc() { …… return HourlyEmployee(); } privateint val3; private double val4; } public class Base { public Employee func() { … return Employee(); } private int val1; private string val2; } Need to have the same function signatures! Can the return type of the overriding method be modified? Typically no! But it is allowed if the derived class has the return type which is the derived class of the return type of the original function! Can we change the access modifier of a method? Yes, but can only weaken the control.

  17. Constructor in derived classes What do we need to pay attentions to ? We need to properly initialize the member variables inherited from the base class

  18. Constructor in derived classes What do we need to pay attentions to ? We need to properly initialize the member variables inherited from the base class How? Use key word super(…) to call the corresponding constructor of the base class. super(…) should always be the first line. public class Base { public Base() { val1= 0; val2 = “”; } public int val1; private string val2; } public class Derived extends Base { public Derived() { super(); val1 = 0; val4 = 0.0; } public int val1; private double val4; }

  19. An example on super constructor The base class • public class Base • { • private int x, y = 0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • } • public Base(intx_val) • { this (x_val); • } • …… • } The derived class • public class Derived extends Base • { • private double x, y = 0; • public Derived(double x_val, double y_val) • { • x = x_val; y = y_val; • } • public Derived(double x_val) • { this (x_val, 0.0); • x = x_val; • super (x_val); • } • …… • } Any issues?

  20. An example on super constructor The base class • public class Base • { • private int x, y = 0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • } • public Base(intx_val) • { this (x_val); • } • …… • } The derived class • public class Derived extends Base • { • private double x, y = 0; • public Derived(double x_val, double y_val) • { • // Base class does not have a constructor with empty argument list! • x = x_val; y = y_val; • } • public Derived(double x_val) • { this (x_val, 0.0); • x = x_val; • super (x_val); // super needs to be in the first line! • } • …… • } Any issues?

  21. An example on super constructor The base class • public class Base • { • private int x = 0, y = 0; • public Base() {} • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • } • public Base(intx_val) • { this (x_val); • } • …… • } The derived class • public class Derived extends Base • { • private double x, y = 0; • public Derived(double x_val, double y_val) • { • super (x_val); // super needs to be in the first line! • x = x_val; y = y_val; • } • public Derived(double x_val) • { this (x_val, 0.0); • x = x_val; • } • …… • } Any issues?

  22. Constructor in derived classes What do we need to pay attentions to ? We need to properly initialize the member variables inherited from the base class How? Use key word super(…) to call the corresponding constructor of the base class. super(…) should always be the first line. Do you know the difference between super(…) and this(…)? Do you know how to use super. to invoke the overridden function from the base class?

  23. Example • public class Derived2 extends Derived • { • booleansetx_or_y = false; • public Derived2(){} • public Derived2(boolean flag, double val) • { • if (flag==true) x=val; • else y=val; • setx_or_y = flag; • System.out.println("Derived class 2."); • } • public static void main(String[] args) • { • Base obj1; • Derived obj2 = new Derived (4, 5); • Derived2 obj3 = new Derived2(false, 3); • obj2.print(); • obj3.print(); • } • } • public class Base • { • protected int x=0, y=0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • System.out.println(“Base class.”); • } • public Base() • { this (0, 0); • } • public void print() • { System.out.println(“x=“+x); • System.out.println(“y=“+y); • } • } • public class Derived extends Base • { • protected double x=0, y=0; • public Derived() • { • this (0.0, 1.0); • } • public Derived(double x_val, double y_val) • { • super ((int)x_val, (int)y_val); • x = x_val; y = y_val; • System.out.println(“Derived class.”); • } • } what will be the output?

  24. Example • public class Derived2 extends Derived • { • booleansetx_or_y = false; • public Derived2(){} • public Derived2(boolean flag, double val) • { • if (flag==true) x=val; • else y=val; • setx_or_y = flag; • System.out.println("Derived class 2."); • } • public static void main(String[] args) • { • Base obj1; • Derived obj2 = new Derived (4, 5); • Derived2 obj3 = new Derived2(false, 3); • obj2.print(); • obj3.print(); • } • } • public class Base • { • protected int x=0, y=0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • System.out.println(“Base class.”); • } • public Base() • { this (0, 0); • } • public void print() • { System.out.println(“x=“+x); • System.out.println(“y=“+y); • } • } • public class Derived extends Base • { • protected double x=0, y=0; • public Derived() • { • this (0.0, 1.0); • } • public Derived(double x_val, double y_val) • { • super ((int)x_val, (int)y_val); • x = x_val; y = y_val; • System.out.println(“Derived class.”); • } • } Base Derived Derived2

  25. Example • public class Derived2 extends Derived • { • booleansetx_or_y = false; • public Derived2(){} • public Derived2(boolean flag, double val) • { • if (flag==true) x=val; • else y=val; • setx_or_y = flag; • System.out.println("Derived class 2."); • } • public static void main(String[] args) • { • Base obj1; • Derived obj2 = new Derived (4, 5); • Derived2 obj3 = new Derived2(false, 3); • obj2.print(); • obj3.print(); • } • } • public class Base • { • protected int x=0, y=0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • System.out.println(“Base class.”); • } • public Base() • { this (0, 0); • } • public void print() • { System.out.println(“x=“+x); • System.out.println(“y=“+y); • } • } • public class Derived extends Base • { • protected double x=0, y=0; • public Derived() • { • this (0.0, 1.0); • } • public Derived(double x_val, double y_val) • { • super ((int)x_val, (int)y_val); • x = x_val; y = y_val; • System.out.println(“Derived class.”); • } • } Base class. Derived class. Base Derived Derived2

  26. Example • public class Derived2 extends Derived • { • booleansetx_or_y = false; • public Derived2(){} • public Derived2(boolean flag, double val) • { • if (flag==true) x=val; • else y=val; • setx_or_y = flag; • System.out.println("Derived class 2."); • } • public static void main(String[] args) • { • Base obj1; • Derived obj2 = new Derived (4, 5); • Derived2 obj3 = new Derived2(false, 3); • obj2.print(); • obj3.print(); • } • } • public class Base • { • protected int x=0, y=0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • System.out.println(“Base class.”); • } • public Base() • { this (0, 0); • } • public void print() • { System.out.println(“x=“+x); • System.out.println(“y=“+y); • } • } • public class Derived extends Base • { • protected double x=0, y=0; • public Derived() • { • this (0.0, 1.0); • } • public Derived(double x_val, double y_val) • { • super ((int)x_val, (int)y_val); • x = x_val; y = y_val; • System.out.println(“Derived class.”); • } • } Base class. Derived class. Base Derived Derived2

  27. Example • public class Derived2 extends Derived • { • booleansetx_or_y = false; • public Derived2(){} • public Derived2(boolean flag, double val) • { • if (flag==true) x=val; • else y=val; • setx_or_y = flag; • System.out.println("Derived class 2."); • } • public static void main(String[] args) • { • Base obj1; • Derived obj2 = new Derived (4, 5); • Derived2 obj3 = new Derived2(false, 3); • obj2.print(); • obj3.print(); • } • } • public class Base • { • protected int x=0, y=0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • System.out.println(“Base class.”); • } • public Base() • { this (0, 0); • } • public void print() • { System.out.println(“x=“+x); • System.out.println(“y=“+y); • } • } • public class Derived extends Base • { • protected double x=0, y=0; • public Derived() • { • this (0.0, 1.0); • } • public Derived(double x_val, double y_val) • { • super ((int)x_val, (int)y_val); • x = x_val; y = y_val; • System.out.println(“Derived class.”); • } • } Base class. Derived class. Base class. Derived class. Derived class 2. Base Derived Derived2

  28. Example • public class Derived2 extends Derived • { • booleansetx_or_y = false; • public Derived2(){} • public Derived2(boolean flag, double val) • { • if (flag==true) x=val; • else y=val; • setx_or_y = flag; • System.out.println("Derived class 2."); • } • public static void main(String[] args) • { • Base obj1; • Derived obj2 = new Derived (4, 5); • Derived2 obj3 = new Derived2(false, 3); • obj2.print(); • obj3.print(); • } • } • public class Base • { • protected int x=0, y=0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • System.out.println(“Base class.”); • } • public Base() • { this (0, 0); • } • public void print() • { System.out.println(“x=“+x); • System.out.println(“y=“+y); • } • } • public class Derived extends Base • { • protected double x=0, y=0; • public Derived() • { • this (0.0, 1.0); • } • public Derived(double x_val, double y_val) • { • super ((int)x_val, (int)y_val); • x = x_val; y = y_val; • System.out.println(“Derived class.”); • } • } Base class. Derived class. Base class. Derived class. Derived class 2. Base Derived Derived2

  29. Example • public class Derived2 extends Derived • { • booleansetx_or_y = false; • public Derived2(){} • public Derived2(boolean flag, double val) • { • if (flag==true) x=val; • else y=val; • setx_or_y = flag; • System.out.println("Derived class 2."); • } • public static void main(String[] args) • { • Base obj1; • Derived obj2 = new Derived (4, 5); • Derived2 obj3 = new Derived2(false, 3); • obj2.print(); • obj3.print(); • } • } • public class Base • { • protected int x=0, y=0; • public Base(intx_val, inty_val) • { • x = x_val; y = y_val; • System.out.println(“Base class.”); • } • public Base() • { this (0, 0); • } • public void print() • { System.out.println(“x=“+x); • System.out.println(“y=“+y); • } • } • public class Derived extends Base • { • protected double x=0, y=0; • public Derived() • { • this (0.0, 1.0); • } • public Derived(double x_val, double y_val) • { • super ((int)x_val, (int)y_val); • x = x_val; y = y_val; • System.out.println(“Derived class.”); • } • } Base class. Derived class. Base class. Derived class. Derived class 2. x=4 y=5 x=0 y=1 Base Derived Derived2

  30. Take Home Example • public class Base1 • { • public Base1(intval) • { System.out.println(“Base1: “+val); • } • } • public class Derived21 extends Base2 • { • public Derived21 (intval) • { super(val); • System.out.println(“Derived21: “+val); • } • } • public class Derived11 extends Base1 • { • public Derived11 (intval) • { super(val); • System.out.println(“Derived11: “+val); • } • } • public class Base3 • { • public Base3(intval) • { System.out.println(“Base3: “+val); • } • } • public class Derived12 extends Derived11 • { • public Derived12 (intval) • { super(val); • System.out.println(“Derived12: “+val); • } • } • public class Derived31 extends Base3 • { • private Derived11 comp1; • private Derived21 comp2; • public Derived31(intval) • { super(val+1); • comp1 = new Derived12(val+2); • comp2 = new Derived21(val+4); • } • public static void main(String[] args) • { • Derived31 obj = new Derived31(1); • } • } • public class Base2 • { • public Base2(intval) • { System.out.println(“Base2: “+val); • } • }

  31. Java Polymorphism • Why do we need polymorphism. • Further improve the reuse and maintenance of software • What does polymorphism mean? • It refers to the ability to associate many meanings to one method name by means of a special mechanism known as late binding or dynamic binding. • What does late binding mean? • determining the instance function based on the type of the calling object during run time!

  32. Java Polymorphism • How to enable late binding in Java? • What are the three ingredients to enable Java polymorphism?

  33. Java Polymorphism • How to enable late binding in Java? • Most functions are late binding • What are the three ingredients to enable Java polymorphism? • Inheritance • method overriding • upcasting

  34. Example public class Animal { public Animal() { System.out.println(“Animal.”);} public void eat() { System.out.println(“Animal needs to eat.”); } } public class Human extends Primate { public Human() { System.out.println(“Human.”);} public void eat() { System.out.println(“Human eats whatever we can eat.”); } } public class Bird extends Animal { public Bird () { System.out.println(“Bird.”);} public void eat() { System.out.println(“Bird eats bugs.”); } } public class WhatAnimalEat { public static void whatdoyoueat(Animal a) { a.eat(); } public static void main(String[] args) { Animal a, b, c; a = new Animal(); b = new Bird(); c = new Human(); whatdoyoueat(a); whatdoyoueat(b); whatdoyoueat(c); } } public class Primate extends Animal { public Primate() { System.out.println(“Primate.”);} public void eat() { System.out.println(“Primate eats both vegs and meat.”); } } What will be the output?

  35. The final Modifier • If the modifier finalis placed before the definition of a method, then that method may not be redefined in a derived class • If the modifier finalis placed before the definition of a class, then that class may not be used as a base class to derive other classes

  36. Example public class Animal { public Animal() { System.out.println(“Animal.”);} public void eat() { System.out.println(“Animal needs to eat.”); } } public class Human extends Primate { public Human() { System.out.println(“Human.”);} } public class Bird extends Animal { public Bird () { System.out.println(“Bird.”);} public void eat() { System.out.println(“Bird eats bugs.”); } } public class WhatAnimalEat { public static void whatdoyoueat(Animal a) { a.eat(); } public static void main(String[] args) { Animal a, b, c; a = new Animal(); b = new Bird(); c = new Human(); whatdoyoueat(a); whatdoyoueat(b); whatdoyoueat(c); } } public class Primate extends Animal { public Primate() { System.out.println(“Primate.”);} public final void eat() { System.out.println(“Primate eats both vegs and meat.”); } } What will be the output?

  37. Abstract Class To postpone the definition of a method, it is specified as an abstract method. A class containing at least one abstract method needs to be specified as an abstract class. An abstract class must have the “abstract” modifier in its class heading public abstract class Figure { public Figure (double cx, double cy) { center_x=cx; center_y=cy;} public Figure() { this (0,0); } public abstract void draw(); public abstract void area(); public void reset_center(double x, double y) { center_x=x; center_y=y;} private double center_x=0, center_y=0; }; Abstract methods define the interface of the base class and all its derived classes, because…?

  38. Abstract Class To postpone the definition of a method, it is specified as an abstract method. A class containing at least one abstract method needs to be specified as an abstract class. An abstract class must have the “abstract” modifier in its class heading public abstract class Figure { public Figure (double cx, double cy) { center_x=cx; center_y=cy;} public Figure() { this (0,0); } public abstract void draw(); public abstract void area(); public void reset_center(double x, double y) { center_x=x; center_y=y;} private double center_x=0, center_y=0; }; Abstract methods define the interface of the base class and all its derived classes, because…? Can an abstract class be used to create an object? Why or why not?

  39. Example • public abstract class Base • { • protected int type = 0; • public Base(inttype) • { type = type; • System.out.println(“Base class.”); • } • public Base() • { this (0); } • public abstract intgetType() • { return type;} • public String toString() • { • return Integer.toString(getType()); • } • } • public class Derived2 extends Derived • { • private intderived_type = 2; • public Derived2 (inttype) • { super (type); derived_type=type; • System.out.println(“Derived class 2.”); • } • public Derived2() • { this(2);} • public intgetType() • { System.out.print(“Derived class 2 type ”); • return type; • } • } public class TestDemo { public static void main(String[] args) { Base obj1 = new Derived(1); Base obj2 = new Base(); Base obj3 = new Derived2(3) System.out.println(obj1); System.out.println(obj2); System.out.println(obj3); } } • public class Derived extends Base • { • private intderived_type = 1; • public Derived (inttype) • { super (type); derived_type=type; • System.out.println(“Derived class.”); • } • public Derived() • { this(1); } • public intgetType() • { System.out.print(“Derived class type ”); • return derived_type; • } • } What will be the output of this code?

  40. Java Interface A Java interface specifies a set of methods that any class that implements the interface must have. One way to view an interface is as an extreme form of an abstract class. An interface is NOT a class, but rather a type! Purpose: define methods with parameters of an interface type, and have the code apply to all classes that implementthe interface.

  41. Java Interface A Java interface specifies a set of methods that any class that implements the interface must have. One way to view an interface is as an extreme form of an abstract class. An interface is NOT a class, but rather a type! Purpose: define methods with parameters of an interface type, and have the code apply to all classes that implement the interface. public interfaceInterface_Name { publicreturn_type func1(<argument list>); public void func2(); public String getInfo(); publicbooleancompareTwoObjs(Object obj1, Object obj2); } public for the interface methods!

  42. Java Interface A Java interface specifies a set of methods that any class that implements the interface must have. One way to view an interface is as an extreme form of an abstract class. An interface is NOT a class, but rather a type! Purpose: define methods with parameters of an interface type, and have the code apply to all classes that implement the interface. Other classes that use the interface need to use the key word implements. public interfaceInterface_Name { publicreturn_type func1(…) public void func2(); public String getInfo(); } public ConcreteClassimplementsInterface_Name { public Object func1(…){//provide func body!} public void func2(){ // func2 body} public String getInfo(){ // getInfo body} }

  43. File I/O in Java File I/O is important! Like every other programming language, Java supports the writing to and reading from different files with different formats. It is achieved via the following set of classes java.io.PrintWriter; java.io.FileOutputStream; java.util.Scanner; java.io.FileInputStream; java.io.BufferedReader; java.io.FileReader; ……

  44. Screen I/O streams We have learned some screen stream using System.out.* functions and Scanner and System.in objects System.out.printf(“<formatting>”, var1, var2,…); System.out.print(String…); //in same line System.out.println(String…); //next line import java.util.Scanner//for input Scanner keyboard = new Scanner(System.in); int var1 = keyboard.nextInt(); double var2 = keyboard.nextDouble(); String s1 = keyboard.next(); // read one word String s2 = keyboard.nextline(); //read one line Byte stream: perform input and output of 8-bit bytes. In the later File IO FileInputStream and FileOutputStream are byte streams that allow the program to read and write binary files. All other stream types are built on byte streams, such as the character streamfor text file reading and writing.

  45. How to write to a text file Use PrintWriterclass It has the similar methods as System.out such as print(…) and println(…) import java.io.PrintWriter; import java.io.FileOutputStream; import java.io.FileNotFoundException; public class WriteTextFileDemo { public static void main (String[] args) { PrintWriteroutputStreamName; String Filename = "test.txt"; try { outputStreamName= new PrintWriter(Filename); //outputStreamName= new PrintWriter(new FileOutputStream (Filename)); outputStreamName.println("test text file!"); outputStreamName.println("succeeded!"); // Do other fancy output … outputStreamName.close(); } catch(FileNotFoundExceptione) { System.out.println("File "+Filename+"cannot be found."); System.exit(0); } } }

  46. Appending to a text file In some situations, you do not want to overwrite what has been recorded in the existing file. The new output will be appended to the previous output. Use the following format to open the file! outputStreamName = new PrintWriter( new FileOutputStream(FileName, true)); Or outputStreamName = new PrintWriter(FileName, true);

  47. Read from a text file 1. Using Scannar class • Simply replace the argument System.in (to the Scanner constructor) with a suitable stream that is connected to the text file • Scanner StreamObject= • new Scanner(new FileInputStream(FileName)); Methods of the Scanner class for reading input behave the same whether reading from the keyboard or reading from a text file.

  48. Testing the end of the text file Example: adding line number to the file Given input file: The output file will be

  49. Read from a text file 2. Using BufferReader class • BufferedReaderreaderObject; • readerObject= new BufferedReader(new • FileReader(FileName)); After the file is successfully opened, the readLine() and read() methods can be used to read from the file. • The readLinemethod is the same method used to read from the keyboard, but in this case it would read from a file. • The readmethod reads a single character, and returns a value (of type int) that corresponds to the character read.

More Related