- What is the size in bytes of each of these datatypes?
int double char boolean
Ans: 4; 8; 2; 1
- Write a for loop that prints the odd numbers from 99 to 1 in descending order. ANs:
for(int n = 99; n >= 1; n -= 1) {
System.out.println(n);
}
- How does a switch statement work? Ans:
switch(n) {
case 1: word = "one"; break;
case 2: word = "two"; break;
case 3: word = "three"; break;
default: word = "other";
}
- What is the difference between a static method and an instance method?
Ans: A static method is called from a class; an instance method is called from an object.
- How does the toString method work for a class? What does
@Override do?
Ans: The toString method for a class returns a
String representation of an object. @Override means that
the method is overriding a method in the base class of the current class.
- Create an array that contains these strings:
ibm oracle microsoft google
// Ans:
String[ ] arr = {"ibm", "oracle", "microsoft", "google"};
- Create an ArrayList collection that contains the same strings as the array in Problem 6. Ans:
ArrayList<String> col = new ArrayList<String>( );
for(String s : arr) {
col.add(s);
}
- Explain the difference between a derived class and an interface. What is an abstract class?
Ans: A derived class inherits instance variables and methods from a base class. It can override (replace)
base class class methods in the current class. An interface specifies required methods, but does not define them.
The class that implements the interface supplies definitions for the required methods.
An abstract class cannot be instantiated. It can specify abstract methods which must be overridden in the
derived class. A class can only have one base class, but a class can implement many interfaces.