Strings, Exceptions, and Files Flashcards
How do you change the case of a String?
String s = “string”;
s.toLowerCase();
s.toUpperCase();
What does String1.compareTo(String2) do?
it tells you which is first in “alphabetical order”. “Less” or “greater” is determined by the numeric codes (ASCII or Unicode) of the characters in that position. Uppercase is always less than lowercase
How could you find one String within another?
string1.indexOf(string2);
How can you remove leading/trailing whitespace from a String?
s.trim();
How could you find what characters are between two indices?
String1.substring(start, end)
start is the position of the first character you want
end is the position of the first character you don’t want
What does String[] split(String) do?
break up a String into an array of Strings at the positions of the given substring
“Test 12 34”.split(“ “) gives {“Test”, “12”, “34”}
What are Exceptions?
represent problems that arise during execution, which a program might want to deal with. Exceptions are objects that give information about what went wrong and where in the program it went wrong.
What are some examples of exceptions?
- 5/0 gives an Arithmetic Exception
- array[-1] = 0 gives an
ArrayIndexOutOfBoundsException - Integer.parseInt(“Not a number”) gives a NumberFormatException
What are the methods that every exception object has?
- String getMessage() - find more about what happened
- void printStackTrace() - print out where the program was at the time this exception object was created
- String toString() - the name of the exception and its message
What are Errors in Java
As opposed to Exceptions, Errors are more serious problems that a program is not supposed to manage/handle. When it happens, the program will terminate with a description of the error.
What happens when you use an Exception?
When something goes wrong, you can “throw” an exception. This object is now automatically returned up the stack, immediately terminating all of these methods until it hits something that “catches” it.
How do you use an Exception in a method?
all methods that throw an exception or call a method that does this have “throws Exception” at the end of the signature unless the method catches the exception itself.
What is the format of a try-catch?
try {
… statements
}
catch(TypeOfException e) {
… do this if an exception happens
}
catch(OtherTypeOfException ae) { … }
finally {
… do this every time, whether try successfully completed or an exception was thrown and caught
}
… continue unless some un-caught exception occurs
What are RuntimeExceptions?
unchecked exceptions. You don’t need to catch them, or declare in your method signature that it could throw them. RuntimeExceptions are thrown when the programmer makes a mistake and calls a method incorrectly. They happen during runtime
What are checked exceptions?
Types of exceptions that must be handled wherever they may occur in your program; otherwise, your program will not compile