Chapter 1 - Java Coding Conventions

0.0(0)
studied byStudied by 0 people
0.0(0)
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/70

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 3:28 AM on 2/1/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai

No analytics yet

Send a link to your students to track their progress

71 Terms

1
New cards

What are the 22 rules to adhere to when writing Java code?

  1. Use Javadoc comments for every method.

  2. All non-private classes, constructors, and methods need javadoc comments

  3. Declare, then initialize.

  4. All parameters must be final (this includes main method and for loop parameters)

  5. All variables should have explicit units (priceUsd, datePublished).

  6. All numbers should be private static final constants, no magic numbers. Only use hardcoded values in for loops.

  7. Always group together final static constants from regular constants.

  8. Never include hardcoded values in comments or validation methods. If you’re checking for negative values, always make it < MIN_VALUE never less than 0.

  9. Separate author tags for separate authors.

  10. For class comments, make sure there is an enter space between version and author names.

  11. Never include an @throws clause if it breaks the flow of @param tags. If you have 3 parameters, and 3 @param tags grouped together, don’t break the flow with @throws.

  12. Final instance variables should never contain javadoc comments.

  13. Verbs are reserved for methods only.

  14. All lowercase, unique, meaningful, reverse domain names for packages. (ca.bcit.comp2522.calculator)

  15. Private final instance variables (unless they change).

  16. One method should only perform one thing.

  17. A class should only have one responsibility.

  18. Never validate in the constructor, always call validation methods in the constructor.

  19. CamelCase for variables and for methods.

  20. No System.out.println() in your final code, only return statements.

  21. Always use braces, even for single lines of code.

  22. File names should match the class name.

2
New cards

Demonstrate the correct way to write a bank account object called sofiasAccount

BankAccount sofiasAccount;

sofiasAccount = new BankAccount();

3
New cards

How should you be initializing and declaring variables?

You should be initializing and declaring variables in a group.

4
New cards

Primitive types …

only hold a value

5
New cards

Reference Types …

only hold a memory address.

6
New cards

Give examples of reference types:

String, Array, System, BankAccount

7
New cards

What is an array?

An array is a reference type that stores a fixed number of values belonging to a single data type.

8
New cards

Are all variables automatically initialized by java when you don’t assign them a value?

No, only instance variables (class-level variables) and static variables receive default values.

Local variables (method-level) do not receive default values.

9
New cards

What are the default values given to Instance Variables and Static variables?

int 0

double 0.0

boolean false

char \u0000

String null

Array null

(All objects are set to null)

10
New cards

What is the difference between null and ““

Null means that there is no object, so primitive types cannot be null. When something is null, it cannot have any methods and it has no address associated with it.

““: means a string without any characters. Unlike null, it does have methods, and it does have a memory address. Empty strings have a length of 0.

11
New cards

What would be the output of the following code:

final String s1;

final String s2;

s1 = null;

s2 = ““;

System.out.println(s1.length());

System.out.println(s1.length());

NullPointerException

0

12
New cards

What would be the result of the following:

final String s1;

s1 = “ “;

System.out.println(s1.length());

When using .length() on a string filled with spaces, you will still get a value for length. This is because spaces are counted as being part of the length of a string.

13
New cards

final String s;

s = “\n\t\t“;

System.out.println(s.length());

When using .length() on a string filled with newlines (\n) and tabs (\t), you will still get a value for length. Tabs and newlines are counted as being part of the string’s length.

14
New cards

What would be the output of the following:

final String s;

s = “\n\t\t“;

System.out.println(s == null);

False. The string object is not null because it contains newlines and spaces that are counted as characters.

15
New cards

What would be the output of the following:

final String s;

s = ““;

System.out.println(s == null);

False, empty strings are also not null. Having no characters just means that you have a length of 0, but you still have methods and a memory address, which is not a characteristic of something that is null.

The only time a variable will be null is when you manually set its value to null.

16
New cards

What would be the output of the following:

final String s;

s = ““;

System.out.println(s.isEmpty());

isEmpty() returns true only if the length of the string is actually 0. Otherwise, if the string contains whitespace, those will be counted as characters and isEmpty() will return false.

In this case, s has a length of 0. Therefore, it returns True.

17
New cards

What would be the output of the following:

final String s;

s = “ “;

System.out.println(s.isEmpty());

isEmpty() will only return true if the length of a string is actually 0. Since this string contains whitespace, it is technically not empty, therefore, isEmpty() returns False.

18
New cards

What would be the output of the following:

final String s;

s = null;

System.out.println(s.isEmpty());

NullPointerException

Using a method on any variable that is null will give you an exception. This is because null variables don’t have any methods associated with them.

19
New cards

What does isEmpty() check for? When can it be used?

isEmpty() checks if a string actually has a length of 0. If it does, it returns true, but if it contains whitespace, it returns false.

20
New cards

What would be the output of the following:

final String s;

s = null;

System.out.println(s.isBlank());

NullPointerException

You cannot use any methods on a null variable.

21
New cards

What would be the output of the following:

final String s;

s = "";

System.out.println(s.isBlank());

.isBlank() returns true only when a String contains REAL CHARACTERS THAT ARE NOT WHITESPACE.

If your string has a length of 0, contains only whitespace, or only contains tabs and newlines, then isBlank() will return false.

Answer: True

22
New cards

What would be the output of the following:

final String s;

s = " ";

System.out.println(s.isBlank());

True

23
New cards

What would be the output of the following:

final String s;

s = "/t/t/n";

System.out.println(s.isBlank());

True

24
New cards

What would be the output of:
“hello”.isBlank();

False

25
New cards

What is the problem with the following code?

String s;
s = null;
if(!s.isEmpty() && s != null);

The code will not validate properly because it short-circuits. Since the string is null, the first statement will produce a NullPointerException and it will never get to the second part of the statement.

26
New cards

How can we fix this code:

String s;
s = null;
if(!s.isEmpty() && s != null);

By swapping the order of the two statements:

String s;
s = null;
if(s != null && !s.isEmpty());

27
New cards

What is an instance variable? What modifiers do we use for instance variables?

Instance variables should be private final.

Instance variables are just class-level variables.

28
New cards

What about the main method? Should it be public or private?

The main method stays public.

29
New cards

In the following code, what is the visibility of this class?

class Sofia {
    public static void main(final String args[]) {
        final BankAccount b1;
        b1 = new BankAccount();
    }
}

By default, when you do not provide a visibility modifier, it is only accessible within the same package.

Answer: It has package-visibility.

30
New cards

What does the final keyword mean?

final means that a variable cannot be re-assigned.

31
New cards

As a general rule, what should be final?

Most variables should be final unless their value changes throughout the program.

All arguments in methods and constructors should be final.

32
New cards

What is a key characteristic of Static variables?

When you use static for a variable, it means there is only a single version of that variable shared across all objects created of that class (or shared across all instances of a class).

Changing the value of a static variable means you change its value for all objects of the same class.

33
New cards

What are some key characteristics of static methods?

Static methods belong to a single class, so you can use them by calling the class name directly; It does not require you to create an object of that class.

IMPORTANT NOTE: Static methods are not capable of accessing instance variables that are not static (directly). This is because static methods belong to a class, and instance variables belong to an object, so it doesn’t know which object to refer to.

34
New cards

When should you use static variables?

Whenever you feel like the data should belong to the class as a whole, not to any individual object.

Ask yourself: If I create 100 objects, should there be 100 different copies of this value for each individual object or not?

35
New cards

Give two examples of when NOT to use a static variables

Don’t use static variables when you have a Person class.

When you have a “Person” class, you don’t want to make eyeColor, heightFt, ageYears static because each individual person likely has their own unique value for height, eye color, age and so on. Using static variables here would mean that if you created 100 different Person objects, they would all share the same value for eyeColor, heightFt.

Don’t use static variables if the value of that variable depends on the user’s input per object.

36
New cards

When would it be appropriate to use static variables? Give an example:

If you had a human race class, with instance variables like oldestPerson, population, then it would be appropriate to make those instance variables static, because those are values that are shared across all objects of the human race.

37
New cards

What is a symbolic constant?

Symbolic Constants: variables that are both static and final

38
New cards

What are the advantages to using Symbolic Constants?

Symbolic constants are good because they are meaningful, improve readability, and eliminate magic numbers. They also prevent errors from having to change the value of a variable in multiple spots.

39
New cards

Write a symbolic constant to represent prime interest rate. It should be of type double.

private static final double PRIME_INTEREST_RATE;

40
New cards

When should you use static methods?

Use a static method whenever the method doesn’t depend on a non-static instance variable. This is because static methods cannot access non-static instance variables.

Use a static method when the method is a utility/tooll and it doesn’t make sense to belong to an object.

ex. Math.sqrt()

41
New cards

What is the “Static Error”?

The static error is when you try to access a non-static instance variable through a static method.

This is not allowed because regular instance variables, by definition, belong to an object, not to a class, and therefore the static method does not know which object you’re referring to when you try to access it/use it.

42
New cards

What actually happens when you declare an instance variable as being static?

When you declare a variable as static, it stops being an instance variable.

It becomes a class variable instead.

So it is actually wrong to say that “static methods cannot access static instance variables” because static instance variables don’t actually exist. The moment you declare them as static, we call them class variables instead. So technically, static methods cannot access instance variables (which have to be non-static), but they can access class variables declared as static.

43
New cards

How can we get around the “Static Error”?

Make the instance variable static, but keep in mind that this would change the meaning of the variable. Now all objects would share the same value for this variable.

OR

Create a brand new object in your static method, and access the instance variable that way. Here’s an example of how its done:

BankAccount sofiasAccount;
sofiasAccount = new BankAccount();
System.out.println(sofiasAccount.number); 

44
New cards

What makes javadoc comments different from other types of comments?

Javadoc comments are eventually published in an HTML class library, where they act as a user’s manual.

45
New cards

When is it mandatory to have javadoc comments?

Use javadoc comments for all non-private methods and all classes. Never use them for instance variables.

46
New cards

In a javadoc comment for a class, what is mandatory to have?

A description

@author

@version tags

47
New cards

In a javadoc comment for a method, what is mandatory to have?

@param (Only necessary if it doesn’t break the flow of parameters)

@return

@throws (Only for checked exceptions: exceptions that the compiler forces you to deal with, and manage using a try catch block).

48
New cards

Write a javadoc comment for the following class:

class RoyalBankAccount {
    private static double primeInterestRate = 5.12;

/**
* This is a class that creates a RoyalBank Account.
* @author Sofia
*
* @version 1.0
*/
class RoyalBankAccount {
    private static double primeInterestRate = 5.12;

49
New cards

What is the role or job of a package? What is the advantage of using a package?

A package is just a folder on your computer that’s used to group together related classes.

Example: The math package, which just holds all of the math-related classes.

Using a package helps you avoid naming conflicts so that you can have 2 different Person classes in different packages.

50
New cards

How should we name packages?

Packages should be named in all lowercase, with reverse domain names, and they should be meaningful and unique.

51
New cards

What does the private modifier mean?

It means that something is only accessible within the same class.

52
New cards

What does the default modifier mean?

Accessible within the same package.

53
New cards

What does the protected modifier mean?

Accessible within the same package and in subclasses

54
New cards

What does public mean?

Accessible anywhere.

55
New cards

What is a constructor?

A special method (but Jason doesn’t consider it to be a method) used to create objects.

OR
A blueprint for creating objects.

56
New cards

How can we distinguish a constructor from a regular method? When do constructors run? What do we use constructors for?

Constructors have no return type (not even void), which makes them different from regular methods.

Constructors run automatically when you use the new keyword.

We use constructors for validating and initializing instance data; However, constructors don’t validate the data themselves, they call validation methods to do so.

57
New cards

When you use the new keyword to create an object, what happens behind the scenes?

Using the new keyword allocates memory for the new object and sets all of its instance variables to their default values (automatic initialization). It then calls the constructor to actually initialize the object.

58
New cards

What are instance initializer blocks?

Instance initializer blocks are blocks of code that run before a constructor whenever a new object is created.

They are often referred to as “pre-constructors”.

59
New cards

If you have an instance initializer block, and you create a new object, what happens behind the scenes? How many times does it run?

When you use the new keyword, memory is allocated for that object, instance variables get their default values due to automatic initialization (false, 0, 0.0, null, etc.), then the instance initializer block runs, and afterwards, the constructor is called to initialize the object.

Note: Instance initializer blocks only run EACH TIME an object is first created, not just a single time.

60
New cards

Why would we ever need to use an instance initializer block?

We use instance initializer blocks to avoid redundancies; Sometimes classes have multiple constructors running the same set-up code for initializing instance variables.

In that case, you could either copy or paste the same code in every constructor, or you could put the shared code in a single instance initializer block, so that all constructors automatically get the code.

61
New cards

Write an Instance Initializer block to initialize the following instance variables before the following constructors:

class Player {
    private int health;
    private int stamina;

    // these two below are two different constructors (overloaded)
    Player() {} 
    Player(final String name) {}

class Player {
    private int health;
    private int stamina;
    
    // this is the instance initializer block; both of the constructors below will inherit this code
    {
        health = 100;
        stamina = 50;
    }

    // the two constructors
    Player() {} 
    Player(final String name) {}

62
New cards

What differentiates a static initializer block from a regular initializer block?

A static initializer block is specifically for initializing static variables.

Unlike regular initializer blocks, static initializer blocks don’t run every time a new object is created. It only runs ONCE, when a class first loads into memory.

63
New cards

Give an example of what a static instance initializer block looks like:

class Player {
    private static int health;
    private static int stamina;

    Player() {} 
    Player(final String name) {}

Exactly the same, just with the static keyword:

class Player {
    private static int health;
    private static int stamina;

static {
    health = 100;
    stamina = 50;
}
    Player() {} 
    Player(final String name) {}

64
New cards

When do static initializer blocks actually run?

Static initializer blocks only run when a class first loads in;

A class loading in could mean any of the following:

  • A new object was created

  • You accessed a static field or static “instance variable”

  • You called a static method

  • You manually loaded the class or a subclass was loaded

65
New cards

Why use a static instance initializer block when you could just use a static method to achieve the same result? What are the advantages of using a static instance initializer block?

Static instance initializer blocks are better because they allow you to have more complex logic, exception handling, and are fool-proof because they will always run automatically when a class first loads in, so you don’t have to remember to call them, like static methods.

66
New cards

What is a core feature that all objects should start out with?

All objects should start their life in a valid state.

Example: A bank account object should never start out with a negative account balance or an invalid pin number.

67
New cards

What do we use to guarantee that an object stays valid? What role do constructors play in this?

We use constructors to make sure an object initially starts out valid, and we use getters and setters to maintain that validity over time.

68
New cards

What is a validation method?

Validation methods are just methods that validate input (typically instance variables) and throw an exception if the input is invalid. They don’t return any values and don’t assign any new values either.

69
New cards

What modifiers do we use for validation methods and why?

Validation methods should be declared with private static.

This is because private static methods cannot be overridden, which means that your validation logic can never be overridden by another class.

70
New cards

Write a validation method with the formal parameter: double balanceCad that checks to see if the value of this variable is less than MIN_BALANCE_CAD.

private static void checkBalance(final double balanceCad) {
    if(balanceCad < MIN_BALANCE_CAD) {
        throw new IllegalArgumentException("invalid balance" + balance);
    }
}

71
New cards

Write a validation method that has the following formal parameter: int pin

and checks to see if pin is less than MIN_PIN_VALUE and if the pin is greater than the MAX_PIN_VALUE.

private static void checkPin(final int pin) {
    if(pin < MIN_PIN_VALUE || pin > MAX_PIN_VALUE) {
        throw new IllegalArgumentException("invalid pin" + pin);
    }
}