Sunteți pe pagina 1din 3

.File IO 1.

Write a single line of code that instantiates a file Scanner to read from a file
called numbers.dat. Scanner fileScanner = new Scanner(new
FileInputStream(numbers.dat));
2. Which methods do we use to read values from a
file using a Scanner object? nextLine(), nextInt(), nextDouble(), nextBoolean(), etc...
3. Write a single line of code that instantiates a file PrintWriter to write to a file called
names.txt. PrintWriter fileWriter = new PrintWriter(new
FileOutputStream(names.txt));
4. Which methods do we use to write values to a file
using a PrintWriter object? print() and println()
5. What Exception can be thrown when
instantiating a Scanner or PrintWriter for file IO? Is this exception checked or unchecked?
FileNotFoundException, checked
6. Write a segment of code that prints the contents
of a file to the Java console. Assume you have a file Scanner called myFileScanner. while
(myFileScanner.hasNextLine()) { System.out.println(myFileScanner.nextLine()); }
7. Write a try-catch-finally block that correctly opens a PrintWriter object and closes it
after use. Your PrintWriter should write to a file called output.txt. PrintWriter writer =
null; ....try { writer = new PrintWriter(new FileOutputStream(output.txt)); }
catch (FileNotFoundException ex) { System.out.println(ex.getMessage()); } finally
{ if (writer != null) { writer.close(); } }
8. True or false The File class can be used to
represent both files and directories. true
Recursion 1. What are the 3 rules of recursion? Include a base case, Approach your
base case, Make your recursive call , TRUST THAT IT WORKS! 2. What is the Java call
stack and why is it important? The java call stack manages the variables and return
types associated with an method calls. It is important to understand how methods
are added or removed from the stack during a recursive method call.
3. Suppose you had the following recursive method. public void foo(int n) { //base case if (n
== 30) { return; } else { //print n System.out.println(n); //recurse foo(n + 5); } } What is
wrong with the following code segment? What do we call this behavior? foo(21); This will
skip over the base case. This is infinite recursion!
.Abstract Classes 1. For the following Fruit class, add an abstract method called
isHealthy() with a return type of boolean. public abstract class Fruit { public abstract
boolean isHealthy(); }
2. Suppose your are given the following class. public abstract
class Ship { private int maxCapacity; public Ship(int myMaxCapacity) { maxCapacity =
myMaxCapacity; } } What is wrong with the following code segment? Ship titanic = new
Ship(1000); You cannot instantiate an abstract class. 3. Circle any of the following that
are true concerning abstract classes. a. Abstract classes cannot have constructors b. You
cannot instantiate an abstract class c. An abstract class can only include one abstract
method d. Abstract classes cannot contain fields e. A child class of an abstract class
must implement all abstract methods, or it must also be marked abstract 4. True or false A
class can choose to not implement an abstract method that has been inherited. true
.Console Programming 2. What types of values can you send as an argument to
System.out.print() and System.out.println()? most of the primitive types, and object
types
3. Can you pass object (reference) types to the System.out.print() and
System.out.println() methods? What output is sent to the console? Yes, it will print out the
toString() method of the object.
4. Write a single line of code that creates a Scanner
object to read from the Java console. Scanner myScanner = new Scanner(System.in);
5. What method do we call on a Scanner object to read a String from the Java console?
nextLine() 6. Write a loop that prompts the user for three numbers and prints them to the
Java console. Assume you have access to a Scanner object called myScanner. for (int i =
1; i <= 3; i++) { System.out.println(Please enter a number: ); int number =
myScanner.nextInt(); System.out.println(The number you entered was: +
number); }
.The Random Class 1. What is wrong with the following code segment? Random rand =
new Random(); //prints a random number between 1 and 90 .
System.out.println(rand.nextInt(90)); The comment is incorrect. This will print a number
between 0 and 89. 2. What does it mean that the random class generates pseudo-random
numbers. Computers have difficult generating truly random numbers. The numbers

generated by the Random class are pulled from a series of numbers generated by a
mathematical algorithm. The only random part about the routine is where to begin
retrieving numbers from the series. 3. Write a segment of code that prints random
numbers between 5 and 15. Assume you have access to a Random object
calledmyRandom.System.out.println(myRandom.nextInt(11) + 5);
String Manipulation 1. What does it mean when we say that the String class is immutable?
Be as clear as possible when answering this question. A string object cannot be changed
once it has been created.
Exceptions1. Write a single line of code that throws an IllegalStateException with the
following message: Stop that! Stop that right now! throw new
IllegalStateException(Stop that! Stop that right now!); 2. Write a try-catch block that
surrounds the given line of code and catches the ClassCastException type. You can leave
your catch block empty. public void foo(Object anObject) { try { //might throw an
exception, surround me

with a try-catch! .....MyClass newObject = (MyClass)anObject } ....catch


(ClassCastException ex) {
..System.out.println(ex.getMessage()); } } 3. Is it better to have multiple catch blocks for
different exception types, or instead to include a single catch block for the Exception type?
Make an argument about the pros/cons of either choice. Using multiple catch blocks gives
you the flexibility to response to different exceptions in different ways. A catch
block for Exception gives you the peace of mind that all exceptions that are thrown
will be caught. 4. The following code does not compile. Explain why. try { //an exception
might be thrown here! } catch (RuntimeException ex) { //handle RuntimeException
here}catch(InputMismatchException ex) { //handle InputMismatchException here } catch
(NumberFormatException ex) {//handle NumberFormatException here }
Your catch
blocks should have more specific exceptions before less specific exceptions (from
top to bottom). The two bottom catch blocks are unreachable code. 5. What class do
all unchecked exceptions inherit from? The RuntimeException class.
6. What is the
difference between checked and unchecked exceptions? Be as clear as possible when
answering this question. In JavaSW, the Exception class is a subclass of Throwable.
The RuntimeException class is a subclass of Exception. If an exception is a subclass
of Exception but not RuntimeException, it is a checked exception. A checked
exception needs to either be caught in a method (in a try/catch block), or the
method needs to specify that it can throw the exception on further (via a throws
clause of a method declaration). If an exception is a subclass of RuntimeException,
it is an unchecked exception. An unchecked exception can be caught, but it does
not have to be. Thus, it is 'unchecked'. 7. What is the catch or declare rule? Be as clear
as possible when answering this question. The catch or declare rule ensures that
checked exceptions are surrounded by a try-catch block, otherwise the method
containing the checked exception must be declared to throw that exception. 8. Write
a custom exception class for situations where you would not want an numeric argument to be
negative. Call the class NegativeArgumentException and include both a default and
parameterized constructor. public class NegativeArgumentException extends
RuntimeException { public NegativeArgumentException() { super(Negative
arguments are not accepted!); } public NegativeArgumentException(String
message) { super(message); } } 9. What is the output of the following code segment? try
{ String message =null;//printourmessage....System.out.println(message.toString()); //print
that were all done ....System.out.println(Done!); } catch (NullPointerException ex)
{ System.out.println(An error occurred.); } finally { System.out.println(What happens
here?); } An error occurred. What happens here? ObjectOrientedPrograming1. Name
two differences between methods and constructors. Constructors have no return type.
Constructors have the same name as the class they are contained within. 3. Suppose
you are given a field called favoriteMovie. Write a getter for this field. public String

getFavoriteMovie() { return favoriteMovie; } 4. Suppose you are given a field called


leastFavoriteSong. Write a setter for this field. public void setLeastFavoriteSong(String
newFavorite) { leastFavoriteSong = newFavorite; } 5. What is the purpose of a
toString() method? To return a string representation of an object. 9. What technique is
shown in the following constructors? public class BankAccount { private String accountHolder;
private int accountNumber; public BankAccount() { this(0, No Name); } public
BankAccount(int acctNumber) { this(acctNumber, No Name); } public BankAccount(int
acctNumber, String acctHolder) { accountHolder = acctHolder; accountNumber =
acctNumber; } } Constructor chaining. 10. What is wrong with the following constructors?
public class Pet { private String type; private String name; public Pet() {
System.out.println(You called a default constructor!); this(No Type, No Name); }
public Pet(String animalType, String animalName) { System.out.println(You assigned your
type and name fields!); type = animalType; name = animalName; } } Calling another
constructor using this() or super() must be the first line of code in your constructor.
Inheritance 1. What is the primary benefit of inheritance? Code reuse. This reduces code
redundancy. 3. Which keyword do we use to call our parents constructor? super 8. Given
the class below, name two methods we can call on Computer objects. public class Computer {
private String processorType; private int numberOfProcessorCores; //nothing more here } Any
method from the Object class: toString(), equals(), getClass(), hashCode(), etc... 9.
What is the difference between overloading and overriding? Be as clear as possible when
answering this question. Method overriding is when a child class redefines the same
method as a parent class, with the same parameters. Method overloading is defining
several methods in the same class, that accept different numbers and types of parameters.
StringManipulattion1. What does it mean when we say that the String class is immutable?
Be as clear as possible when answering this question. A string object cannot be changed
once it has been created.

S-ar putea să vă placă și