1/70
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
What are the 22 rules to adhere to when writing Java code?
Use Javadoc comments for every method.
All non-private classes, constructors, and methods need javadoc comments
Declare, then initialize.
All parameters must be final (this includes main method and for loop parameters)
All variables should have explicit units (priceUsd, datePublished).
All numbers should be private static final constants, no magic numbers. Only use hardcoded values in for loops.
Always group together final static constants from regular constants.
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.
Separate author tags for separate authors.
For class comments, make sure there is an enter space between version and author names.
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.
Final instance variables should never contain javadoc comments.
Verbs are reserved for methods only.
All lowercase, unique, meaningful, reverse domain names for packages. (ca.bcit.comp2522.calculator)
Private final instance variables (unless they change).
One method should only perform one thing.
A class should only have one responsibility.
Never validate in the constructor, always call validation methods in the constructor.
CamelCase for variables and for methods.
No System.out.println() in your final code, only return statements.
Always use braces, even for single lines of code.
File names should match the class name.
Demonstrate the correct way to write a bank account object called sofiasAccount
BankAccount sofiasAccount;
sofiasAccount = new BankAccount();
How should you be initializing and declaring variables?
You should be initializing and declaring variables in a group.
Primitive types …
only hold a value
Reference Types …
only hold a memory address.
Give examples of reference types:
String, Array, System, BankAccount
What is an array?
An array is a reference type that stores a fixed number of values belonging to a single data type.
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.
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)
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
What would be the output of the following:
final String s;
s = " ";
System.out.println(s.isBlank());
True
What would be the output of the following:
final String s;
s = "/t/t/n";
System.out.println(s.isBlank());
True
What would be the output of:
“hello”.isBlank();
False
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.
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());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.
What about the main method? Should it be public or private?
The main method stays public.
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.
What does the final keyword mean?
final means that a variable cannot be re-assigned.
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.
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.
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.
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?
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.
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.
What is a symbolic constant?
Symbolic Constants: variables that are both static and final
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.
Write a symbolic constant to represent prime interest rate. It should be of type double.
private static final double PRIME_INTEREST_RATE;
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()
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.
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.
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); 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.
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.
In a javadoc comment for a class, what is mandatory to have?
A description
@author
@version tags
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).
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;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.
How should we name packages?
Packages should be named in all lowercase, with reverse domain names, and they should be meaningful and unique.
What does the private modifier mean?
It means that something is only accessible within the same class.
What does the default modifier mean?
Accessible within the same package.
What does the protected modifier mean?
Accessible within the same package and in subclasses
What does public mean?
Accessible anywhere.
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.
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.
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.
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”.
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.
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.
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) {}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.
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) {}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
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.
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.
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.
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.
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.
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);
}
}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);
}
}