Chapter 2 Java Building Blocks Notes Flashcards

1
Q

Constructor

A
  • constructor is a special type of method that creates a new object
    • name of the constructor matches the name of the class
    • no return type
  • For most classes, you don’t have to code a constructor—the compiler will supply a “do nothing” default constructor for you.
  • For the exam, remember that anytime a constructor is used, the new keyword is required.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

INSTANCE INITIALIZER

A

Instance initializer are code blocks appear outside a method.

ex:

1: public class Bird {
2:    public static void main(String[] args) {
3:       { System.out.println("Feathers"); }
4:    }
5:    { System.out.println("Snowy"); } //instance initializer
6: }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

ORDER OF INITIALIZATION

A
  • Fields and instance initializer blocks are run in the order in which they appear in the file.
  • The constructor runs after all fields and instance initializer blocks have run.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

The Primitive Types

A
  1. boolean, true or false, default: false
  2. byte, 8-bit integral value, default: 0, (-128 to 127)
  3. short, 16-bit integral value, default: 0, ( -32,768 to 32,767)
  4. int, 32-bit integral value, default: 0,
  5. long, 64-bit integral value, default: 0L
  6. float, 32-bit floating-point value, default: 0.0f
    The float data type is a single-precision 32-bit IEEE 754 floating point
  7. double, 64-bit floating-point value, default: 0.0d
    The double data type is a double-precision 64-bit IEEE 754 floating point.
  8. char, 16-bit Unicode value, default: ‘\u0000’, (‘\u0000’ (or 0) to ‘\uffff’)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

SIGNED AND UNSIGNED: SHORT AND CHAR

A
  • both are stored as integral types with the same 16-bit length
  • short is signed
  • char is unsigned. Therefore, char can hold a higher positive numeric value than short, but cannot hold any negative numbers.
short bird = 'd';
char mammal = (short)83;

System.out.println(bird);   // Prints 100
System.out.println(mammal); // Prints S

short reptile = 65535;  // DOES NOT COMPILE
char fish = (short)-1;  // DOES NOT COMPILE
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

FLOATING-POINT NUMBERS AND SCIENTIFIC NOTATION

A

for the exam you are not required to know scientific notation or how floating-point values are stored.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Writing Literals

A

By default, Java assumes you are defining an int value with a numeric literal.

long max = 3123456789;  // DOES NOT COMPILE, out of range for int
long max = 3123456789L;  // postfix L, now Java knows it is a long
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Java allows you to specify digits in several other formats:

  • Octal (digits 0–7), which uses the number 0 as a prefix—for example, 017
  • Hexadecimal (digits 0–9 and letters A–F/a–f), which uses 0x or 0X as a prefix—for example, 0xFF, 0xff, 0XFf. Hexadecimal is case insensitive so all of these examples mean the same value.
  • Binary (digits 0–1), which uses the number 0 followed by b or B as a prefix—for example, 0b10, 0B10
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Literals and the Underscore Character

A
  • You can add underscores anywhere except at the beginning of a literal, the end of a literal, right before a decimal point, or right after a decimal point.
  • You can even place multiple underscore characters next to each other, although we don’t recommend it.

Ex:

double notAtStart = _1000.00;          // DOES NOT COMPILE
double notAtEnd = 1000.00_;            // DOES NOT COMPILE
double notByDecimal = 1000_.00;        // DOES NOT COMPILE
double annoyingButLegal = 1_00_0.0_0;  // Ugly, but compiles
double reallyUgly = 1\_\_\_\_\_\_\_\_\_\_2;      // Also compiles
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Reference Type

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

DISTINGUISHING BETWEEN PRIMITIVES AND REFERENCE TYPES

A
  • Reference types can be assigned null
  • Primitives do not have methods.
  • primitive types have lowercase type names.
  • All classes that come with Java begin with uppercase.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

4 Legal Identifiers Rules:

A
  • Identifiers must begin with a letter, a $ symbol, or a _ symbol.
  • Identifiers can include numbers but not start with them.
  • Since Java 9, a single underscore _ is not allowed as an identifier.
  • You cannot use the same name as a Java reserved word. A reserved word is special word that Java has held aside so that you are not allowed to use it. Remember that Java is case sensitive, so you can use versions of the keywords that only differ in case. Please don’t, though.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Legal?

long okidentifier;
float $OK2Identifier;
boolean _alsoOK1d3ntifi3r;
char \_\_SStillOkbutKnotsonice$;
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Legal?

int 3DPointClass; 
byte hollywood@vine;_
String *$coffee; 
double public;
short _;
A
int 3DPointClass;    // identifiers cannot begin with a number
byte hollywood@vine; // @ is not a letter, digit, $ or _
String *$coffee;     // * is not a letter, digit, $ or _
double public;       // public is a reserved word
short _;             // a single underscore is not allowed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

IDENTIFIERS IN THE REAL WORLD

A
  • Method and variable names are written in camelCase with the first letter being lowercase.
  • Class and interface names are written in camelCase with the first letter being uppercase. Also, don’t start any class name with $, as the compiler uses this symbol for some files.
  • Constants, uppercase snake_case, ex: THIS_IS_A_CONSTANT
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

DECLARING MULTIPLE VARIABLES

A
  • You can declare many variables in the same declaration as long as they are all of the same type.
    Java does not allow you to declare two different types in the same statement. Even if they are the same type:
    6: double d1, double d2; //ilegal
  • You can also initialize any or all of those values inline.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

LOCAL VARIABLES

A
  • A local variable is a variable defined within a constructor, method, or initializer block.
  • Local variables do not have a default value and must be initialized before use.
  • you are not required to initialize the variable on the same line it is defined, but be sure to check to make sure it’s initialized before it’s used on the exam.
18
Q
public void findAnswer(boolean check) {
   int answer;
   int otherAnswer;
   int onlyOneBranch;
   if (check) {
      onlyOneBranch = 1;
      answer = 1;
   } else {
      answer = 2;
   }
   System.out.println(answer);
   System.out.println(onlyOneBranch); // DOES NOT COMPILE
}
A

The answer variable is initialized in both branches of the if statement, regardless of whether check is true or false, the value answer will be set to something before it is used.

The otherAnswer variable is not initialized but never used, and the compiler is equally as happy. Remember, the compiler is only concerned if you try to use uninitialized local variables; it doesn’t mind the ones you never use.

19
Q
public void checkAnswer() {
   boolean value;
   findAnswer(value);  // DOES NOT COMPILE
}
A

The call to findAnswer() does not compile because it tries to use a variable that is not initialized.

20
Q

DEFINING INSTANCE AND CLASS VARIABLES

A

An instance variable, often called a field, is a value defined within a specific instance of an object.

a class variable is one that is defined on the class level and shared among all instances of the class.

Instance and class variables do not require you to initialize them. As soon as you declare these variables, they are given a default value.

Default initialization values by type

  • boolean, false
  • (byte, short, int, long), 0
  • (float, double), 0.0
  • char, ‘\u0000’ (NUL)
  • All object references (everything else), null
21
Q

VAR

A
  • Introduce in Java 10
  • The formal name of this feature is local variable type inference.
  • You can only use this feature for local variables
    • var can be used in for loops
    • with some lambdas
    • var can be used with try-with-resources.
22
Q

Type Inference of var

A

When you type var, you are instructing the compiler to determine the type for you. The compiler looks at the code on the line of the declaration and uses it to infer the type.

In Java, var is still a specific type defined at compile time. It does not change type at runtime.

23
Q
7:  public void reassignment() {
8:     var number = 7;
9:     number = 4;
10:   number = "five";  // DOES NOT COMPILE
11: }
A
  • On line 8, the compiler determines that we want an int variable.
  • On line 9, we have no trouble assigning a different int to it.
  • On line 10, Java has a problem. We’ve asked it to assign a String to an int variable. This is not allowed.
24
Q
var apples = (short)10;
apples = (byte)5;
apples = 1_000_000;  // DOES NOT COMPILE
A
  • The first line creates a var named apples with a type of short.
  • It then assigns a byte of 5 to it, but did that change the data type of apples to byte
  • The last line does not compile, as one million is well beyond the limits of short. The compiler treats the value as an int and reports an error indicating it cannot be assigned to apples.
25
Q
4: public void twoTypes() {
5:    int a, var b = 3;  // DOES NOT COMPILE
6:    var n = null;      // DOES NOT COMPILE
7: }
A

Line 5 wouldn’t work even if you replaced var with a real type. All the types declared on a single line must be the same type and share the same declaration. We couldn’t write
int a, int v = 3; either.

Line 6, var cannot be initialized with a null

26
Q
5:    var a = 2, b = 3;  // DOES NOT COMPILE
A

Java does not allow var in multiple variable declarations.

27
Q
13: var n = "myData";
14: n = null;
15: var m = 4;
16: m = null;  // DOES NOT COMPILE
A

While a var cannot be initialized with a null value without a type, it can be assigned a null value after it is declared, provided that the underlying data type of the var is an object.

  • Line 14 compiles without issue because n is of type String, which is an object.
  • Line 16 does not compile since the type of m is a primitive int, which cannot be assigned a null value.
28
Q
17: var o = (String)null;
A

var can be initialized to a null value if the type is specified

29
Q
public int addition(var a, var b) {  // DOES NOT COMPILE
   return a + b;
}
A

In this example, a and b are method parameters. These are not local variables. Be on the lookout for var used with constructors, method parameters, or instance variables. Using var in one of these places is a good exam trick to see if you are paying attention. Remember that var is only used for local variable type inference!

30
Q
package var;
 
public class Var {
   public void var() {
      var var = "var";
   }
   public void Var() {
      Var var = new Var();
   }
}
A

this code does compile. Java is case sensitive, so Var doesn’t introduce any conflicts as a class name. Naming a local variable var is legal.

31
Q
public class var {  // DOES NOT COMPILE
public var() { }
}
A

While var is not a reserved word and allowed to be used as an identifier, it is considered a reserved type name. A reserved type name means it cannot be used to define a type, such as a class, interface, or enum.

32
Q

Review of var Rules

A

Review of the var rules:

  1. A var is used as a local variable in a constructor, method, or initializer block.
  2. A var cannot be used in constructor parameters, method parameters, instance variables, or class variables.
  3. A var is always initialized on the same line (or statement) where it is declared.
  4. The value of a var can change, but the type cannot.
  5. A var cannot be initialized with a null value without a type.
  6. A var is not permitted in a multiple-variable declaration.
  7. A var is a reserved type name but not a reserved word, meaning it can be used as an identifier except as a class, interface, or enum name.
33
Q

VAR IN THE REAL WORLD

A
PileOfPapersToFileInFilingCabinet pileOfPapersToFile =
    new PileOfPapersToFileInFilingCabinet();

You can see how shortening this would be an improvement without losing any information:

var pileOfPapersToFile = new PileOfPapersToFileInFilingCabinet();
34
Q

Managing Variable Scope

public void eat(int piecesOfCheese) {
   int bitesOfCheese = 1;
}
A
  • There are two local variables in this method.
  • The bitesOfCheese variable is declared inside the method.
  • The piecesOfCheese variable is a method parameter
  • Both of these variables are said to have a scope local to the method. This means they cannot be used outside of where they are defined.
35
Q

LIMITING SCOPE

3: public void eatIfHungry(boolean hungry) {
4:    if (hungry) {
5:       int bitesOfCheese = 1;
6:    }  // bitesOfCheese goes out of scope here
7:    System.out.println(bitesOfCheese);  // DOES NOT COMPILE
8: }
A
  • Local variables can never have a scope larger than the method they are defined in.
  • However, they can have a smaller scope.
  • When you see a set of braces ({}) in the code, it means you have entered a new block of code.
  • Each block of code has its own scope.
  • When there are multiple blocks, you match them from the inside out.

Ex:

  • The variable hungry has a scope of the entire method,
  • The variable bitesOfCheese has a smaller scope. It is only available for use in the if statement because it is declared inside of it.
36
Q

NESTING SCOPE

16: public void eatIfHungry(boolean hungry) {
17:    if (hungry) {
18:       int bitesOfCheese = 1;
19:       {
20:          var teenyBit = true;
21:          System.out.println(bitesOfCheese);
22:       }
23:    }
24:    System.out.println(teenyBit);  // DOES NOT COMPILE
25: }
A

These smaller contained blocks can reference variables defined in the larger scoped blocks, but not vice versa.

  • The variable defined on line 18 is in scope until the block ends on line 23.
  • Using it in the smaller block from lines 19 to 22 is fine.
  • The variable defined on line 20 goes out of scope on line 22. Using it on line 24 is not allowed.
37
Q

TRACING SCOPE

11: public void eatMore(boolean hungry, int amountOfFood) {
12:    int roomInBelly = 5;
13:    if (hungry) {
14:       var timeToEat = true;
15:       while (amountOfFood > 0) {
16:          int amountEaten = 2;
17:          roomInBelly = roomInBelly - amountEaten;
18:          amountOfFood = amountOfFood - amountEaten;
19:       }
20:    }
21:    System.out.println(amountOfFood);
22: }
A

scope of each variable

  • hungry and amountOfFood are method parameters, so they are available for the entire method. (line 11-22)
  • The variable roomInBelly goes into scope on line 12 because that is where it is declared. It stays in scope for the rest of the method and so goes out of scope on line 22.
  • The variable timeToEat goes into scope on line 14 where it is declared. It goes out of scope on line 20 where the if block ends.
  • Finally, the variable amountEaten goes into scope on line 16 where it is declared. It goes out of scope on line 19 where the while block ends.
38
Q

Review the rules on scope:

A
  • Local variables: In scope from declaration to end of block
  • Instance variables: In scope from declaration until object eligible for garbage collection
  • Class variables: In scope from declaration until program ends
39
Q

Eligible for Garbage Collection

A
  • The object no longer has any references pointing to it.
  • All references to the object have gone out of scope.
40
Q
Calling System.gc()
A

For the exam, you need to know that System.gc() is not guaranteed to run or do anything