Part 2

  • Uploaded by: Adithya Addanki
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Part 2 as PDF for free.

More details

  • Words: 6,667
  • Pages: 76
SCJP Boot Camp (Part II) SQL STAR INTERNATIONAL June, 2009

-- 3.3 -Passing Variables into Methods 7.3 Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.

Java: pass-by-copy-of-the-variable (1) • •

can take primitives and/or object references Java: pass-by-copy-of-the-variable • always passing a copy of the bits in the variable • method can't change the caller's variable,



Passing Object Reference Variables: • keep in mind that you're passing the object reference, and not the actual object itself • aren't even passing the actual reference variable, but rather a copy of the reference variable • two identical reference variables refer to the exact same object • can't reassign the caller's original reference variable and make it refer to a different object, or null



Passing Primitive Variables • Only a copy, so won’t change the value of the primitive 3

++ Shadowed variables •

Shadowing involves re-declaring a variable that's already been declared somewhere else • shadow an instance variable by declaring a local variable of the same name • Shadow a reference variable should keep in your mind with: can change the object value, but can’t assign to another object. • It is very easy to be a test

4

Array

1.3 Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names.

Basic concepts



Arrays are objects in Java that store multiple variables of the same type An array of objects can hold any object that passes the IS-A (or instanceof) test for the declared type of the array; can hold either primitives or object references always be an object on the heap



## For exam ##

• •



• How to make an array reference variable (declare) • How to make an array object (construct) • How to populate the array with elements (initialize) 6

Declarations •

Declaring an Array of Primitives • int[] key; // Square brackets before name (recommended) • int key []; // Square brackets after name (legal but less readable)



Declaring an Array of Object References • Thread[] threads; // Recommended • Thread threads []; // Legal but less readable



multidimensional arrays: • String[][] occupantName; • String[] ManagerName []; // it's legal doesn't mean it's right



illegal to include the size of the array in your declaration: • int [5] scores; is not right 7

Constructing •

To create an array object, Java must know how much space to allocate on the heap, so you must specify the size of the array at creation time. • must have either a dimension expression or an initializer. If fail to do, then a compile-time error is generated. • int scores[ ] = new int[5]; • int[ ] scores = new int[ ] {1,2,3,4,5} ;

• •

One-Dimensional Arrays Multidimensional Arrays • an object of type int array (int[]), with each element in that array holding a reference to another int array. • The second dimension holds the actual int primitives. • Must specify the first dimension, can not only define the second without define the first • ++ int [ ] [ ] x = new int [5] [ ] is legal  new int [ ] [5] is illegal

• the JVM needs to know only the size of the object assigned to the variable myArray.

• ++ WRONG: int [ ] x = new short [ ];  short can put into int[ ], but char [ ] can not assign to int[ ]. • ++ CANNOT define both size and initialize at the same time

8

Initialization Array doesn't actually hold the objects, but instead holds a reference to the object. • ++ Array index number always begins with zero • Need to assign elements to reference the actual created objects one by one. •

• Try to use null element will get an NullPointerException • out-of-range array index will get an ArrayIndexOutOfBoundsException •

Declaring, Constructing, and Initializing on One Line • for(Dog d : myDogs) d = new Dog();



Constructing and Initializing an Anonymous Array • • • •

Init blocks execute in the order they appear. Static init blocks run once, when the class is first loaded. Instance init blocks run every time a class instance is created. Instance init blocks run after the constructor's call to super(). 9

++ Initialization Blocks ++ Instance init blocks are often used as a place to put code that all the constructors in a class should share. That way, the code doesn't have to be duplicated across constructors. static blocks run only once, when the class is first loaded



2.



any mistake in static blocks, JVM throw ExceptionInInitializationError

Initial blocks execute in the order of they appear, after call new

3.



Initial blocks can be repeatedly run depend on the objects creation 10

-- 3.5 -Using Wrapper Classes and Boxing 3.1 Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.

• • • • • • • •

• •



boolean byte char double float short int long

Overview

| Boolean | Byte | Character | Double | Float | Short | Integer | Long

| boolean or String | byte or String | char | double or String | float, double, or String | short or String | int or String | long or String

Wrapper objects are immutable, as String, value can’t change two constructors: (except Character) • takes a primitive of the type being constructed, • ++ takes a String representation of the type being constructed ++ Boolean ≠ boolean • Boolean can used as an expression in a boolean test because of12 the autoboxing

Wrapper Conversion Utilities •

primitive xxxValue() • to convert a Wrapper to a primitive: int x = xxWrapper.intValue();



primitive parseXxx (String) • to convert a String to a primitive: • double x = Double.parseDouble(“12.34”);

• parseXxx() returns the named primitive. •

Wrapper valueOf (String) • to convert a String to a Wrapper: • Double x = Double.valueOf(“12.34”);

• valueOf() returns a newly created wrapped object of the type that invoked the method. •

String toString(): static • a String with the value of the primitive wrapped in the object • String x = xxDouble.toString();



toXxxString() (Binary, Hex, Octal) • String x = Integer.toOctalString(123);

13

Autoboxing • •

the compiler does the unboxing and reassignment for you Boxing, ==, and Equals() •



== check if the object is same, equals() check the value

++ But, When == is used to compare a primitive to a wrapper

object, the wrapper object will be unwrapped to its primitive value, and the comparison will be made between the two primitives' values • Only for those Wrappers: • Boolean, Byte, • Character from \u0000 to \u007f , • Integer and Short from -128 to 127 • • •

• •

use wrappers to make those primitives collection-compatible boxing and unboxing work wherever you can normally use a primitive or a wrapped object. Remember, wrapper reference variables can be null. That means that you have to watch out for code that appears to be doing safe primitive operations, but that could throw a NullPointerException short cannot boxing to Integer int cannot boxing to Long 14

-- 3.6 -Overloading 1.5 Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method. 5.4 Given a scenario, develop code that declares and/or invokes overridden or overloaded methods…

• •



Overloading Tricks (1)

Three factors that can make overloading a little tricky: • ++ Widening > Autoboxing >Var-args Method Matching • In every case, when an exact match method isn't found, the JVM uses the method with the smallest argument that is wider than the parameter. Boxing • the compiler will choose widening over boxing • int x will

• static void go (long x) {} > static void go (Integer x) {} • ++ but not the go (Long x) : because int  long but no longer to Long •

Var-Args • the compiler will choose the older style before it chooses the newer style, keeping existing code more robust • byte x, byte y • static void go (int x, int y) {} > static void go (byte... x) {}

• the var-args method is "looser" than the other method • static void go (Byte x, Byte y) {} > static void go (byte... x) {}

16

++ Overloading Tricks (2) • •

Widening > Boxing > Var-args (loosest) Widening Reference Variables

• reference widening depends on inheritance: if pass the ISA test • Primitive widening uses the "smallest" method argument possible. • Example: input “int” choose double argument over Integer argument • •

Boxing and var-args are compatible with overloading. Boxing and widening are not compatible • You CANNOT widen from one wrapper type to another. (IS-A fails.) • Integer is not a Long, Byte…. • You CANNOT widen and then box. (An int can't become a Long.) • You CAN box and then widen. (An int can become an Object, via Integer.)



var-args CAN combine with either widening or boxing. 17

-- 3.7 -Garbage Collection 7.4 Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization.

Memory management •





Memory leaks: over many thousands of iterations they can make enough memory inaccessible that programs will eventually crash. Heap: All of garbage collection revolves around making sure that the heap has as much free space as possible. An object is eligible for garbage collection when no live thread can access it == Java program has a reference variable that refers to an object, and that reference variable is available to a live thread, then that object is considered reachable. 19

• • •

Explicit Code Makes Objects Eligible for Collection

Nulling a Reference Reassigning a Reference Variable Isolating a Reference

• instance variables so that they refer to each other, but their links to the outside world have been nulled. •

Forcing Garbage Collection • The garbage collection routines that Java provides are members of the Runtime class. • The Runtime class is a special class that has a single object (a Singleton) for each main program. • Runtime.getRuntime(): returns the Singleton • Once you have the Singleton you can invoke the garbage collector using the gc() method; • Runtime.getRuntime().gc(); or • System.gc();

20

finalize() •

• •

every class inherits the finalize() method from java.lang.Object finalize () is called by the garbage collector when it determines no more references to the object exist Cleaning up before Garbage Collection—The finalize() Method • For any given object, finalize () will be called only once (at most) by the garbage collector. • Calling finalize() can actually result in saving an object from deletion.



CAN be overridden • normally it should be overridden to clean-up non-Java resources ie closing a file • use a try-catch-finally statement and to always call super.finalize()

• protected void finalize() throws Throwable { • try { • close(); // close open files

• } finally { • super.finalize();

• }

• }

21

-- 4.1 -Operators 7.6 Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, | |), and the conditional operator (? :), to produce a desired result. Write code that determines the equality of two objects or two primitives.

Basic concepts •

The result of most operations is either a boolean or numeric value. Because Java operators aren't typically overloaded. • The + operator can be used to add two numeric primitives together, or to perform a concatenation operation if either operand is a String. • The &, |, and ^ operators can all be used in two different ways, although as of this version of the exam, their bit twiddling capabilities won't be tested

23

Assignment Operators (=) •

• •

When assigning a value to a primitive, size matters. Be sure you know when implicit casting will occur, when explicit casting is necessary, and when truncation might occur. Remember that a reference variable isn't an object; it's a way to get to an object. When assigning a value to a reference variable, type matters. Remember the rules for supertypes, subtypes, and arrays • • • •

Super ref = sub object, is wrong Sub ref = super object, is ok Instance methods depend on real object Static method, static variable depend on reference

24

"Equality" Operators (== , !=) •

Four testable types of things: • numbers • characters • boolean primitives • Object reference variables • When == is used to compare a primitive to a wrapper object, the wrapper object will be unwrapped to its primitive value, and the comparison will be made between the two primitives' values • Only for those Wrappers: Boolean, Byte, Character from \u0000 to \u007f , Integer, Short

• • • •

Equality for Primitives Equality for Reference Variables Equality for Enums instanceof Comparison: should pass IS-A test • Legal to test whether the null reference is an instance of a class.  will always result in false • can't use the instanceof operator to test across two different class hierarchies 25

Logical Operators • •

Bitwise Operators (&, |, and ^) Short-Circuit Logical Operators ( &&, || ) • work only with boolean operands.



Logical Operators (&, |, ^ and ! ) • evaluate both sides of the expression, always

26

++ instanceof •

Returns true if the reference variable being tested is of the type being compared to • if (t1 instanceof Object) { • System.out.println(“ t1 is an Object."); • } else { • System.out.println(“ t1 isn’t an Object."); • }

• ++ null instanceof Xxx always be false • ++ instanceof can not test two different class hierarchies, will cause compile error •

++ Trick: • Integer [] x  x instanceof Object  true, not Integer yet • Integer[1]  instanceof Object and Integer, Number are true 27

Other operators •

Compound Assignment Operators ( +=, -=, *=, and /= ) • ++ x *= 2 + 5;  x = x * (2 + 5) ; • the expression on the right is always placed inside parentheses

• • •

Relational Operators ( <, <= , >, >=, == , and != ) Arithmetic Operators( +, -, *, /, % ) String Concatenation Operator • If either operand is a String, the + operator becomes a String concatenation operator. If both operands are numbers, the + operator is the addition operator.



Increment and Decrement Operators (++, - -)



++ Conditional Operator: • X = (boolean expression) ? value to assign if true : value to assign if false; 28

-- 5.1 -Flow Control if and switch Statements 2. 1 Develop code that implements an if or switch statement; and identify legal argument types for these statements.

if • else if () {} may be unreachable • Only legal expression in an if test is a boolean. • ++ Boolean x  if (x= true) is legal • Be prepared for questions that not only fail to indent nicely, but intentionally indent in a misleading way

30

switch •

switch (expression) { } • ++ only accept: variables and values that can be automatically promoted to an int • Can use an enum



Case constant: • Case variable must be constant • must evaluate to the same type as the switch expression • ++ Byte expression  case 128 is out of range • ++ final int a = 1;  is a constant, compile time constant • ++ final int b; b= 1;  not a constant • Cannot using the same value • case constants are evaluated from the top down, and the first case constant that matches the switch's expression is the execution entry point. • The default case doesn't have to come at the end of the 31 switch.

-- 5.3 -Loops and Iterators 2.2 Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution.

While and do •

while • ++ expression of a while loop must be declared before the expression is evaluated  illegal: while (boolean x = true) {} • The expression result must be a boolean



do

33

for •

for (/*Initialization*/ ; /*Condition*/ ; /* Iteration */) { •



/* loop body */

} • None of the three sections of the for declaration are required for( ; ; ) {}



Initialization expression : • Can declare more than one, Separate with comma • ++ Be careful the scope problem: for(int x; ;)  can not use x out of for loop • ++ int x = 0; for(; x<10;) { x++ } is legal and x can be used out of for loop



Conditional expression • Only one test expression



Interation Expression • After the body run finished



++ break, return, System.exit() will cause a loop terminate



++ for variable is within same scope with method: • Method(int i), then for can not redefine int i 34

The Arrays Enhanced for Loop •

for (declaration : expression) • Declaration: This variable will be available within the for block, and its value will be the same as the current array element. • Expression: This must evaluate to the array you want to loop through. Or could be an array variable or a method call that returns an array. ++ The array can be any type: primitives, objects, even arrays of arrays.

35

++ Special controls •

continue • statements must be inside a loop



break • statements must be used inside either a loop or switch statement • Execution jumps immediately to the 1st statement after the for loop.



return • Execution jumps immediately back to the calling method.



system.exit() • All program execution stops; the VM shuts down. 36

Labeled Statements •

most common to use labels with loop statements like for or while, in conjunction with break and continue statements. • Not for if statement



A label statement • ++ must be placed just before the statement

• being labeled plus a “:” •

Labeled continue and break statements must be inside the loop that has the same label name; otherwise, the code will not compile.

37

-- 5.4 -Handling Exceptions 2.4 Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions. 2.5 Recognize the effect of an exception arising at a specific point in a code fragment, Note that the exception may he a runtime exception, a checked exception, or an error.

try and catch/finally •

try is used to define guarded region, a block of code in which exceptions may occur • Must be followed by either catch or finally, or both • Can't sneak any code in between the try, catch, or finally blocks. • only with finally, must still declare the exception



catch clauses match a specific exception to a block of code that handles it • no requirement that catch clause for every possible exception • The order of catch must from smaller to bigger (exception hierarchy )



finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. • ++ Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes • If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. 39 • Is not required

Exception propagation “duck” • • •



++ Rule: “handle or declare” Can throws the exception down to the bottom of stack the exception drops down to the previous method, until it is caught or until it reaches the very bottom of the call stack. An exception that's never caught will cause your application to stop running. • main() need to handle the exception, otherwise JVM will shut down

40

Checked/Runtime exception •

Throws & throw: • void xxxx() throws xxException { • If (condition== ture) {

• throw new xxException(); • } • } •

Checked exception: • Compiler guarantees the exceptions have been checked



• Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception. (declare/ duck) Runtime (Unchecked) exception: • Compiler won’t check it • Can wrap it by try/catch, or leave it be 41

Multiple Throw/Catch Multiple Throw • A method can throw multiple exceptions • void xxxMethod() throws xxException, yyException { } Multiple Catch • try { // some code } • catch (Exception e) { e.printStackTrace(); } • • •

This code will catch every exception generated. No single exception handler can properly handle every exception, and programming in this way defeats the design objective.

++ Catch the subclass then catch the superclass, otherwise get compiler error: • •

TestEx.java:15: exception java.io.FileNotFoundException has already been caught } catch (FileNotFoundException ex) {

Re-throwing the Same Exception • ++ Must handle and declare • •

declare that exception Catch throw the same exception you just caught • Catch (IOException e) { throw e; }



All other catch clauses are ignored

42

43

Exception hierarchy •

Throwable classes, includes Exception and Error. • exceptions are always some subclass of java.lang.Exception • Exception, Error, RuntimeException, and Throwable types can all be thrown using the throw keyword, and can all be caught



Two methods in Throwable: • getMessage() • printStackTrace()



Create your own exception • class MyException extends Exception { }



++ Override method • It's okay for an overriding method to throw the same exceptions, narrower exceptions, or no exceptions. • it's okay for the overriding method to throw any runtime exceptions. 44

Error Objects of type Error are not Exception objects, although they do represent exceptional conditions. • ++ Also use throw keyword • Error is unchecked •

• You are not required to catch Error objects or Error subtypes. You can do it • No need to declare an Error 45

-- 5.5 -Common Exceptions & Errors 2.6 Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programmatically

Categories of Exceptions/Errors •





JVM exceptions Those exceptions or errors that are either exclusively or most logically thrown by the JVM.

• There's no way that the compiler can hope to find these problems before runtime. Programmatic exceptions Those exceptions that are thrown explicitly by application and/or API programmers. • Do not depend on the RuntimeException ++ 2.6 Recognize situations that will result in any of the following being thrown: • • • • •



AssertionError, StackOverflowError, ClassCastException, IllegalArgumentException, IllegalStateException,

ExceptionInInitializerError, NoClassDefFoundError, ArrayIndexOutOfBoundsException, NumberFormatException, NullPointerException.

++ Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programmatically. 47

Distinguish •

Checked exceptions • ++ are subclass's of Exception excluding class RuntimeException and its subclasses. • Checked Exceptions forces programmers to deal with the exception that may be thrown. • Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller



Unchecked exceptions • are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. • Unchecked exceptions , however, the compiler doesn't force the programmers to either catch the exception or declare it in a throws clause. • In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. • They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions).



Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be. 48

Throwable inheritance tree Object | |--> Throwable | |----> Error (Unchecked Exceptions) | | | |---> All other errors (Thrown by JVM) | | |----> Exception | |--> RuntimeException (Unchecked Exception) | | | |---> All other exceptions (Thrown by jVM) | |--> All other exceptions (Unchecked Exception) (Thrown programmatic or by API's programmer)

49

Common Errors •

StackOverflowError – Error - JVM Thrown -UN

• Thrown when a stack overflow occurs because an application recurses too deeply. • The most common way for this to occur is to create a recursive method. A recursive method is one that invokes itself in the method body. • runs out of space to store the call stack. •

NoClassDefFoundError – Error - JVM Thrown -UN

• Thrown when the JVM can't find a class it needs, because of a command-line error, a classpath issue, or a missing .class file. •

AssertionError - Error – Programmatic -UN

• Thrown when a statement's boolean test returns false. •

• The seven one-argument public constructors provided by this class ensure that the assertion error returned by the invocation. ExceptionInInitializerError - Error - JVM Thrown -UN

• Thrown when attempting to initialize a static variable or an initialization block. • Signals that an unexpected exception has occurred in a static initializer. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a 50 static variable.

Common Exceptions (1) •



ArithmeticException - RuntimeException -UN • Thrown when an exceptional arithmetic condition has occurred. • For example, an integer "divide by zero" throws an instance of this class. ++ NullPointerException() - RuntimeException - JVM Thrown -UN • Thrown when you attempt to access an object using a reference variable with a current value of null. • There's no way that the compiler can hope to find these problems before runtime. • • • • • •



Calling the instance method of a null object. Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array. Throwing null as if it were a Throwable value. Applications should throw instances of this class to indicate other illegal uses of the null object.

ClassCastException - RuntimeException - JVM Thrown - UN

• Thrown when attempting to cast a reference variable to a type that fails the IS-A test. 51

Common Exceptions (2) •



IllegalArgumentException - RuntimeException – Programmatic -UN • Thrown to indicate that a method has been passed an illegal or inappropriate argument. NumberFormatException -RuntimeException – Programmatic -UN •





++ subclass of IllegalArgumentException

• Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. IllegalStateException - RuntimeException – Programmatic -UN • Signals that a method has been invoked at an illegal or inappropriate time. • The Java environment or Java application is not in an appropriate state for the requested operation. • e.g., using a Scanner that's been closed. ArrayIndexOutOfBoundsException - RuntimeException - JVM Thrown -UN • Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. 52

-- 5.6 -Assertion Mechanism 2.3 Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions.

Assertion Expression Rules •

assert (expression1): expression2; • Expression1 - bollean • False: throws an AssertionError • True: go with the normal code

• Expression2 - system.out.println(xxxx) • Optional • ++ Must have a result of any value • A method with return

• Enabled when an application is being tested and debugged, but disabled when the application is deployed. 54

Enabling Assertions Compiling Assertion-Aware Code



Command Line

assert Is an Identifier

assert Is a Keyword

javac -source 1.3 TestAsserts .java

Code compiles with warnings.

Compilation fails.

javac -source 1.4 TestAsserts .java

Compilation fails.

Code compiles.

javac -source 1.5 TestAsserts .java

Compilation fails.

Code compiles.

javac -source 5 TestAsserts .java

Compilation fails.

Code compiles.

Javac TestAsserts .java

Compilation fails.

Code compiles.



Running with Assertions

Command Line

What It Means

java -ea / Java -enableassertions

Enable assertions.

java –da / Java -disableassertions

Disable assertions (default behavior of 1.5)

java -ea:com.foo.Bar

Enable assertions in class com.foo.Bar.

java -ea:com.foo…

Enable assertions in package com.foo and any of its subpackages.

java -ea -dsa

Enable assertions in general, but disable assertions in system classes.

java -ea -da:com.foo...

Enable assertions in general, but disable assertions in package com.foo and any of its subpackages.

55

Using Assertions Appropriately •

Don’t try to catch an AssertionError •



++ Don't Use Assertions to Validate Arguments to a Public Method • •



If you're going to try to recover from something, it should be an exception. Because public methods are part of your interface to the outside world, supposed to guarantee that any constraints on the arguments will be enforced by the method itself.

Do Use Assertions to Validate Arguments to a Private Method • •

Test your assumption you assume that the logic in code calling your private method is correct



++ Don't Use Assertions to Validate Command-Line Arguments



Do Use Assertions, Even in Public Methods, to Check for Cases that You Know are Never, Ever Supposed to Happen



++ Don't Use Assert Expressions that can Cause Side Effects •

Assert expression should leave the program in the same state it was in before the expression!

56

Strings • •

String, StringBuilder, and StringBuffer 3.1 Discuss the differences between the String, StringBuilder, and StringBuffer classes.

String Class •

++ Strings

Are Immutable Objects

• character in a string is a 16-bit Unicode character. • String s = new String("abcdef");  String s = “abcdef” • Every change need to reassign • • •

the JVM sets aside a special area of memory called the "String constant pool." String class is marked final String methods use zero-based indexes, • The substring() cut begin + end -1

58

• •

• •

Important Methods in the String Class (1)

public char charAt(int index) Returns the character located at the specified index public String concat(String s) Appends one String to the end of another (overloaded + and += operators also works) public boolean equalslgnoreCase(String s) Determines the equality of two Strings, ignoring case public int length() Returns the number of characters in a String • Distinguish from array’s attribute: Array.length;

• • •

public String replace(char old, char new) Replaces occurrences of a character with a new character public String Substring(int Begin) public String substring(int begin, int end) Returns a part of a String (cut end-1)

59

Important Methods in the String Class (2) • • • • •



• •

public String toLowerCase() Returns a String with uppercase characters converted public String toString() Returns the value of a String public String toUpperCase() Returns a String with lowercase characters converted public String trim() Removes whitespace from the ends of a String public int IndexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified substring. public int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. public boolean startsWith (String prefix) 60 public boolean endsWith (String prefix)

StringBuffer and StringBuilder Classes • •

Should be used when you have to make a lot of modifications to strings of characters A common use for StringBuffers and StringBuilders is file I/O when large, ever-changing streams of input are being handled by the program. • In these cases, large blocks of characters are handled as units, and StringBuffer objects are the ideal way to handle a block of data, pass it on, and then reuse the same memory to handle the next block of data.



StringBuffer vs. StringBuilder • • • • •

StringBuilder class was added in Java 5. StringBuilder has exactly the same API as the StringBuffer class, StringBuilder is not thread safe (methods are not synchronized ) StringBuilder will run faster Method calls can be chained to each other 61

Important Methods in StringBuffer & StringBuilder •

StringBuffer objects and StringBuilder objects can be changed. • public synchronized StringBuffer append(String s) • public StringBuilder delete(int start, int end) a substring is removed from the original object. (as same as substring) • public StringBuilder insert(int offset, String s) insert s into the original StringBuilder starting at the offset location • public synchronized StringBuffer reverse() • public String toString()



chained methods • Determine what the leftmost method call will return (let's call it x). • Use x as the object invoking the second (from the left) method. If there are only two chained methods, the result of the second method call is the expression's result. • If there is a third method, the result of the second method call is used to Invoke the third method, whose result is the expression's result 62

++ Exam watch • •

++ Be careful: String has no insert(), append(), delete(), reverse() ++ String always need assign the result to the reference, but StringBiffer/StringBuilder needn’t • s.concat(“xx”);  will be lost if there is not: s = s.concat(“xx”);



++ String s = “xx”; is not String x = new String(“xx”); the new keyword will create a normal object, not put the string into the constant pool; • String s = “xx”; • String s1 = “xx”;  s1== s is true • String s2 = new String(“xx”);  s2 ==s is false

• •

++ the array has attribute length, String has method length(); StringBuffer/StringBuilder do not have equals(), their equals() means ==

63

-- 6.1 -File Navigation and I/O 3.2 Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader, BufferedWriter, File, FileReader, FileWriter, and PrintWriter.

File I/O • • • • • •

Always need import java.io.*; All the I/O stuff must be in a try/catch. Every thing can throw an IOException. Don’t forget close(); Chain BufferedWriter/ BufferedReader and FileWriter/FileReader for efficiency. File object is not actual content of the file. Use split() to split a String into individual tokens 65

I/O classes summary (1) •

File • The API says that the class File is "An abstract representation of file and directory pathnames." • lets you manage (add, rename, and delete) files and directories



FileReader • used to read character files. Its read() methods are fairly low-level, allowing you to read single characters, the whole stream of characters, or a fixed number of characters. • usually wrapped by higher-level objects such as BufferedReaders, which improve performance and provide more convenient ways to work with the data. 66

I/O classes summary (2) •

BufferedReader • used to make lower-level Reader classes like FileReader more efficient and easier to use. • Compared to FileReaders, BufferedReaders read relatively large chunks of data from a file at once, and keep this data in a buffer. When you ask for the next character or line of data, it is retrieved from the buffer, which minimizes the number of times that timeintensive, file read operations are performed. • In addition, BufferedReader provides more convenient methods such as readLine(), that allow you to get the next line of characters from a file.



File Writer • used to write to character files. • Its write() methods allow you to write character(s) or Strings to a file. • FileWriters are usually wrapped by higher-level Writer objects such as BufferedWriters or PrintWriters, which provide better performance and higher-level, more flexible methods to write data. 67

I/O classes summary (3) •

BufferedWriter • used to make lower-level classes like FileWriters more efficient and easier to use. • Compared to FileWriters, BufferedWriters write relatively large chunks of data to a file at once, minimizing the number of times that slow, file writing operations are performed. • In addition, the BufferedWriter class provides a newLine() method that makes it easy to create platform-specific line separators automatically.



PrintWriter • has been enhanced significantly in Java 5. Because of newly created methods and constructors (like building a PrintWriter with a File or a String), you might find that you can use PrintWriter in places where you previously needed a Writer to be wrapped with a FileWriter and/or a BufferedWriter. • New methods like format(),printf(), and append() make PrintWriters very flexible and powerful. 68

Write/Read a file •

createNewFile() and mkDir() add entries to your file system. • • • • •

• • • •

File f = new File (“xxxx.txt”); File dir = new File (“xxxxdir”); dir.mkdir(); File myFile = new File(dir, "xxxx.txt "); myFile.createNewFile();

BufferedWriter writer = new BufferedWriter(new FileWriter(myFile )); Writer.close(); BufferedReader reader = new BufferedReader(new FileReader(myFile)); Reader.close(); 69

Combining I/O classes • •

java.io package contains about 50 classes, 10 interfaces, and 15 exceptions File: File, String • createNewFile() ,delete() ,exists() , isDirectory() , isFile() , list() , mkdir() , renameTo(File f)



FileWriter: File, String • close() ,flush() ,write()



BufferedWriter: Writer • close() ,flush() ,newLine() , write()



PrintWriter: Writer • close() , flush(), format()*, printf()*, print(), println() ,write()



FileReader: File, String • read()



BufferedReader: Reader • read(), readLine()

70

java.io.File •

java.lang.Object   java.io.File

• • • • • •

boolean exist(); // does the file exist boolean canWrite(); // can the file be written to boolean canRead(); // can the file be read boolean isFile(); // does it represent a file boolean isDirectory(); // or a directory boolean renameTo(File f) //Renames the file

• 71

java.io.FileReader •

throws IOException throws FileNotFoundException



java.lang.Object



 java.io.Reader  java.io.InputStreamReader   java.io.FileReader



java.lang.Object  java.io.Reader  java.io.BufferedReader

72

java.io.FileWriter •

throws IOException



java.lang.Object  java.io.Writer  java.io.OutputStreamWriter   java.io.FileWriter



java.lang.Object  java.io.Writer  java.io.BufferedWriter



java.lang.Object  java.io.Writer  java.io.PrintWriter 73

FilenameFilter •

+ java.io.FilenameFilter is an interface which has one method: • boolean accept(File dir, String name) • can pass FilenameFilter to File's list() or listFiles() • File xxxdir = new File(“folder”); • String[] a = xxxdir.list(); • File[] b = xxxdir.listFile();

• list() --> String[], including direction and files • listFiles() --> File[] 74

Console (1) •

java.lang.Object  java.io.Console



Make easy to accept input from and output to command line • • • •

import java.io.Console; Console c = System.console(); String readLine() char[] readPassword(): for security purpose

75

Console (2) •

All the methods are: • • • •

Void flush() Console format(String fmt, Object... args) Console printf (String fmt, Object... args): Reader reader() • Retrieves the unique Reader object associated with this console.

• PrintWriter writer(): • Retrieves the unique PrintWriter object associated with this console.

• • • •

String readLine() String readLine(String fmt, Object... args): char[] readPassword() char[] readPassword(String fmt, Object... args) • Reads a password or passphrase from the console with echoing disabled

76

Related Documents

Part 2
April 2020 27
Part 2
November 2019 32
Part 2
November 2019 31
Part 2
May 2020 25
Part 2
December 2019 33
Part 2
December 2019 32

More Documents from "ossama"