Chapter 2 Java Building Blocks Flashcards

1
Q

Creating Objects
How to create object?

A
  1. Calling Constructor
  2. Some classes provide built-in methods that allow you to create new instances without using a constructor or the new keyword. (Integer using the valueOf() method.)
Park p = new Park();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is constructor?

A

A constructor in Java is a special method that is used to initialize objects.

The constructor is called when an object of a class is created.

It can be used to set initial values for object attributes.

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

Two key points to note about the constructor

2 key points to identify a constructor.

A
  1. Constructor name matches class name
  2. No return type
public class Chick {
    public Chick() {
        System.out.println("in constructor");
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Default Constructor

A

For most classes, you don’t have to code a constructor—the compiler will supply a “do nothing” default constructor for you.

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

The purpose of a constructor

A

is to initialize fields

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

READING AND WRITING MEMBER FIELDS

A
public class Swan {
   int numberEggs;                            // instance variable
   public static void main(String[] args) {
      Swan mother = new Swan();
      mother.numberEggs = 1;                  // set variable
      System.out.println(mother.numberEggs);  // read variable
   }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

read values of already initialized fields on a line initializing a new field

A
1: public class Name {
2:    String first = "Theodore";
3:    String last = "Moose";
4:    String full = first + last;
5: }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

EXECUTING INSTANCE INITIALIZER BLOCKS

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

Code Block

A

The code between the braces is called a code block.(sometimes called “inside the braces” {})

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

Instance Initializer

A

Code blocks appear outside a method.

Line 5 is an instance initializer

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
11
Q

FOLLOWING ORDER OF INITIALIZATION
Order of Initialization

A
  1. Fields and instance initializer blocks are run in the order in which they appear in the file.
  2. 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
12
Q

What is the output?

1:  public class Chick {
2:     private String name = "Fluffy"; 
3:     { System.out.println("setting field"); }
4:     public Chick() {
5:        name = "Tiny";
6:        System.out.println("setting constructor");
7:     }
8:     public static void main(String[] args) {
9:        Chick chick = new Chick(); 
10:       System.out.println(chick.name); } }
A
Ans : 
setting field
setting constructor
Tiny
1:  public class Chick {
2:     private String name = "Fluffy"; //2
3:     { System.out.println("setting field"); }//3
4:     public Chick() {
5:        name = "Tiny";//4
6:        System.out.println("setting constructor");//5
7:     }
8:     public static void main(String[] args) {
9:        Chick chick = new Chick(); //1
10:       System.out.println(chick.name); } }//6
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can you refer to a variable before it has been defined?

A

Ans : No.

Order matters for the fields and blocks of code. You can’t refer to a variable before it has been defined

Example :

{ System.out.println(name); }  // DOES NOT COMPILE
private String name = "Fluffy";
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What do you think this code prints out?

public class Egg {
   public Egg() {
      number = 5;
   }
   public static void main(String[] args) {
      Egg egg = new Egg();
      System.out.println(egg.number);
   }
   private int number = 3; 
   { number = 4; } 
A

Ans: 5

public class Egg {
   public Egg() {
      number = 5; //4
   }
   public static void main(String[] args) {
      Egg egg = new Egg(); //1
      System.out.println(egg.number);
   }
   private int number = 3; //2
   { number = 4; } //3
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Data types

A
  1. Primitive types
  2. Reference types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is primitive types?

A
  1. Java has eight (8) built-in data types, referred to as the Java primitive types.
  2. A primitive is not an object in Java nor does it represent an object.
  3. A primitive is just a single value in memory, such as a number or character.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Balanced parentheses problem

A

You cannot use a closed brace “}” if there’s no corresponding open brace “{” that it matches written earlier in the code.

In programming, this is referred to as the balanced parentheses problem, and it often comes up in job interview questions.

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

Java primitive types

A
  1. boolean (true or false), defalult false
  2. byte (8-bit integral value), defalult 0 (-128 to 127)
  3. short (16-bit integral value), defalult 0 (-32,768 to 32,767)
  4. int (32-bit integral value), defalult 0 (-2,147,483,648 to 2,147,483,647)
  5. long (64-bit integral value), defalult 0L (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
  6. float (32-bit floating-point value), defalult 0.0f
  7. double (64-bit floating-point value), defalult 0.0d
  8. char(16-bit Unicode value), default ‘\u0000’ (or 0)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

IS STRING A PRIMITIVE?

A

Ans : No.

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

What is String default value?

A

String or any object default value is null.

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

Java primitive type key points:

A
  1. The float and double types are used for floating-point (decimal) values.
  2. A float requires the letter f following the number so Java knows it is a float.
  3. The byte, short, int, and long types are used for numbers without decimal points. In mathematics, these are all referred to as integral values, but in Java, int and Integer refer to specific types.
  4. Each numeric type uses twice as many bits as the smaller similar type. For example, short uses twice as many bits as byte does.
  5. All of the numeric types are signed in Java. This means that they reserve one of their bits to cover a negative range. For example, byte ranges from -128 to 127. You might be surprised that the range is not -128 to 128. Don’t forget, 0 needs to be accounted for too in the range.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

SIGNED AND UNSIGNED: SHORT AND CHAR

A

short and char are closely related, as both are stored as integral types with the same 16-bit length.

short is signed

char is unsigned

Unsigned means range is strictly positive including 0.

Therefore, char can hold a higher positive numeric value than short, but cannot hold any negative numbers.

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

Valid short and char declaration

A
short bird = 'd';
char mammal = (short)83;
System.out.println(bird);   // Prints 100
System.out.println(mammal); // Prints S
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Invalid short and char declaration

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

FLOATING-POINT NUMBERS AND SCIENTIFIC NOTATION

A

This means the numbers are stored as two numbers, a and b, of the form a x 10b.

This notation allows much larger values to be stored, at the cost of accuracy.

No in exam

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

Declare and initialize long

A

Add the uppercase L.
L is more readable then lowercase l (look like 1)

long max = 3123456789L; // now Java knows it is a long
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Literals and the Underscore Character

A

In Java SE 7 and later, any number of underscore characters (_)can appear anywhere between digits in a numerical literal. This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code.

underscores in numbers to make them easier to read

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.

int million2 = 1_000_000;
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
28
Q

Writing Literals

A

Numeric primitives.
When a number is present in the code, it is called a literal.
By default, Java assumes you are defining an int value with a numeric literal.

long max = 3123456789;  // DOES NOT COMPILE

long max = 3123456789L;  // now Java knows it is a long

please use the uppercase L. The lowercase l looks like the number 1.

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

Java allows you to specify digits in several other formats:

A
  • base 10 since there are 10 numbers. It is also known as the decimal number system.
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Reference type

A

A reference type refers to an object (an instance of a class).

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

Primitive vs Reference type

A

Unlike primitive types that hold their values in the memory where the variable is allocated,
references do not hold the value of the object they refer to. Instead, a reference “points” to an object by storing the memory address where the object is located, a concept referred to as a pointer.

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

some examples that declare and initialize reference types.

A
java.util.Date today;
String greeting;
today = new java.util.Date();
greeting = new String("How are you?");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

DISTINGUISHING BETWEEN PRIMITIVES AND REFERENCE TYPES

A
  1. First, reference types can be assigned null, which means they do not currently refer to an object. Primitive types will give you a compiler error if you attempt to assign them null.
int value = null;   // DOES NOT COMPILE
String s = null;
  1. reference types can be used to call methods, assuming the reference is not null. Primitives do not have methods declared on them
4: String reference = "hello";
5: int len = reference.length();
6: int bad = len.length(); // DOES NOT COMPILE
  1. 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
34
Q

Declaring Variables

A

A variable is a name for a piece of memory that stores data.

When you declare a variable, you need to state the variable type along with giving it a name.

String zooName;
int numberAnimals;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Initializing variable

A

After declared a variable, we can give it a value.
This is called initializing a variable.

To initialize a variable, you just type the variable name followed by an equal sign

zooName = "The Best Zoo";
numberAnimals = 100;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

declarations and initializations

A
String zooName = "The Best Zoo";
int numberAnimals = 100;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Identifier

A

An identifier is the name of a variable, method, class, interface, or package.

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

There are only four rules to remember for legal identifiers:

A
  1. Identifiers must begin with a letter, a $ symbol, or a _ symbol.
  2. Identifiers can include numbers but not start with them.
  3. Since Java 9, a single underscore _ is not allowed as an identifier.
  4. 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
39
Q

Reserved words

A

abstract, assert,
boolean, break, byte
case, catch, char, class, const, continue
default, do, double
else, enum, extends
false**, final, finally, float, for
goto

if, implements, import, instanceof, int, interface
long
native, new, null**
package, private, protected, public
return
short, static, strictfp, super, switch, synchronized
this, throw, throws, transient, true**, try
void, volatile
while
_ (underscore)

* The reserved words const and goto aren’t actually used in Java. They are reserved so that people coming from other programming languages don’t use them by accident—and in theory, in case Java wants to use them one day.

** true/false/null are not actually reserved words, but literal values. Since they cannot be used as identifier names, we include them in this table.

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

legal identifier example

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

illegal identifier example

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
42
Q

Most Java developers follow these conventions for identifier names:

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q
A

Also, know that valid letters in Java are not just characters in the English alphabet.

Java supports the Unicode character set, so there are thousands of characters that can start a legal Java identifier.

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

Style: snake_case

A

Constant indentifier style
ex: THIS_IS_A_CONSTANT

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

Style: camelCase

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

Constant indentifier style

A

THIS_IS_A_CONSTANT

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

DECLARING MULTIPLE VARIABLES

A

You can declare many variables in the same declaration as long as they are all of the same type.

You can also initialize any or all of those values inline.

If you want to declare multiple variables in the same statement, they must share the same type declaration and not repeat it.

48
Q

DECLARING MULTIPLE VARIABLES

A

You can declare many variables in the same declaration as long as they are all of the same type. You can also initialize any or all of those values inline.

If you want to declare multiple variables in the same statement, they must share the same type declaration and not repeat it.

void sandFence() {
   String s1, s2;
   String s3 = "yes", s4 = "no"; 
}

void paintFence() {
   int i1, i2, i3 = 0; //declared: i1, i2, and i3, initialized: i3
}

int num, String value; // DOES NOT COMPILE different type

4: boolean b1, b2; //legal
5: String s1 = "1", s2; //legal
6: double d1, double d2; //ilegal cannot repeat data type
7: int i1; int i2; // legal, trick question it's a semi colon, not comma.
8: int i3; i4; //ilegal, trick question, did not specify a type for i4.
49
Q

How many variable is declared and initialized?

void paintFence() {
int i1, i2, i3 = 0;

}

A

three variables were declared: i1, i2, and i3.

only one of those values was initialized: i3.

50
Q
A
void sandFence() {
String s1, s2;
String s3 = "yes", s4 = "no";
int num, String value; // DOES NOT COMPILE
}
51
Q
A

void paintFence() {
int i1, i2, i3 = 0;
}

52
Q

Local variable

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.

Remember, the compiler is only concerned if you try to use uninitialized local variables; it doesn’t mind the ones you never use.

53
Q
4: public int notValid() {
5: int y = 10;
6: int x;
7: int reply = x + y; // DOES NOT COMPILE
8: return reply;
9: }
A

The y variable is initialized to 10. However, because x is not initialized
before it is used in the expression on line 7, the compiler generates the following error:

Test.java:7: variable x might not have been initialized
int reply = x + y; // DOES NOT COMPILE
^
54
Q
public int valid() {
int y = 10;
int x; // x is declared here
x = 3; // and initialized here
int reply = x + y;
return reply;
}
A

The compiler is smart enough to recognize variables that have been
initialized after their declaration but before they are used.

55
Q
public void findAnswer(boolean check) {
   int answer;
   int otherAnswer; //never use so can compile
   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, so the compiler is perfectly happy. It knows that 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.

The onlyOneBranch variable is initialized only if check happens to be true. The compiler knows there is the possibility for check to be false, resulting in uninitialized code, and gives a compiler error.

56
Q
A

Note:
On the exam, be wary of any local variable that is declared but not initialized in a single line. This is a common place on the exam that could result in a “Does not compile” answer. As you saw in the previous examples, 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.

57
Q

local variable initializations

A
58
Q

Variables passed to a constructor or method are called constructor parameters or method parameters

A

These parameters are local variables that have been pre-initialized.

The rules for initializing constructor and method parameters are the same

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

public void findAnswer(boolean check) {}

A

check is a method parameter.

60
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.

While the caller of a method checkAnswer() needs to be concerned about the variable being initialized, once inside the method findAnswer(), we can assume the local variable has been initialized to some value.

61
Q

Instance variables

A

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

No initialization required

62
Q

Class variable

A

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

You can tell a variable is a class variable because it has the keyword static before it.

No initialization required

63
Q

Default initialization values by type

A

Instance and class variables do not require you to initialize them.
1. boolean (false)
2. byte, short, int, long (0)
3. float, double (0.0)
4. char (‘\u0000’ (NUL))
5. All object references (everything else) (null)

64
Q

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

A

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

65
Q

var

A

Starting in Java 10

The formal name of this feature is local variable type inference.

can only use this feature for local variables.

The compiler looks at the code on the line of the declaration and uses it to infer the type.

value for a var can change after it is declared but the type never does.

Java does not allow var in multiple variable declarations.

The designers of Java decided it would be better not to allow var for null than to have to guess at intent.

it can be assigned a null value after it is declared

66
Q

var example

A
short apples = (short)10;
apples = (byte)5;
apples = 1_000_000;  // DOES NOT COMPILE

4: public void twoTypes() {
5:    int a, var b = 3;  // DOES NOT COMPILE
6:    var n = null;      // DOES NOT COMPILE
7: }

3:  public void doesThisCompile(boolean check) {
4:     var question; // DOES NOT COMPILE
5:     question = 1;
6:     var answer; // DOES NOT COMPILE
7:     if (check) {
8:        answer = 2;
9:     } else {
10:       answer = 3;
11:    }
12:    System.out.println(answer);
13: }
67
Q
A

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

68
Q
short apples = (short)10;
apples = (byte)5;
apples = 1_000_000; // DOES NOT COMPILE
A

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.

69
Q
public class VarKeyword {
var tricky = "Hello"; // DOES NOT COMPILE
}
A

Local variable type inference works with local variables and not instance variables.

70
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. It is equivalent to typing this:

int number = "five";

71
Q
A

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

72
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. Likewise, this is not allowed:
5: var a = 2, b = 3; // DOES NOT COMPILE
In other words, Java does not allow var in multiple variable declarations.

73
Q
3: public void doesThisCompile(boolean check) {
4:     var question;
5:     question = 1;
6:     var answer;
7:     if (check) {
8:         answer = 2;
9:     } else {
10:      answer = 3;
11:   }
12:     System.out.println(answer);
13: }
A

Remember that for local variable type inference, the compiler looks only at the line with the declaration.

lines 4 and 6 do not compile, since question and answer are not assigned values on the lines where they are defined

74
Q
7: public void breakingDeclaration() { 
8:     var silly 
9:     = 1;
10: }
A

This example is valid and does compile, but we consider the declaration and initialization of silly to be happening on the same line.

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

Java is case sensitive, so Var doesn’t introduce any conflicts as a class name.

Naming a local variable var is legal.(but it is not a good practice)

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.

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

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.

77
Q

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.

A

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.

78
Q

https://openjdk.java.net/projects/amber/LVTIstyle.html

A

This resource includes great style suggestions.
https://openjdk.java.net/projects/amber/LVTIstyle.html

79
Q

var Rules

A
  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.
80
Q
A
13: var n = "myData";
14: n = null;
15: var m = 4;
16: m = null;  // DOES NOT COMPILE
81
Q

PileOfPapersToFileInFilingCabinet pileOfPapersToFile =
new PileOfPapersToFileInFilingCabinet();

A

var pileOfPapersToFile = new PileOfPapersToFileInFilingCabinet();

82
Q

Managing Variable Scope

A
public void eat(int piecesOfCheese) {
int bitesOfCheese = 1;
}

There are two local variables in this method.

The bitesOfCheese variable is declared inside the method.

The piecesOfCheese variable is a method parameter and, as discussed earlier, it also acts like a local variable in terms of garbage collection and scope.

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.

83
Q

local variables

A
public void eat(int piecesOfCheese) {
int bitesOfCheese = 1;
}

two local variables in this method.

84
Q

LIMITING SCOPE

A

Local variables can never have a scope larger than the method they are defined in. However, they can have a smaller scope.

85
Q
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

The variable hungry has a scope of the entire method, while variable
bitesOfCheese has a smaller scope.

Since bitesOfCheese is declared in an if statement block, the scope is
limited to that block. When the compiler gets to line 7, it complains that it doesn’t know anything about this bitesOfCheese thing and gives an error:

error: cannot find symbol
System.out.println(bitesOfCheese); // DOES NOT COMPILE
^
symbol: variable bitesOfCheese
86
Q

NESTING SCOPE

A
  • blocks can contain other blocks.
  • These smaller contained blocks can reference variables defined in the larger scoped blocks, but not vice versa.
87
Q
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

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.

88
Q

TRACING SCOPE

A
89
Q
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

while : line 15 -19
if : line 13 - 20
Method : line 11 - 22

90
Q

APPLYING SCOPE TO CLASSES

A
91
Q

instance variables scope

A

they are available as soon as they are defined and last for the entire
lifetime of the object itself.

92
Q

class variable scope

A

they go into scope when declared like the other variable types.
However, they stay in scope for the entire life of the program.

93
Q
1: public class Mouse {
2:     final static int MAX_LENGTH = 5;
3:     int length;
4:     public void grow(int inches) {
5:         if (length < MAX_LENGTH) {
6:             int newSize = length + inches;
7:             length = newSize;
8:         }
9:     }
10: }
A
  • 1 class variable MAX_LENGTH (scope line 2- program end)
  • 1instance variable length (scope line 3 - as long as Mouse object exist)
  • two local variables, inches and newSize.
    • inches (scope line 4 - 9)
    • newSize (scope line 6 - 8 )
94
Q

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
95
Q

Destroying Objects

A

Java provides a garbage collector to automatically look for objects that aren’t needed anymore.

Java code exists inside of a Java Virtual Machine (JVM), which includes numerous processes independent from your application code. One of the most important of those is a built-in garbage collector.

96
Q

heap

A

All Java objects are stored in your program memory’s heap.

The heap, which is also referred to as the free store, represents a large pool of unused memory allocated to your Java application.

97
Q
A

One of the distinguishing characteristics of Java since its very first version is that it automatically performs garbage collection for you. In fact, other than removing references to an object, there’s very little you can do to control garbage collection directly in Java.

While garbage collection is pretty standard in most programming languages now, some languages, such as C, do not have automatic garbage collection. When a developer finishes using an object in memory, they have to manually deallocate it so the memory can be reclaimed and reused.

Failure to properly handle garbage collection can lead to catastrophic performance and security problems, the most common of which is for an application to run out of memory. Another similar problem, though, is if secure data like a credit card number stays in memory long after it is used and is able to be read by other programs. Luckily, Java handles a lot of these complex issues for you.

98
Q

UNDERSTANDING GARBAGE COLLECTION

A

Garbage collection refers to the process of automatically freeing memory on the heap by deleting objects that are no longer reachable in your program.

99
Q

eligible for garbage collection

A

eligible for garbage collection refers to an object’s state of no longer being accessible in a program and therefore able to be garbage collected.

100
Q

for the exam, you will need to know at any given moment which objects are eligible for garbage collection.

A

for the exam, you will need to know at any given moment which objects are eligible for garbage collection.

101
Q

It is the JVM’s responsibility to actually perform the garbage collection.

A
102
Q

Calling System.gc()

A
public static void main(String[] args) {
System.gc();
}
103
Q

What is the System.gc() command guaranteed to do?

A

Nothing, actually. It merely suggests that the JVM kick off garbage collection. The JVM may perform garbage collection at that moment, or it might be busy and choose not to. The JVM is free to ignore the request.

104
Q

When is System.gc() guaranteed to be called by the JVM? Never,
actually. While the JVM will likely run it over time as available memory
decreases, it is not guaranteed to ever actually run. In fact, shortly before a program runs out of memory and throws an OutOfMemoryError, the JVM will try to perform garbage collection, but it’s not guaranteed to succeed.

A
105
Q

For the exam, you need to know that System.gc() is not guaranteed to run or do anything, and you should be able to recognize when objects become eligible for garbage collection.

A
106
Q

How does the JVM know when an object is eligible for garbage collection?

A

The JVM waits patiently and monitors each object until it determines that the code no longer needs that memory. An object will remain on the heap until it is no longer reachable. An object is no longer reachable when one of two situations occurs:
* The object no longer has any references pointing to it.
* All references to the object have gone out of scope.

107
Q

An object is no longer reachable when one of
two situations occurs:

A
  • The object no longer has any references pointing to it.
  • All references to the object have gone out of scope.
108
Q

OBJECTS VS. REFERENCES

A
109
Q

reference

A

The reference is a variable that has a name and can be used to access the contents of an object. A reference can be assigned to another reference, passed to a method, or returned from a method. All references are the same size, no matter what their type is.

110
Q

object

A

An object sits on the heap and does not have a name. Therefore, you have no way to access an object except through a reference. Objects come in all different shapes and sizes and consume varying amounts of memory. An object cannot be assigned to another object, and an object cannot be passed to a method or returned from a method. It is the object that gets garbage collected, not its reference.

111
Q

1: public class Scope {
2:     public static void main(String[] args) {
3:         String one, two;
4:         one = new String("a");
5:         two = new String("b");
6:         one = two;
7:         String three = one;
8:         one = null;
9:     } 
}
A
112
Q

finalize()

A

This topic is no longer on the exam. In fact, it is deprecated in Object as of Java 9, with the official documentation stating, “The finalization
mechanism is inherently problematic.” We mention the finalize() method in case Oracle happens to borrow from an old exam question. Just remember that finalize() can run zero or one times. It cannot run twice.

113
Q

constructors

A

constructors create Java objects.

A constructor is a method matching the class name and omitting the return type.

When an object is instantiated, fields and blocks of code are initialized first. Then the constructor is run.

114
Q

Constructor example

A
public class Chick {
   public Chick() { //matches class name and no return type
      System.out.println("in constructor");
   }
}
115
Q

Which line compiles?
~~~
int million2 = 1000000;
double notAtStart = _1000.00;
double notAtEnd = 1000.00
;
double notByDecimal = 1000
.00;
double annoyingButLegal = 1_00_0.0_0;
double reallyUgly = 1__________2;
~~~

A
int million2 = 1_000_000; // compiles
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
116
Q

Which line compiles?
~~~
4: boolean b1, b2;
5: String s1 = “1”, s2;
6: double d1, double d2;
7: int i1; int i2;
8: int i3; i4;
9: int num, String value;
~~~

A
4: boolean b1, b2;
5: String s1 = "1", s2;
6: double d1, double d2; //cannot have to data type
7: int i1; int i2;
8: int i3; i4; //should use comma, instead of semicolon
9: int num, String value; // DOES NOT COMPILE