COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi
Chapter 9: String + Files
String is a reference type (class) String //Since strings are used frequently, Java provides a //shorthand initializer for creating a string: String message = "Welcome to Java"; //String is a class String message = new String("Welcome to Java"); //You can also create a string from an array of // characters (char) char [] charArray = {‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’}; String message = new String(charArray);
Immutable String s = "Java"; s = "HTML";
If you use the string initializer, no new object is created, if the interned object is already created. Interned String
Difference between “==“ vs. “equals()” String Comparison String s1 = new String("Welcome"); String s2 = "Welcome"; if (s1.equals(s2)) { // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same reference }
To compare strings, do not use >=, <= String Comparison String s1 = new String("Welcome"); String s2 = "Welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 // lexicographically, i.e. unicode order } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents } else // s1 is less than s2
x.compareTo(y) return the difference of the first distinct character x = a b c y = a b d Unicode code = 81 Unicode code = 82 x.compareTo(y) = 81 – 82 = -1 String Comparison
The StringBuilder / StringBuffer class is an alternative to the String class. In general, a StringBuilder/StringBuffer can be used wherever a string is used. StringBuilder/StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer whereas the value of a String object is fixed once the string is created. StringBuilder
Command line arguments Command Line args class TestMain { public static void main(String[] args) {... }
The File class is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine- independent fashion. The filename is a string. The File class is a wrapper class for the file name and its directory path. File
The file path might be absolute or relative Absolute c:\book\Welcome.java /home/liang/book/Welcome.java Relative ..\Welcome.java images/123.jpg File Path
The directory separator for Windows is a backslash (\). The backslash is a special character in Java and should be written as \\ in a string literal The forward slash (/) is the Java directory separator, which is the same as on Unix. The statement new File("image/us.gif")works on Windows, Unix, and any other platform. File Path
A File object encapsulates the properties of a file or a path. But does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. Scanner and PrintWriter classes. Text I/O
What is the printout of the following code? Q >Welcome to Java >Welcabcme tabc Java
Suppose that s1 and s2 are two strings. Which of the following statements or expressions are incorrect? Q
Chapter 11: Inheritance
Suppose you want to define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design these classes so to avoid redundancy? The answer is to use inheritance. Motivation
Superclass GeometricObject Circle4 Rectangle1 TestCircleRectangle Run
A subclass does not inherit the private members of its parent class. A subclass is not a subset of the superclass Contains more information! Inheritance
An abstract class example abstract public abstract class GraphicObject { // declare fields // declare non-abstract methods abstract void getPerimeter(); }
A constructor may invoke An overloaded constructor or Its superclass’s constructor If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. Constructors
Example Constructors
The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways: To call a superclass constructor super(); To call a superclass method super.toString(); super
Chaining
Method overriding Overriding
Like an instance method, a static method can be inherited. However, a static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden. Overriding
Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object. Object Class
Equivalent Object Class
An object of a subtype can be used wherever its supertype value is required. This feature is known as polymorphism. Polymorphism
Polymorphism Code
Accessibility summary Accessibility
A final class cannot be extended A final variable is a constant A final method cannot be overridden by its subclasses. final
What is the printout of running the class C? Q
What problem arises in compiling the program? Q
True or false? 1. A subclass is a subset of a superclass. 2. When invoking a constructor from a subclass, its superclass’s no-arg constructor is always invoked. 3. You can override a private method defined in a superclass. 4. You can override a static method defined in a superclass. Q
What is the output? Q
Chapter 13: Exceptions
Exception Types Exception Hierarchy
RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. Checked
Exception handling process 1. Declare exception 2. Throw exception 3. Catch exception Exception Handling
Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. Declaring Exception
When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Throwing Exception
Example Throwing Exception /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
Example Catching Exception
Exception handling example Catching Exception
To deal with a checked exception, you have to write the code as shown in (a) or (b) Catching Exception
The order in which exceptions are specified in catch blocks is important. A compile error will result if a catch block for a superclass type appears before a catch block for a subclass type. Catching Exception
Occasionally, you may want some code to be executed regardless of whether an exception occurs or is caught. finally
When to use exceptions: 1. An exception occurs in a method: If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it. When?
When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. When?
Output? Q
Q
Suppose that statement2 causes an exception in the following try-catch block: Q
Answer the following questions: ■ Will statement3 be executed? ■ If the exception is not caught, will statement4 be executed? ■ If the exception is caught in the catch block, will statement4 be executed? ■ If the exception is passed to the caller, will statement4 be executed? Q