☰ Contents The Main Thing

Just in Case

Student: I have another question.
Prof: Go for it!
Student: The way you write names seems to be very specific, and we talked about String being capitalized and int not being capitalized. Then things like method and variable names seem to start lowercase and become capital?
Prof: Right! This is a good time to answer that, while we’re looking at some Java-specific details. This is called the casing style of identifiers. “Identifier” is a word for a name in a program; it could be a method name or a definition name or a class name, those are all identifiers. There are both rules and conventions around identifiers.
Student: What’s the difference between a rule and a convention?
Prof: So identifiers, in Java, have to start with a letter and can only contain letters, numbers and a few special characters like underscores (_). So france and image2 and MyFavoriteNumber are all valid identifiers, while 2kool4u and my-favorite-number are invalid; java will simply give an error if you use them as names. Those are the rules in Java.
Student: OK, so what’s a convention?

Prof: In Java, there are a few conventions, which are guidelines that most Java programmers follow to make their code more predictable to read. There are two that we have seen:

  • Method names, parameter names, and definition names are what’s called camelCase. That is, they start with a lowercase letter, and any words after the first get a capital letter. The camel comes from the idea that many names look like a camel (🐫) because they have humps in the middle.
  • Class and record names (like String and CourseTime) are PascalCase, which was a convention in an early programming language called Pascal. These are like camel case, but they have the first letter capitalized.

There are other conventions, like Python which uses snake_case with underscores, or Scheme which uses kebab-case with hyphens. They have some pretty fun and whimsical names. In this book, we’ll use camel case and Pascal case following the Java conventions.

Student: I see, so it’s similar to rules for writing and having good style?
Prof: Correct – the rules are things that would be strictly wrong in writing, like saying “he are” instead of “he is”. The conventions are stylistic, like whether you use the “u” in colo[u]r. We often make a choice consistently for style across a whole document or kind of writing, and the consistency matters more than the specific choice that was made.

Practice

For each identifier, say what it is now, and what Java convention says it should be.
courseSchedule, a definition that holds a CourseTime: →
GreetingCard, a record with a to and a from field: →
DrawHouse, a method that returns a Pict: →
songInfo, a record with a title and an artist: →
2ndPlace, a definition that holds a runner’s name: →
total-price, a parameter of a method: →