Java Questions 11 - 20  «Prev Next»

Java Classes and References Variables Questions

  1. What is a class in Java?
    Answer:
    A class is a user-defined type that responds to a number of different service requests.
  2. What is a reference variable in Java?
    Answer:
    When a variable (Student y) refers to an instance (object) of class Student.
    Reference variable is one which holds reference(points to) to a an instance(object) of a class.
  3. How many primitive types are there in Java?
    Answer:
    1) int 2) double 3) float 4) byte 5) short 6) long 7) char 8) boolean
  4. Why can't primitive types be reference variables in Java?
    Answer:
    Primitive types are not reference types, that is, they do not refer to objects. In Java, only objects can be reference types.
  5. What are the naming conventions for reference variables in Java?
    Answer:
    Reference variables should use this declaration standard.
    Course prerequisiteOfThisCourse;
    Professor facultyAdvisor;
    
    Naming Conventions
    Package names - lowercase.for.all.components
    Class and Interface names - CaptializedWithInternalWordsCaptialized
    Method names - firstWordLowercaseButInternalWordsCapitalized()
    Variable names - firstWordLowercaseButInternalWordsCaptialized
    Constants - UPPER_CASE_WITH_UNDERSCORES
    

  6. Why is a reference variable sometimes called a handle on an object?
    Answer:
    A reference variable is sometimes said to hold onto an object.
  7. How is a reference in Java similar to a pointer in C?
    Answer:
    A reference refers behind the scenes to the memory location address where a particular object is stored.
  8. Describe a way to get a reference variable to release its handle on an object?
    Answer:
    Set the reference variable to the value null.
  9. What is garbage collection?
    Answer:
    If there are no remaining active references to an object, it becomes a candidate for garbage collection.
  10. When does garbage collection occur?
    Answer:
    Garbage collection occurs whenever the JVM determines that the application is getting low on free memory.
  11. How can you explicitly request garbage collection to occur?
    Answer:
    Runtime.getRuntime().gc();
    

    Caution: The precise moment of when garbage collection occurs is out of the programmer’s control.
    An object becomes eligible for Garbage Collection when its last live reference disappears.