Chapter 1 Welcome to Java Flashcards

1
Q

The Java Development Kit (JDK) contains the minimum software you need to do Java development.
Key commands include:

A
  1. javac : compiler, convert source file (.java) into bytecode (.class).
  2. java : launcher, launch Java Virtual Machine (JVM), JVM run bytecode on the actual machine.
  3. jar: archiver, package files together
  4. Javadoc: generate documentation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

JVM

A

Java Virtual Machine (JVM), JVM run bytecode on the actual machine.

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

JDK

A

Java Development Kit (JDK)

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

API

A

Java comes with a large suite of application programming interfaces (APIs) that you can use.

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

IDE

A

integrated development environment (IDE)

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

Java Release

A
  • Every six months, Oracle releases a new version of Java.
  • Java 11 came out in September 2018.
  • Java 17 came out in September 2021.
  • You should use Java 17 to study with since this is a Java 17 exam. The rules and behavior can change with later versions of Java. You wouldn’t want to get a question wrong because you studied with a different version of Java!
  • Every three years, Oracle has a long-term support (LTS) release. LTS releases have patches and upgrades available for at least three years.
  • non-LTS versions supported only six months.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Benefits of Java

A

1. Object Oriented
2. Encapsulation
3. Platform Independent
4. Robust
5. Simple
6. Secure
7. Multithreaded
8. Backward Compatibility

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

Java has some key benefits that you’ll need to know for the exam.

A
  1. Object Oriented
    • Java is an object-oriented language, which means all code is defined in classes, and most of those classes can be instantiated into objects.
    • Java allows for functional programming within a class, but object-oriented is still the main organization of code.
  2. Encapsulation
    • Java supports access modifiers to protect data from unintended access and modification.
  3. Platform Independent
    • “write once, run everywhere.”
    • The portability allows you to easily share pre-compiled pieces of software.
    • If you get asked about running Java on different operating systems on the 1Z0-815 exam, the answer is that the same class files run everywhere.
  4. Robust
    • One of the major advantages of Java over C++ is that it prevents memory leaks.
    • Java manages memory on its own and does garbage collection automatically.
    • Bad memory management in C++ is a big source of errors in programs.
  5. Simple
    • Java was intended to be simpler to understand than C++.
    • In addition to eliminating pointers, it got rid of operator overloading.
    • In C++, you could write a + b and have it mean almost anything.
  6. Secure
    • Java code runs inside the JVM. This creates a sandbox that makes it hard for Java code to do evil things to the computer it is running on.
  7. Multithreaded
    • Java is designed to allow multiple pieces of code to run at the same time. There are also many APIs to facilitate this task.
  8. Backward Compatibility
    • The Java language architects pay careful attention to making sure old programs will work with later versions of Java. While this doesn’t always occur, changes that will break backward compatibility occur slowly and with notice.
    • Deprecation is a technique to accomplish this where code is flagged to indicate it shouldn’t be used. This lets developers know a different approach is preferred so they can start changing the code.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Understanding the Java Class Structure

A
  • Class is the java basic building blocks.
  • When defining a class, you describe all the parts and characteristics of one of those building blocks.
  • Other building blocks such as interfaces, records, and enums.
  • To use most classes, you have to create objects.
  • An object is a runtime instance of a class in memory.
  • An object is often referred to as an instance since it represents a single representation of the class.
  • All the various objects of all the different classes represent the state of your program.
  • A reference is a variable that points to an object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is class?

A

Class is the java basic building blocks, a template used to create objects and to define object data types and methods.

A class is the blueprint from which individual objects are created.

A Java class is a blueprint or template from which objects are created. It defines the data and methods that will be present in the objects of that class.

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

What are the syntax rules for defining a Java class?
(WIP)

A
  1. Keyword: Start with the keyword ‘class’.
  2. Class Name: Followed by the name of the class (identifier).
  3. Class Body: Enclosed within curly braces {}.
  4. Fields: Define fields (variables) to represent data.
  5. Constructors: Optionally include constructors to initialize objects.
  6. Methods: Define methods (functions) to perform operations.
  7. Access Modifiers: Optionally specify access modifiers (public, private, protected).
  8. Other Modifiers: Optionally include other modifiers (final, abstract, static).
  9. Comments: Include comments for code documentation (optional but recommended).
  10. Semicolon: End the class definition with a semicolon (;) if it is declared within a package and not the main class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
A

In Java programs, classes are the basic building blocks. When defining a class, you describe all the parts and characteristics of one of those building blocks.

To use most classes, you have to create objects.

An object is a runtime instance of a class in memory.

An object is often referred to as an instance since it represents a single representation of the class.

All the various objects of all the different classes represent the state of your program.

A reference is a variable that points to an object.

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

What are Java class primary elements?

A
  1. method
  2. field
    Together these are called the members of the class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

FIELDS AND METHODS

A

Java classes have two primary elements:
methods, often called functions or procedures in other languages, and fields, more generally known as variables.
Together these are called the members of the class.
Variables hold the state of the program, and methods operate on that state.

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

What is object?

A

An object is a runtime instance of a class in memory. An object is often referred to as an instance since it represents a single representation of the class.

  1. A Java object is an instance of a class.
  2. It is created using the ‘new’ keyword followed by the class name, and it represents a real-world entity or concept in a Java program.
  3. Objects encapsulate data (fields) and behavior (methods) defined by their class.
  4. Each object has its own set of instance variables and methods, independent of other objects of the same class.
  5. Objects interact with each other by invoking methods and accessing each other’s fields.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is reference?

A

A reference is a variable that points to an object.

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

Class declaration

A
1:  public class Animal {
2:  }
  • Line 1 includes the public keyword, which allows other classes to use it.
  • The class keyword indicates you’re defining a class.
  • Animal gives the name of the class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Add variable in class

A
1:  public class Animal {
2:  String name;
3:  }
  • Line 2, we define a variable named name. We also declare the type of that variable to be String.
  • A String is a value that we can put text into, such as “this is a string”.
  • String is also a class supplied with Java.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Add method in class

A
1:  public class Animal {
2:      String name;
3:      public String getName() {
4:          return name;
5:      }
6:      public void setName(String newName) {
7:          name = newName;
8:      }
9:  }
  • On lines 3–5, we define a method. A method is an operation that can be called.
    • Again, public is used to signify that this method may be called from other classes.
    • Next comes the return type in this case, the method returns a String.
  • On lines 6–8 is another method.
    • This one has a special return type called void. The void keyword means that no value at all is returned.
    • This method requires that information be supplied to it from the calling method; this information is called a parameter.
    • The setName() method has one parameter named newName, and it is of type String.
    • This means the caller should pass in one String parameter and expect nothing to be returned.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Class declaration
(WIP)

A

Class declaration in Java refers to the process of defining a new class. It involves specifying the structure and behavior of the class, including its fields (variables), constructors, and methods. Here’s a breakdown of what class declaration entails:

  1. Access Modifier: This determines the visibility of the class and its accessibility from other classes. Java provides four access modifiers: public, protected, private, and default (no modifier).
  2. Keyword: The keyword class is used to declare a new class.
  3. Class Name: Following the class keyword, you specify the name of the class. This name should be a valid identifier and follow Java’s naming conventions.
  4. Class Body: Enclosed within curly braces {}, the class body contains all the members of the class, including fields, constructors, and methods.
  5. Fields (Variables): These are the variables declared within the class to hold data. Fields represent the state of objects created from the class.
  6. Constructors: Constructors are special methods responsible for initializing objects of the class. They have the same name as the class and may take parameters to set initial values to the object’s state.
  7. Methods: Methods define the behavior of objects. They encapsulate functionality and can manipulate the object’s state or perform operations.

Example:
public class MyClass {
// Class body containing fields, constructors, and methods
}

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

Class with field and method

A
public class Animal {
    String name;
    public String getName() {
         return name;
     }
     public void setName(String newName) {
         name = newName;
     }
 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is method signature?

A

The method name and parameter types are called the method signature.

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

Type of Java Comment?

A
  1. A single-line comment
// comment until end of line
  1. **A multiple-line comment (also known as a multiline comment) **
/* Multiple
 * line comment
 */

3.** Javadoc comment**:

/**
 * Javadoc multiple-line comment
 * @author Jeanne and Scott
 */
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Java Comment

A
  1. A single-line comment begins with two slashes. The compiler ignores anything you type after that on the same line.
// comment until end of line
  1. A multiple-line comment (also known as a multiline comment) includes anything starting from the symbol /* until the symbo*/. People often type an asterisk * at the beginning of each line of a multiline comment to make it easier to read, but you don’t have to.
/* Multiple
* line comment
*/
  1. Javadoc comment:
    This comment is similar to a multiline comment, except it starts with /**. This special syntax tells the Javadoc tool to pay attention to the comment. Javadoc comments have a specific structure that the Javadoc tool knows how to read. You probably won’t see a Javadoc comment on the exam. Just remember it exists so you can read up on it online when you start writing programs for others to use.
/**
* Javadoc multiple-line comment
* @author Jeanne and Scott
*/
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

CLASSES VS. FILES

A
  1. Most of the time, each Java class is defined in its own .java file.
  2. Java does not require that the class be public.
  3. You can even put two classes in the same file.
  4. Only one of the classes in the file is allowed to be public.
  5. If you do have a public class, it needs to match the filename.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

CLASSES VS. FILES

A
  • Most of the time, each Java class is defined in its own .java file.
  • It is usually public, which means any code can call it.
  • Interestingly, Java does not require that the class be public.
    For example, this class is just fine:
1: class Animal {
2:    String name;
3: }
  • You can even put two classes in the same file.
  • When you do so, at most one of the classes in the file is allowed to be public.
    That means a file containing the following is also fine:
1: public class Animal {
2:    private String name;
3: }
4: class Animal2 {
5: }
  • If you do have a public class, it needs to match the filename.
  • The declaration public class Animal2 would not compile in a file named Animal.java.
  • In Chapter 7, we will discuss what access options are available other than public.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

main()

A
  • A Java program begins execution with its main() method.
  • A main() method is the gateway between the startup of a Java process, which is managed by the Java Virtual Machine (JVM), and the beginning of the programmer’s code.
  • The JVM calls on the underlying system to allocate memory and CPU time, access files, and so on.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

valid main()

A
public static void main(String []args) { }
public static void main(String args[]) { }
public static void main(String...args) { }
public strictfp static void main(String[] args) { }
public static void main(final String[] args) { }
final static synchronized strictfp void main(final String[] args) { }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

CREATING A MAIN() METHOD

A
public class Zoo {
   public static void main(String[] args) {
     System.out.println("Welcome!");
   }
}
30
Q

The rules for what a Java code file contains, and in what order, are more detailed than what we have explained so far (there is more on this topic later in the chapter). To keep things simple for now, we’ll follow this subset of the rules:

A
  • Each file can contain only one public class.
  • The filename must match the class name, including case, and have a .java extension.
31
Q

Compile and execute notes

A
  1. To compile Java code, the file must have the extension .java.
  2. The name of the file must match the name of the class.
  3. The result is a file of bytecode by the same name, but with a .class filename extension.
  4. Remember that bytecode consists of instructions that the JVM knows how to execute.
  5. Notice that we must omit the .class extension to run Zoo.java.
  6. Each file can contain only one public class.
  7. The filename must match the class name, including case, and have a .java extension.
  8. If the Java class is an entry point for the program, it must contain a valid main() method.
32
Q

Valid main() method

A
  1. main() method is required, will throw an error if we try execute the class.
  2. public access modifier is required, will throw an error if we try execute the class.
  3. static is required, will throw an error if we try execute the class.
  4. void return type is required, will throw an error if we try execute the class.
  5. main() method’s parameter list, represented as an array of java.lang.String objects. In practice, you can write any of the following:
 String[] args
 String args[]
 String... args;
 String[] options
 String options []
 String... options;
33
Q

Optional Modifiers in main() Methods

A
public final static void main(final String[] args) {}
34
Q

PASSING PARAMETERS TO A JAVA PROGRAM

A
  1. array indexes begin with 0
public class Zoo {
   public static void main(String[] args) {
      System.out.println(args[0]);
      System.out.println(args[1]);
   }
}
  1. If you want spaces inside an argument, you need to use quotes
javac Zoo.java
java Zoo "San Diego" Zoo

San Diego
Zoo
  1. output as String values
javac Zoo.java
java Zoo Zoo 2

Zoo
2
  1. Will throw exception if did not pass enough arguments
Zoo
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:  Index 1 out of bounds for length 1
   at Zoo.main(Zoo.java:4)
35
Q

RUNNING A PROGRAM IN ONE LINE

A
  1. Starting in Java 11, you can run a program without compiling it first
  2. This feature is called launching single-file source-code programs.
  3. if your program has two .java files, you still need to use javac.

ex:

public class SingleFileZoo {
   public static void main(String[] args) {
      System.out.println("Single file: " + args[0]);
   }
}

java SingleFileZoo.java Cleveland
36
Q

Running programs
Differences between this new feature(Single-file source-code) and the traditional way of compiling

A

Full command
* ex:

 javac HelloWorld.java 
 java HelloWorld
  • Produces a class file
  • For any program
  • Can import code in any available Java library

Single-file source-code command
* ex:

java HelloWorld.java
  • Fully in memory
  • For programs with one file
  • Can only import code that came with the JDK
37
Q

Import package

A
import java.util.Random;  // import tells us where to find Random
public class ImportExample {
   public static void main(String[] args) {
      Random r = new Random();  
      System.out.println(r.nextInt(10));  // print a number 0-9
   }
}
38
Q

Understanding Package Declarations and Imports

A
  1. Java classes are grouped into packages
  2. The import statement tells the compiler which package to look in to find a class.
  3. Java only looks for class names in the package.
  4. If package name begins with java or javax, this means it came with the JDK.
  5. package name ex: com.amazon.javabook
  6. Java calls more detailed packages child packages.
39
Q
public class ImportExample {
public static void main(String[] args) {
Random r = new Random(); // DOES NOT COMPILE
System.out.println(r.nextInt(10));
}
}
A

Random cannot be resolved to a type

import java.util.Random; // import tells us where to find Random
public class ImportExample {
public static void main(String[] args) {
Random r = new Random();
System.out.println(r.nextInt(10)); // print a number 0-9
}
}
40
Q

If it begins with java or javax, this means it came with the JDK.

A
41
Q

The rule for package names is that they are mostly letters or numbers separated by periods (.).
Technically, you’re allowed a couple of other characters between the periods (.). The rules are the same as for variable names,

A
42
Q

import WILDCARDS

A
  1. Classes in the same package are often imported together.
  2. You can use a shortcut to import all the classes in a package.
  3. The * is a wildcard that matches all classes in the package.
  4. The compiler figures out what’s actually needed.
  5. Which approach you choose is personal preference—or team preference if you are working with others on a team.
    * Listing the classes used makes the code easier to read, especially for new programmers.
    * Using the wildcard can shorten the import list.
43
Q

WILDCARDS example

A
import java.util.*;    // imports java.util.Random among other things
public class ImportExample {
   public static void main(String[] args) {
      Random r = new Random();
      System.out.println(r.nextInt(10));
   }
}
44
Q
import java.util.*; // imports java.util.Random among other things
public class ImportExample {
public static void main(String[] args) {
Random r = new Random();
System.out.println(r.nextInt(10));
}
}
A

The * is a wildcard that matches all classes in the package.

It doesn’t import child packages, fields, or methods; it imports only classes.

45
Q

Which package is automatically imported?

A

java.lang

There’s one special package in the Java world called
java.lang. This package is special in that it is automatically imported.

46
Q
1: import java.lang.System;
2: import java.lang.*;
3: import java.util.Random;
4: import java.util.*;
5: public class ImportExample {
6: public static void main(String[] args) {
7: Random r = new Random();
8: System.out.println(r.nextInt(10));
9: }
10: }
A

The answer is that three of the imports are redundant. Lines 1 and 2 are redundant because everything in java.lang is automatically considered to be imported. Line 4 is also redundant in this example because Random is already imported from java.util.Random. If line 3 wasn’t present, java.util.* wouldn’t be redundant, though, since it would cover importing Random.

47
Q

What imports do you think would work to get this code to compile?

public class InputImports {
public void read(Files files) {
Paths.get("name");
}
}
A

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;
48
Q
A

Now let’s consider some imports that don’t work.

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.*; // NO GOOD - you cannot import methods
// only class names
49
Q

Invalid import

A
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.*; // NO GOOD - you cannot import methods
                              // only class names
50
Q

Import naming conflict class

A

If you explicitly import a class name, it takes precedence over any wildcards present.

51
Q

NAMING CONFLICTS

A

common example of this is the Date class. Java provides implementations of java.util.Date and java.sql.Date.

52
Q
import java.util.*;
import java.sql.*; // causes Date declaration to not compile

When the class is found in multiple packages, Java gives you a compiler error.

error: reference to Date is ambiguous
Date date;
^

both class java.sql.Date in java.sql and class java.util.Date in java.util match

A
53
Q

What import could we use if we want the java.util.Date version?

public class Conflicts {
Date date;
// some more code
}
A

The answer should be easy by now. You can write either import java.util.*; or import java.util.Date;.

54
Q
import java.util.Date;
import java.sql.*;
A

If you explicitly import a class name, it takes precedence
over any wildcards present.

55
Q
import java.util.Date;
import java.sql.Date;
A

Java is smart enough to detect that this code is no good. As a programmer, you’ve claimed to explicitly want the default to be both the java.util.Date and java.sql.Date implementations. Because there can’t be two defaults, the compiler tells you the following:

error: reference to Date is ambiguous
Date date;
^

both class java.util.Date in java.util and class java.sql.Date in java.sql match

56
Q

How to handle class NAMING CONFLICTS?

A

you can pick one to use in the import and use the other’s fully qualified class name [the package name, a period (.), and the class name] to specify that it’s special. Here’s an example:

import java.util.Date;
 
public class Conflicts {
   Date date;
   java.sql.Date sqlDate;
 
}
public class Conflicts {
   java.util.Date date;
   java.sql.Date sqlDate;
 
}
57
Q

What is default package?

A

special unnamed package that you should use only for throwaway code.

58
Q

Suppose we have these two classes in the C:\temp directory:

package packagea;
public class ClassA {
}
package packageb;
import packagea.ClassA;
public class ClassB {
public static void main(String[] args) {
ClassA a;
System.out.println("Got it");
}
}
A

When you run a Java program, Java knows where to look for those package names. In this case, running from C:\temp works because both packagea and packageb are underneath it.

What do you think happens if you run java packageb/ClassB.java?
This does not work. Remember that you can use the java command to run a file directly only when that program is contained within a single file. Here, ClassB.java relies on ClassA.

59
Q

COMPILING WITH WILDCARDS

A

You can use an asterisk to specify that you’d like to include all Java files in a directory.

javac packagea/*.java packageb/*.java
60
Q

USING AN ALTERNATE DIRECTORY

A
  1. The -d option specifies this target directory.
  2. Java options are case sensitive.
javac -d classes packagea/ClassA.java packageb/ClassB.java
61
Q

CLASSPATH OPTIONS

A

1. -cp option is the short form.
2. -classpath
3. –class-path

62
Q

COMPILING WITH JAR FILES

A

Windows:

java -cp ".;C:\temp\someOtherLocation;c:\temp\myJar.jar" myPackage.MyClass

macOS/Linux:

java -cp ".:/tmp/someOtherLocation:/tmp/myJar.jar" myPackage.MyClass
63
Q

CREATING A JAR FILE

A
jar -cvf myNewFile.jar .
jar --create --verbose --file myNewFile.jar .
jar -cvf myNewFile.jar -C dir .
64
Q

RUNNING A PROGRAM IN ONE LINE WITH PACKAGES

A
package singleFile;
 
import java.util.*;
 
public class Learning {
   private ArrayList list;
   public static void main(String[] args) {
      System.out.println("This works!");
   }
}

java Learning.java            // from within the singleFile directory
java singleFile/Learning.java // from the directory above singleFile
65
Q

Ordering Elements in a Class

A
  1. Package declaration, optional
  2. Import statements, optional
  3. Class declaration, required
  4. Field declarations, optional
  5. Method declarations, optional
66
Q

Remember that extra whitespace doesn’t matter in Java syntax. The exam may use varying amounts of whitespace to trick you.

A
67
Q

COMPILING AND RUNNING CODE WITH PACKAGES

A

Setup procedure by operating system

68
Q

Setup procedure by operating system

A
  • Create first class.
    Windows: C:\temp\packagea\ClassA.java
    Mac/Linux: /tmp/packagea/ClassA.java
  • Create second class.
    Windows: C:\temp\packageb\ClassB.java
    Mac/Linux: /tmp/packageb/ClassB.java
  • Go to directory.
    Windows: cd C:\temp
    Mac/Linux: cd /tmp
69
Q
A
70
Q

keyword

A

Java calls a word with special meaning a keyword.