Chapter:Classes - Other keywords - Exercises

From Juneday education
Jump to: navigation, search

There are just a few exercises in the form of questions for this chapter! But it's good if you read the links with further reading. It is good to get familiar with the Java Language Specification :-) It is a great source when you think in the lines of "I wonder how this works..." or "what are the rules for..." when programming in Java.

Questions

Reserved words or not?

Read JLS 3.9. Keywords and answer which one of the following are reserved words, which are literals, which are reserved but not in use and which are in fact not keywords at all (and thus valid names for e.g. variables)?

  • short
  • null
  • const
  • final
  • res
  • result
  • val
  • value
  • false

Expand using link to the right to see a suggested answer/solution.

  • short - Reserved word (a primitive type)
  • null - Reserved word (the null literal)
  • const - Reserved but not in use
  • final - Reserved word (a modifier)
  • res - Not reserved - perfectly legal (albeit short) variable name
  • result - Not reserved - perfectly legal variable name
  • val - Not reserved - perfectly legal variable name
  • value - Not reserved - perfectly legal variable name
  • false - Reserved word (a boolean literal)

What does the compiler tell you?

Try to create variables in a class with the words in the list. What does the compiler error for the reserved words above tell you?

Expand using link to the right to see a suggested answer/solution.

The compiler error is error: <identifier> expected. Here's an example class and the compiler errors:

public class Reservation {
  int short;     //Reserved word (a primitive type)
  int null;      //Reserved word (the <code>null</code> literal)
  int const;     //Reserved but not in use
  int final;     //Reserved word (a modifier)
  int res;       //Not reserved - perfectly legal (albeit short) variable name
  int result;    //Not reserved - perfectly legal variable name
  int val;       //Not reserved - perfectly legal variable name
  int value;     //Not reserved - perfectly legal variable name
  int false;     //Reserved word (a boolean literal)
}
/*
Reservation.java:2: error: <identifier> expected
  int short;     //Reserved word (a primitive type)
     ^
Reservation.java:3: error: <identifier> expected
  int null;      //Reserved word (the <code>null</code> literal)
     ^
Reservation.java:4: error: <identifier> expected
  int const;     //Reserved but not in use
     ^
Reservation.java:5: error: <identifier> expected
  int final;     //Reserved word (a modifier)
     ^
Reservation.java:10: error: <identifier> expected
  int false;     //Reserved word (a boolean literal)
     ^
5 errors
*/

Links

Further reading

Where to go next

Next page is: Classes_-_Strings_are_immutable

« PreviousBook TOCNext »