Java Questions 41 - 50  «Prev  Next»

Instance Variables and Primitives(Questions)

  1. What happens to instance variables each time a new instance is created?
    Answer: Instance variables are initialized to a default value each time a new instance is created.
  2. What are the default values for Primitives and Reference Types ?
    Answer:
    1. Object reference = null
    2. byte, short, int, long : 0
    3. float, double: 0.0
    4. boolean: false
    5. char
    6. (TJH) It looks like a char is assigned nothing or blank.
  3. What happens when an object variable has not been explicitly initialized with an assignment?
    Answer:
    The value of the instance variable will be null.
  4. What does it mean when the value of an object is null?
    Answer:
    A null value means the reference variable is not referring to any object on the heap.
  5. How can you check whether an object has been instantiated?
    Answer:
    By using the keyword null and using the following code.
    String s = b.getTitle();
    If (s != null){ 	
    String t = s.toLowerCase(); 
    }
    
  6. What happens if an array instance variable is not explicitly initialized?
    Answer:
    If an array instance variable is not explicitly initialized we will have a value of null.
    public class ArrayTest {
     static Integer	arr[];
     public static void main(String[] args) {
      System.out.println(arr);
     }
    }
    
  7. Are array elements always given default values?
    Answer:
    Yes.
  8. What will be value of the object elements of an array if they are not initialized?
    Answer:
    If the elements of an array are objects, the object reference elements will equal null if they are not initialized individually with values.
  9. Why are local variables called automatic variables?
    Answer:
    "Automatic" is just another term for "local variable". Local variables automatically cease to exist when the execution of the block in which they are declared completes.
  10. Do you have to initialize an automatic variable?
    Answer:
    Yes. A local variable must be assigned a value before it is used or else a compiler error will occur.
    Note: Byte, short, int and long are initialized to zero.