Chapter 1 Flashcards
What are the key (identifying) benefits of Java
- Object Oriented
- Encapsulation
- Platform independent
- Robust
- Simple
- Secure
- Multithreaded
- Backward Compatibility
What key pieces does the Java Development Kit contain?
- The compiler (javac)
- The launcher (java)
- The Java Virtual Machine (JVM)
- javadoc
- jar
What is an object?
A runtime instance of a class in memory
What is a reference?
A variable that points to an object.
What are the two primary elements of a Java class?
Methods and fields.
What is the simplest valid Java class we can write?
public class Animal { }
The method signature consists of .. ?
The method name and parameters.
Does Java require a class to be public?
Java does not require a class to be public
Given a file with two or more classes, how many are allowed to be public? How many must be public?
Only one is allowed to be public (must match file name) & none are required.
Where does Java begin execution?
By calling the main() method.
What command do we use to check the version of java?
java -version
Using the terminal, how can we compile and then run the file Zoo.java?
- javac Zoo.java
2. java Zoo
Using the terminal with single-file source-code, how can we compile and then run the file Zoo.java?
- java Zoo.java
What is the constraint of single-file source-code?
It can only be used if your program contains one file.
What are the differences between using the commands javac + java and single-file source-code to compile and run a program?
Full command-javac Zoo.java java Zoo Bronx Zoo
- need to use two commands
- Produces a class file
- For any program
- Can import code in any available Java library
Single-file source-code - java Zoo.java Bronx Zoo
- one command
- Fully in memory (no class files)
- For programs with one file
- Can only import code that came with the JDK
Is using java.util.Random more efficient than using java.util.* to import the Random class?
Java automatically imports only the classes that are needed so in the end only Random will be importer in both cases.
You might think that including so many classes slows down your program execution, but
it doesn’t. The compiler figures out what’s actually needed.
There is one special package in Java that is implicitely imported by Java. Which one is it?
java.lang
What package do the Files and Paths class belong to?
java.nio.file
How many wildcards (*) are allowed in a package declaration?
One, and it must be at the end.
What does java do with “ties” for precedence in import declarations?
example:
import java.util.Date;
import java.sql.Date;
It throws an error:
- error: reference to Date is ambiquous
Compile and run the following two classes using the java terminal commands:
- javac packagea/ClassA.java packageb/ClassB.java
- java packageb.ClassB
Where does the javac command place the compiled classes by default?
In the same directory as the source code.
How can we use the javac command to compile ‘packagea/ClassA’ in the directory ‘classes’
javac -d classes packagea/ClassA.java
Compile and run the two classes below using the java terminal commands. Compile them into a directory called ‘classes’.
- packagea/ClassA
- packageb/ClassB (contains the main method)
- javac -d classes packagea/ClassA.java packageb/ClassB.java
- java -cp classes packageb.ClassB
What options are there to specify the classpath to the java or javac command?
- ‘-cp’
- ‘-classpath’
- ’–class-path’
Create a JAR file: ‘myNewFile.jar’ based on the current directory.
jar -cvf myNewFile.jar .
– or –
jar –create –verbose –file myNewFile.jar .
Create a JAR file: ‘myNewFile.jar’ based on the directory ‘dir’
jar -cvf myNewFile.jar -C dir .
Is the following entry point method allowed?
- static public void main(String [ ]args) { }
yes
Rules to compile .java file
- Each file can contain only one public class.
- The filename must match the class name, including case, and have a .java extension.
- If the Java class is an entry point for the program, it must contain a valid main() method.
Main method valid arguments
String[] args
String options[]
String… friends
Which import statements do you think would work to get this code to compile?
~~~
public class InputImports {
public void read(Files files) {
Paths.get(“name”);
}
}
~~~
There are two possible answers. The shorter one is to use a wildcard to import both at the
same time.
~~~
import java.nio.file.*;
~~~
The other answer is to import both classes explicitly.
~~~
import java.nio.file.Files;
import java.nio.file.Paths;
~~~
Now let’s consider some imports that don’t work.
import java
import java.nio.*; // NO GOOD -a wildcard only matches // class names, not "file.Files" import java.nio.*.*; // NO GOOD -you can only have one wildcard // and it must be at the end import java.nio.file.Paths.*;
If You Really Need to Use Two Classes with the Same Name
public class Conflicts { java.util.Date date; java.sql.Date sqlDate; }
Compiling to Another Directory
javac -d
classes packagea/ClassA.java packageb/ClassB.java
What is Jar
A Java archive (JAR) file is like a ZIP file of mainly Java class files.
Creating a JAR File
jar -cvf myNewFile.jar .
How many blocks do you see in the following example?
1: public class Bird { 2: public static void main(String[] args) { 3: { System.out.println("Feathers"); } 4: } 5: { System.out.println("Snowy"); } 6: }
There are four code blocks in this example: a class definition, a method declaration, an inner block, and an instance initializer.
When you’re counting** instance initializers, keep in mind that they cannot exist inside of amethod. Line 5 is an instance initializer, with its braces outside a method. On the other hand, line 3 is not an instance initializer**, as it is only called when the main() method is executed.
Order of Initialization
- 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.
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); } }
Running this example prints this:
setting field
setting constructor
Tiny
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; } }
If you answered 5, you got it right. Fields and blocks are run first in order, setting number
to 3 and then 4. Then the constructor runs, setting number to 5. You see a lot more rules
and examples covering order of initialization
primitive
boolean
min value/ max value/ default
n/a
n/a
false
byte
min value/ max value/ default
-128
127
0
integral value
8-bit
short
min value/ max value/ default
-32,768
32,767
0
16-bit
int
-2,147,483,648
2,147,483,647
0
32-bit
long
-2^63
(26^3) – 1
0L
64-bit
float
n/a
n/a
0.0f
32-bit
double
n/a
n/a
0.0
64-bit
char
0
65,535
\u0000
16 BIT
Literals and the Underscore Character
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
Which one compile ?
int value = null; String name = null;
int value = null; // DOES NOT COMPILE String name = null; // compile
How to create Wrapper classes ?
output?
String block = """ doe \ deer""";
doe deer
output ?
String block = """ doe deer """;
doe
deer
String block = """ doe \n deer """;
doe
deer
String eyeTest = "\"Java Study Guide\"\n by Scott & Jeanne";
“Java Study Guide”
by Scott & Jeanne
String block = """ "doe\"\"\" \"deer\""" """;
- “doe”””
“deer”””
*
Text block formmatting table
Illegal variables names
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 many declared and initialized
int i1, i2, i3 = 0;
three variables were declared: i1, i2, and i3. one
of those values was initialized: i3
is correct ?
int num, String value;
int num, String value; // DOES NOT COMPILE
Which line are legall ?
4: boolean b1, b2; 5: String s1 = "1", s2; 6: double d1, double d2; 7: int i1; int i2; 8: int i3; i4;
- 4,5 are legall
- 6 illegal (should be (;))
- 7 is legal (;) - 8 is illegal (should be ,)
What i local variable ?
A local variable is a variable defined within a constructor, method, or initializer block
Is possible to modify final array like follows ?
5: final int[] favoriteNumbers = new int[10]; 6: favoriteNumbers[0] = 10; 7: favoriteNumbers[1] = 20; 8: favoriteNumbers = null;
The compiler error isn’t untilline 8, when we try to change the value of the reference favoriteNumbers.
Is this runns ?
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); }
System.out.println(onlyOneBranch); // DOES NOT COMPILE
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.
Compile ?
public class VarKeyword { var tricky = "Hello"; // }
The formal name of this feature is local variable type inference
.
It only can be used in scope of methods, block etc.
What is var variable ?
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.
7: public void reassignment() { 8: var number = 7; 9: number = 4; 10: number = "five"; // DOES NOT COMPILE 11: }
Is this compile ?
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: }
The code does not compile. Remember that for local variable type inference,
the compiler
looks only at the line with the declaration.
Since question and answer are not assigned
values on the lines where they are defined, the compiler does not know what to make of
them. For this reason, both lines 4 and 6 do not compile.
Is this compile ?
4: public void twoTypes() { 5: int a, var b = 3; 6: var n = null; 7: }
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 is a single line. The compiler is being asked to infer the type of null. This could
be any reference type. The only choice the compiler could make is Object. However, that is
almost certainly not what the author of the code intended. The designers of Java decided it
would be better not to allow var for null than to have to guess at intent.
Is this compile ?
public int addition(var a, var b) { return a + b; }
No
Is this compile ?
public class Var { public void var() { var var = "var"; } public void Var() { Var var = new Var(); } }
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.
Scope of variables
* Local variables
: In scope from declaration to the end of the block
* Method parameters
: In scope for the duration of the method
* Instance variables
: In scope from declaration until the object is eligible for garbage
collection
* Class variables
: In scope from declaration until the program ends
Garbage Collection
Garbage collection refers to the process of automatically freeing memory on the heap by
deleting objects that are no longer reachable in your program.
When Object is garabage Collected ?
eligible forgarbage collection refers to an object’s state of no longer being accessible in a program and therefore able to be garbage collected.
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.