String

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

split the string "J#H#P" on #

"J#H#P".split("#")

For example, the URL string "http:www.google.com/index.html" would cause a MalformedURLException runtime error because _ are required after the colon (:).

//

For the next() method, no conversion is performed. If the token does not match the expected type, a runtime exception java.util... will be thrown.

InputMismatchException

enter a URL

String URLString = new Scanner(System.in).next();

Can it be read?

file.canRead()

Last modified on (plus date formatted)

new java.util.Date(file.lastModified())

Close the file

output.close()

to convert a double value 5.44 to a string, use __

tring.valueOf(5.44)

Java is fun matches Java*

"Java is fun".matches("Java.*")

For the next() method, no conversion is performed. If the token does not match the expected type, a runtime exception java.util..... will be thrown.

InputMismatchException

A _ is thrown if the URL string has a syntax error

MalformedURLException

Write formatted output to the file

Output.print()

The following statement creates a String object message for the string literal "Welcome to Java":

String message = new String("Welcome to Java");

output.print("John T Smith "); output.println(90); output.print("Eric K Jones "); output.println(85); Does

Writes to file

...MalformedURLException... System.out.println("Invalid URL");

catch (java.net.MalformedURLException ex) {

stringBuilder.reverse()

changes the builder to avaJ ot emocleW.

The _ method returns the character at a specific index in the string builder.

charAt(index)

This method is similar to the printf method except that the format method returns a formatted string, whereas the printf method _ a formatted string.

displays

Is it hidden?

file.isHidden()

You can use the _method in the Character class to check whether character ch is a letter or a digit.

isLetterOrDigit(ch)

You can use ___ to create a String- Builder with a specified initial capacity. By carefully choosing the initial capacity, you can make your program more efficient.

new StringBuilder(initialCapacity)

Returns an array of strings consisting of the substrings split by the delimiter.

split(delimiter)

append Java to welcome to 'Welcome to '

stringBuilder.append("Java");

If the capacity is always larger than the actual length of the builder, the JVM will never need to reallocate memory for the builder. On the other hand, if the capacity is too large, you will waste memory space. You can use the __ method to reduce the capacity to the actual size.

trimToSize()

... java.io.PrintWriter output = new java.io.PrintWriter(file);) { Example of auto close

try (

After the block is finished, the resource's close() method is automatically invoked to close the resource. Using __ can not only avoid errors but also make the code simpler.

try with resources

For example, the following statement creates a URL object for http://www.g.com/index.html.

try { URL url = new URL("http://www.g.com/index.html"); }

Another way of converting a number into a string is to use the overloaded static

valueOf method

Scanner input = new Scanner(url.openStream()); ....more to read?

while (input.hasNext()) {

The String class has _ constructors and more than _ methods for manipulating strings.

13, 40

Constructs an empty string builder with capacity 16.

StringBuilder()

The file name is a string. The File class is a _ class for the file name and its direc-tory path. For example, new File("c:\\book") creates a _ for the directory c:\book,

Wrapper, File object

Here _ represents a single digit, and _ represents three digits.

\\d, \\d{3}

Create a file instance x.txt using full io

java.io.File file = new java.io.File("x.txt");

For an application program to read data from a URL, you first need to create a URL object using the _ class with this constructor:

java.net.URL

Both methods next() and nextLine() read a string. The next() method reads a string delimited by delimiters, and __ reads a line ending with a line separator

nextLine()

Returns a new string that replaces all matching characters in this string with the new character.

replace(old, new)

The _ method sets the length of the string builder.

setLength(newLength)

You can also use the getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method to copy a substring of the string from index srcBegin to index srcEnd-1 into a character array dst starting from index dstBegin. For example, the following code copies a substring "3720" in "CS3720" from index 2 to index 6-1 into the character array dst starting from index 4. char[] dst = {'J', 'A', 'V', 'A', '1', '3', '0', '1'}; .... (Thus, dst becomes {'J', 'A', 'V', 'A', '3', '7', '2', '0'}.)

"CS3720".getChars(2, 6, dst, 4);

"Java".equals("Java"); say this with matches

"Java".matches("Java"); (However, the matches method is more powerful. )

returns a new string, WAlcomA.

"Welcome".replace('e', 'A')

returns a new string, WABlcome.

"Welcome".replaceFirst("e", "AB")

For example, the following statement returns a new string that replaces a, b, or # in a+b$#c with the string NNN.

"a+b$#c".replaceAll("[ab#]", "NNN");

The following statement evaluates to true. "440-02-4534".matches

("\\d{3}-\\d{2}-\\d{4}")

If the builder's capacity is exceeded, the array is replaced by a new array. The new array size is _ (the previous array size + 1).

2 x

The StringBuilder class has _constructors and more than _ methods for managing the builder and modifying strings in the builder.

3, 30

Suppose a text file named test.txt contains a line 34 567. After the following code is executed, Scanner input = new Scanner(new File("test.txt")); int intValue = input.nextInt(); String line = input.nextLine(); intValue contains _ and line contains

34, ' ', 5, 6, 7

A list to store elements.

ArrayList (ArrayList<Object>)

A resource is declared and created followed by the keyword try. Note that the resources are enclosed in the parentheses (lines 9-12). The resources must be a subtype of __ such as a PrinterWriter that has the close() method

AutoCloseable

java.io.PrintWriter output = new java.io.PrintWriter(file); Does

Create a file

The _ 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 File class contains the methods for obtaining file and directory properties and for renaming and deleting files and directories, as shown in Figure 12.6. However, the File class does not contain the methods for reading and writing file contents.

File class

A __ is a representation of a possible pathname of a file or a directory in a file system. It provides access to the file or directory, if it exists, and can be used in creating it if it doesn't.

File object

Use the Scanner class for reading text data from a file and the __ class for writing text data to a file.

PrintWriter

You can create _ objects for writing text to any file using print, println, and printf (lines 13-16).

PrintWriter

First, you have to create a PrintWriter object for a text file as follows:

PrintWriter output = new PrintWriter(filename);

To read from the keyboard, you create a Scanner for System.in, as follows:

Scanner input = new Scanner(System.in);

// Create a File instance java.io.File file = new java.io.File("scores.txt"); // Create a Scanner for the file ...

Scanner input = new Scanner(file);

Create a Scanner for the file

Scanner input = new Scanner(file);

After a URL object is created, you can use the openStream() method defined in the URL class to open an input stream and use this stream to create a Scanner object as follows:

Scanner input = new Scanner(url.openStream());

for user to enter a url

String url = input.nextLine();

To convert an array of characters into a string, use the _ constructor or the _method

String(char[]), valueOf(char[]) method

the following statement constructs a string from an array x using the String constructor.

String(x[])

If a string does not require any change, use _ rather than _.

String, StringBuilder (Java can perform some optimizations for String, such as sharing interned strings)

Using _ is more efficient if it is accessed by just a single task, because no synchronization is needed in this case.

String-Builder

The next statement constructs a string from an array x using the valueOf method.

String.valueOf(x[]);

Use _ not _ if the class might be accessed by multiple tasks concurrently, because synchronization is needed in this case to prevent corruptions

StringBuffer, StringBuilder

The StringBuilder class is similar to _ except that the methods for modifying the buffer in _ are _ which means that only one task is allowed to execute the methods.

StringBuffer, synchronized

Constructs a string builder with the specified capacity.

StringBuilder(capacity)

Constructs a string builder with the specified string.

StringBuilder(string)

if (file.exists()) { System.out.println("File already exists"); .... }

System.exit(0);

is a standard Java object for the console output.

System.out

System.out.printf(format, item1, item2, ..., itemk); is equivalent to

System.out.print( String.format(format, item1, itemk));

You can read data from a file or from the keyboard using the Scanner class. You can also scan data from a string using the Scanner class. For example, the following code Scanner input = new Scanner("13 14"); int sum = input.nextInt() + input.nextInt(); System.out.println("Sum is " + sum); displays...

The sum is 27

The directory separator for Windows is a backslash (\). The backslash is a special char-acter in Java and should be written as __ in a string literal

\\

An _ (or full name) contains a file name with its complete path and drive letter

absolute file name

Exception handling enables a method to throw an exception to its _.

caller

The _method returns the current capacity of the string builder. The capacity is the number of characters the string builder is able to store without having to increase its size.

capacity()

.... IOException.... System.out.println("I/O Errors: no such file");

catch (java.io.IOException ex) {

the following statement converts the string Java to an array (to array 'chars')

char[] chars = "Java".toCharArray();

Constructing a File instance does not create a file on the machine. You can create a File instance for any file name regardless whether it exists or not. You can invoke the __method on a File instance to check whether the file exists

exists()

Can it be written?

file.canWrite()

Does it exist?

file.exists()

Absolute path is

file.getAbsolutePath()

Is it absolute?

file.isAbsolute()

Is it a directory?

file.isDirectory()

Is it a file?

file.isFile()

The line-separator string is defined by the system. It is \r\n on Windows and \n on UNIX. To get the line separator on a particular platform, use String lineSeparator = System.....("line.separator");

getProperty

Note that the _ prefix is required for the URL class to recognize a valid URL. It would be wrong if you replace line 2 with the following code: URL url = new URL("www.google.com/index.html");

http://

while (..:) { String firstName = .... String mi = input.next(); ....

input.hasNext() input.next();

Because strings are immutable and are ubiquitous in programming, the JVM uses a unique instance for string literals with the same character sequence in order to improve efficiency and save memory. Such an instance is called an __.

interned string

You can use the File class's _ method to check whether the object represents a directory, and the _ method to check whether the object represents a file.

isDirectory(), isFile()

replaces all the occurrences of StringBuilder by StringBuffer in the file FormatString.java and saves the new file in t.txt.

java ReplaceText FormatString.java t.txt StringBuilder StringBuffer

The file name and strings are passed as command-line arguments as follows:

java ReplaceText sourceFile targetFile oldString newString

The __ class can be used to create a file and write data to a text file. First, you have to create a PrintWriter object for a text file as follows:

java.io.PrintWriter

Often you will need to write code that validates user input, such as to check whether the input is a number, a string with all lowercase letters, or a Social Security number. How do you write this type of code? A simple and effective way to accomplish this task is to use the _.

regular expression

A _ is in relation to the current working directory. The complete directory path for a relative file name is omitted. For example, Welcome.java is a rela-tive file name. If the current working directory is c:\book, the absolute file name would be c:\book\Welcome.java.

relative file name

Returns a new string that replaces all matching substrings in this string with the new substring.

replaceAll(old, new)

Returns a new string that replaces the first matching substring in this string with the new substring.

replaceFirst(old, new)

StringBuilder stringBuilder1 = stringBuilder.reverse(); reverses the string in the builder and assigns the builder's reference to stringBuilder1. Thus, stringBuilder and stringBuilder1 both point to the __.

same object

You can also delete characters from a string in the builder using the two delete methods, reverse the string using the reverse method, replace characters using the replace method, or set a new character in a string using the _ method.

setCharAt

changes the builder to Welcome Java (8, 11)

stringBuilder.delete(8, 11)

changes the builder to Welcome o Java (8)

stringBuilder.deleteCharAt(8)

This code inserts "HTML and " at position 11 in stringBuilder (just before the J).

stringBuilder.insert(11, "HTML and ");

changes the builder to Welcome to HTML (11 15)

stringBuilder.replace(11, 15, "HTML")

sets the builder to welcome to Java.

stringBuilder.setCharAt(0, 'w')

Invoking the constructor of PrintWriter may throw an I/O exception. Java forces you to write the code to deal with this type of exception. For simplicity, we declare __ in the main method header

throws IOException

Strings are not arrays, but a string can be converted into an array, and vice versa. To convert a string into an array of characters, use the _ method.

toCharArray

The nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), next-Double(), and next() methods are known as __

token-reading methods

The nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), next-Double(), and next() methods are known as _

token-reading methods (because they read tokens separated by delimiters)


Set pelajaran terkait

Digital & Content Marketing Practice Questions Exam 2

View Set

Agents to control blood glucose levels prepu

View Set

Chapter 66: Shock, Sepsis, and Multiple Organ Dysfunction Syndrome

View Set