diff --git a/adt-and-links/adt-and-links.md b/adt-and-links/adt-and-links.md index 7915bbd1..5af1953f 100644 --- a/adt-and-links/adt-and-links.md +++ b/adt-and-links/adt-and-links.md @@ -1,6 +1,6 @@ # ADTs and Lists Tutorial -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) ## Introduction diff --git a/cla/cla.md b/cla/cla.md index 723447c0..2b50c592 100644 --- a/cla/cla.md +++ b/cla/cla.md @@ -1,6 +1,6 @@ # Command-Line Arguments -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) When working in a Unix-like environment, programs are launched when the user enters the program's name into the shell (i.e., they type it in, then press @@ -9,34 +9,35 @@ pieces of information, called **command-line arguments**, after the program's name in order to adjust the program's settings and supply values that the program needs to execute. For example, consider using `ls` to list all of the entries in `~/public_html` using the long listing format (`-l`), including -files that being with a dor (`-a`): +hidden files that begin with a dot `.` (`-a`): ``` $ ls -l -a ~/public_html ``` +In the example above, the base command (program) is `ls` and the command-line +arguments used are `-l`, `-a`, and `~/public_html`. Each of the command-line +arguments provides information to the program about how it should run. + When the program is launched, the command-line arguments are passed into -to the program through its `main` method. Like many Unix programs, `ls` is +to the program through its `main` method. The program reads these values as +input and determines how to respond. Like many Unix programs, `ls` is written in C, but support for command-line arguments extends to other languges as well, including Java. Let's try it! 1. Create a directory for this tutorial called `cs1302-cla`, then change into it. 1. Create a `src` and `bin` directory, then create the `.java` file for a class - called `ArgTester` in a package called `cs1302.cla` such that the `src` directory - is the _default package for source code_. + called `ArgTester` and place `ArgTester.java` in the `src` directory. ``` cs1302-cla ├── bin └── src - └── cs1302 - └── cla - └── ArgTester.java + └── ArgTester.java ``` -1. In `ArgTester.java`, add the appropriate package statement, then - add the declaration for the `ArgTester` class. +1. In `ArgTester.java`, add the declaration for the `ArgTester` class. 1. In your `ArgTester` class, add the following `main` method: @@ -52,16 +53,20 @@ languges as well, including Java. Let's try it! 1. Take a few minutes to carefully read through the code above. Try and understand what it's doing. Note: Up until this point, you've always typed `String[] args` as a parameter to `main` but you've - never used it. That parameter is a reference to an array of command-line arguments. + probably never used it. That parameter is a reference to an array containing the command-line arguments. 1. Compile the `ArgTester` class, specifying `bin` as the destination directory. -1. Run `cs1302.cla.ArgTester` as usual using the `java` command. Here is what the command looks + ``` + javac -d bin ArgTester.java + ``` + +1. Run `ArgTester` as usual using the `java` command. Here is what the command looks like with the expected program output, assuming you are running it from the `cs1302-cla` directory: ``` - $ java -cp bin cs1302.cla.ArgTester + $ java -cp bin ArgTester arguments: ``` @@ -71,10 +76,10 @@ languges as well, including Java. Let's try it! 1. Now try the following command: ``` - $ java -cp bin cs1302.cla.ArgTester one two three + $ java -cp bin ArgTester one two three ``` - What happened? It looks like the for-loop iterated. The array referred to by `args` is not + What happened when you ran it? It looks like the for-loop iterated. The array referred to by `args` is not empty. That's right, we've actually used the `args` array for something! Here's the expected output: @@ -92,15 +97,15 @@ languges as well, including Java. Let's try it! different command-line arguments are parsed. Try the following commands: ``` - $ java -cp bin cs1302.cla.ArgTester "one two" three + $ java -cp bin ArgTester "one two" three ``` ``` - $ java -cp bin cs1302.cla.ArgTester --help "some topic" + $ java -cp bin ArgTester --help "some topic" ``` ``` - $ java -cp bin cs1302.cla.ArgTester --string "my \"awesome\" day" + $ java -cp bin ArgTester --string "my \"awesome\" day" ``` 2. That's it! The rest is purely in the realm of code. We've shown you how command-line diff --git a/components/components.md b/components/components.md index 223ca1df..79a76900 100644 --- a/components/components.md +++ b/components/components.md @@ -1,6 +1,6 @@ # JavaFX Custom Component Tutorial -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Spring 2023](https://img.shields.io/badge/Approved%20for-Spring%202023-magenta) JavaFX is a library for creating and delivering applications with graphical user interfaces (GUIs) in Java. In this tutorial, we will use JavaFX 17. The API documentation for @@ -26,8 +26,8 @@ using inheritance and polymorphism to emphasize code reuse. If you encounter problems in this step, then please ensure that you have followed the instructions provided at the beginning of the semester for - [MacOS users](https://github.com/cs1302uga/cs1302-exercises/blob/master/misc/MacOS.md) or - [Windows 10 users](https://github.com/cs1302uga/cs1302-exercises/blob/master/misc/Windows10.md). + [MacOS users](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/setup/MacOS.md) or + [Windows 10 users](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/setup/Windows.md). Also, the `-X` and `-Y` options can be used individually with or without each other. See the manual page for `ssh` for more information about the differences between @@ -50,14 +50,14 @@ using inheritance and polymorphism to emphasize code reuse. ``` 1. Compile and run the provided code without any errors or warnings. If you need a reminder of the compile commands, review - the relevant parts of the [JavaFX Tutorial](https://github.com/cs1302uga/cs1302-tutorials/blob/master/javafx/javafx.md). + the relevant parts of the [JavaFX Tutorial](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/javafx/javafx.md). We recommend creating a compile script so you don't have to retype these commands. If you completed the previous steps correctly, your app should look similar to the screenshot below. You may also find it helpful to review the scene graph for this app (also seen below). -
+
                                     --|
                          Stage            |
                            |              |
@@ -77,8 +77,6 @@ using inheritance and polymorphism to emphasize code reuse.
 1. The default size for the image in the ImageView container is 500x500 (Even though the image says 300x300). 
    Do a quick google search for "500x500 images" and load one or two of the images to make sure the app is 
    functioning properly. **Note:** the `Image` class only supports the BMP, GIF, JPEG, and PNG filetypes.
-
-1. Congratulations on compiling and running a good looking app!
    
 ## Creating a Custom Component
 
@@ -88,7 +86,7 @@ using inheritance and polymorphism to emphasize code reuse.
    reusable component based on the set of existing components contained 
    in the application.
    
-   Consider the following containment hieararchy:
+   Consider the following containment hierarchy:
    
    ```
                                                              --|
@@ -163,14 +161,14 @@ using inheritance and polymorphism to emphasize code reuse.
    1. The class should contain the `static` constants from
       the `ImageApp` class. They can be cut and paste directly
       from that class, perhaps changing them to `protected`
-      visibility if you wish to do so.
-
-   1. Your class should have instance variables for the other
-      nodes in the sub-graph (make sure to import all required classes). 
-      For example, you will need
-      an instance variable called `urlLayer` of type `HBox`
-      as well as instance variables for the remaining nodes.
-      For the most part, these can be cut and paste from the
+      visibility if you wish to do so. That way they can be accessed
+      by the other classes in the package.
+
+   1. Your `ImageLoader` class should contain instance variables for the
+      nodes in the sub-graph above (`HBox`, `TextField`, `Button`, and `ImageView`).
+      You do not need an instance variable for `VBox` because the `ImageLoader` itself
+      is a `VBox`!
+      For the most part, the required instance variables can be cut and paste from the
       `ImageApp` class. Any instance variables that you move
       into the `ImageLoader` class can be removed from `ImageApp`. You can
       also remove any imports that are no longer needed in `ImageApp`.
@@ -184,7 +182,9 @@ using inheritance and polymorphism to emphasize code reuse.
       Use this knowledge to add your newly created nodes to the
       sub-graph rooted at `this` similar to how they are 
       added to the `VBox` node in the `ImageApp` class. 
-      Your code will likely look something like this:
+      Your code will likely look something like the code below with 
+      additional statements to instantiate the components and connect
+      them:
 	  
       ```java
       public ImageLoader() {
@@ -195,23 +195,30 @@ using inheritance and polymorphism to emphasize code reuse.
       } // ImageLoader
 	  ```
 	  
-   1. If you haven't done so already, remove the code to create the subgraph
-      (`HBox`, `ImageView`, `TextField`, and `Button`) from the `start` method 
-      of `ImageApp`. All of that code will be run when we create a new `ImageLoader`
-      object.
+   1. Remove the code to create the subgraph
+      (`HBox`, `ImageView`, `TextField`, and `Button`) from the constructor and `init` methods
+      of `ImageApp`. All of that code will now be run when we create a new `ImageLoader`
+      object. This includes the code to initialize the `ImageView` and set up the button handler.
+      
+   1. Take a moment to think about what you are doing. You have created your own, custom class that extends
+      the JavaFX `VBox` class. This class is essentially a `VBox` with some of the components
+      built into it. Once we complete this class, we will be able to add objects of this class to a
+      scene graph and all the messy details of creating that object will be hidden inside of `ImageLoader`!
       
-   1. Move the `loadImage` method from `ImageApp` to `ImageLoader`.
-      Don't forget to set the handler on your `ImageLoader`'s button.
+   1. Now, move the `loadImage` method from `ImageApp` to `ImageLoader`. This is the method that is
+      called when the button is clicked. Don't forget to set the handler on your `ImageLoader`'s button.
       
    1. You've probably noticed that `ImageApp` has significantly decreased
       in size.  We moved a lot of that code over into our custom component!
-      Now, instantiate two objects of type `ImageLoader` within the `start`
-      method of `ImageApp`.
+      Now, instantiate two objects of type `ImageLoader` within the constructor
+      of `ImageApp`.
       
-   1. Instantiate an `HBox` object within the `start` method of `ImageApp`. This
+   1. Create an `HBox` instance variable in the `ImageApp` class and instantiate 
+      it within the constructor. This
       will serve as the container for our `ImageLoader` objects. Set
       the `spacing` property of the `HBox` to 10 by passing 10 into the `HBox`
-      constructor. Now, Add the two `ImgLoader` objects to the `HBox` object of `ImageApp`.
+      constructor. Now, in the `init` method, add the two `ImgLoader` objects to 
+      the `HBox` object of `ImageApp`.
       
    1. Make sure you pass the reference to your newly created `HBox` object into the
       `Scene` constructor within the `start` method of `ImageApp`. Previously, the 
@@ -221,7 +228,7 @@ using inheritance and polymorphism to emphasize code reuse.
    1. Compile and run your new app and load up a few 500x500 images.  You 
       should see something like the image below:
       
-      
+      
       
    1. Imagine all the ways you could use your new, custom component! Also, think
       of other custom components you could build by extending existing JavaFX
diff --git a/components/setup.sh b/components/setup.sh
index ab83aa9f..e44ae697 100644
--- a/components/setup.sh
+++ b/components/setup.sh
@@ -1,5 +1,5 @@
 #!/bin/bash
-
+1;95;0c
 TUTNAME="components"
 DIR="cs1302-$TUTNAME"
 if [ ! -d $DIR ]; then
@@ -20,4 +20,4 @@ if [ ! -d $DIR ]; then
   echo "subdirectory $DIR successfully created"
 else
   >&2 echo "subdirectory $DIR already exists"
-fi  
+fi
diff --git a/components/src/cs1302/gui/ImageApp.java b/components/src/cs1302/gui/ImageApp.java
index 508c52ce..4bc67d1d 100644
--- a/components/src/cs1302/gui/ImageApp.java
+++ b/components/src/cs1302/gui/ImageApp.java
@@ -20,16 +20,13 @@
  */
 public class ImageApp extends Application {
 
-    Stage stage;
-    Scene scene;
-
     /** The root container for the application scene graph */
     VBox vbox;
 
     /** The container for the url textfield and the load image button */
     HBox urlLayer;
-    TextField urlField;
-    Button loadImage;
+    TextField url;
+    Button loadButton;
 
     /** The container for the loaded image */
     ImageView imgView;
@@ -42,66 +39,90 @@ public class ImageApp extends Application {
     private static final int DEF_HEIGHT = 500;
     private static final int DEF_WIDTH = 500;
 
+    public ImageApp() {
+        System.out.println("2) Creating an instance of the ImageApp Application");
+
+        // Initialize the instance variables
+        vbox = new VBox();
+        urlLayer = new HBox(8);
+        imgView = new ImageView();
+        loadButton = new Button("Load");
+        url = new TextField("https://");
+    } // ImageApp
+
+        @Override
+    public void init() {
+        System.out.println("3) Executing the init method");
+
+        // Connect the components in the scene graph
+        vbox.getChildren().addAll(urlLayer, imgView);
+        urlLayer.getChildren().addAll(url, loadButton);
+        HBox.setHgrow(url, Priority.ALWAYS);
+        // load the default image
+        Image defaultImage = new Image(DEFAULT_IMG);
+
+        // add the image to the imageview
+        imgView.setImage(defaultImage);
+
+        // Create the handler for our button using an anonymous class.
+        // This approach isn't used but it is left in so students can
+        // compare with the lambda below.
+        /*
+        EventHandler mouseClickHandler = new EventHandler() {
+                @Override
+                public void handle(ActionEvent e) {
+                    this.loadImage(e);
+                } // handle
+            };
+        */
+
+        // Create the handler for our button using a lambda expression.
+        // This is a more concise than using an anonymous class but it
+        // accomplishes the same goal.
+        EventHandler mouseClickHandler = (ActionEvent e) -> {
+            this.loadImage(e);
+        };
+
+        loadButton.setOnAction(mouseClickHandler);
+    } // init
+
     /**
      * The entry point for our image viewer application.
      *
      * @param stage A reference to the stage object (window) created by the system.
-     */ 
+     */
     public void start(Stage stage) {
-        this.stage = stage;
-        
-        // Initializing the nodes for the scene graph
-        vbox = new VBox();
-        urlLayer = new HBox(10);
-        urlField = new TextField("https://");
-        loadImage = new Button("Load");
-
-        // Adding the textfield and load image button the the containing hbox
-        urlLayer.getChildren().addAll(urlField, loadImage);
-
-        // Sets the textfield to grow, as necessary, to fill the hbox
-        HBox.setHgrow(urlField, Priority.ALWAYS);
+        System.out.println("4) Executing the start method");
 
-        // Load the default image with the default dimensions
-        Image img = new Image(DEFAULT_IMG, DEF_HEIGHT, DEF_WIDTH, false, false);
-
-        // Add the image to its container and preserve the aspect ratio if resized
-        imgView = new ImageView(img);
-        imgView.setPreserveRatio(true);
-
-        // EventHandler for our button using a fancy method reference.
-        //EventHandler loadImgHandler = this::loadImage;
-        loadImage.setOnAction(this::loadImage);
-
-        // Add the hbox and imageview to the containing vbox and set the vbox
-        // to be the root of the scene
-        vbox.getChildren().addAll(urlLayer, imgView);
-        scene = new Scene(vbox);
+        // Add the root of the scene graph to the stage.
+        Scene scene = new Scene(vbox);
 
         // Set up the stage and set it to be visible
-        // stage.setResizable(false);
         stage.setScene(scene);
         stage.setTitle("1302 Image Viewer!");
         stage.sizeToScene();
         stage.show();
-        
     } // start
 
     /**
      * Students will provide javadoc comments here.
      *
      * @param e source event
-     */ 
+     */
     private void loadImage(ActionEvent e) {
-
         try {
-            Image newImg = new Image(urlField.getText(), DEF_HEIGHT, DEF_WIDTH, false, false);
+            Image newImg = new Image(url.getText(), DEF_HEIGHT, DEF_WIDTH, false, false);
             imgView.setImage(newImg);
         } catch(IllegalArgumentException iae) {
             System.out.println("The supplied URL is invalid");
         } // try
-        
     } // loadImage
-    
-} // ImageApp
 
+    @Override
+    public void stop() {
+        // Won't be used by us. Typically used for application cleanup.
+
+        System.out.println("6) Executing the stop method");
+    } // stop
+
+} // ImageApp
diff --git a/components/src/cs1302/gui/ImageDriver.java b/components/src/cs1302/gui/ImageDriver.java
index f84e5ae8..853e1970 100644
--- a/components/src/cs1302/gui/ImageDriver.java
+++ b/components/src/cs1302/gui/ImageDriver.java
@@ -9,6 +9,7 @@ public static void main(String[] args) {
             Application.launch(ImageApp.class, args);
         } catch (Exception e) {
             System.err.println(e);
+            e.printStackTrace();
             System.err.println("Likely due to X11 timeout. Logout and log back in...");
             System.exit(1);
         } // try
diff --git a/emacs/emacs.md b/emacs/emacs.md
index 63f65a7e..8ebb1696 100644
--- a/emacs/emacs.md
+++ b/emacs/emacs.md
@@ -1,6 +1,6 @@
 # Emacs Tutorial
 
-![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple)
+![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green)
 
 ![Emacs Welcome Screen](welcome.PNG)
 
@@ -40,6 +40,12 @@ If you're interested in learning more about Emacs, check out the [Wikipedia Page
 
 In this tutorial, we will teach you the basics of the Emacs text editor.
 
+Since you will be writing and editing Java code in Emacs, it's important to know the basic shortcuts. We don't
+expect you to memorize all of these shortcuts at this time. Instead, just try to get a basic understanding of
+how Emacs works. You will be practicing with Emacs all semester. We also recommend keeping the 
+[Emacs Reference Card](https://www.gnu.org/software/emacs/refcards/pdf/refcard.pdf) next to you while coding - 
+especially for the first month or two of the course.
+
 ## Control and Meta
 
 Throughout this tutorial we will use `C` to refer to the control key (`CTRL`)
@@ -59,6 +65,9 @@ to understand how to read their associated key bindings so that you can
 successfully make the appropriate keystrokes. In the table below, we'll use
 `KEY(key)` to denote that you should press `key` while holding `KEY` and `(key)`
 to denote that `key` should be pressed without any kind of modifier key.
+For example, `CTRL(x, f)` means to hold `CTRL`, hit `x`, then hit `f`, then release
+`CTRL`. An allternative would be `CTRL(h), (t)` which means to hold `CTRL`,
+hit `h`, release `CTRL`, then hit `t`.
 
 | Command        | Binding   | Alternative | Keystrokes     |
 |----------------|-----------|-------------|----------------|
@@ -66,7 +75,7 @@ to denote that `key` should be pressed without any kind of modifier key.
 | Emacs tutorial | `C-h t`   |             | `CTRL(h), (t)` |
 
 If a binding has consecutive occurences of either the `C` or `M` modifier keys, 
-then there is no need to release the modifer key between those occurances. This 
+then there is no need to release the modifer key between those occurences. This 
 can be seen in the first example, where both of the following keystroke sequences
 result in `C-x C-f`:
 * `CTRL(x), CTRL(f)`
@@ -215,14 +224,19 @@ navigate to where you want to paste, then yank the text from the kill buffer.
 | `C-w`     | Cut selection (goes into kill buffer)                                  |
 | `M-w`     | Copy selection (goes into kill buffer)                                 |
 | `C-y`     | Paste / Yank (from kill buffer)                                        |
+| `C-x h`   | Select all                                                             |
+
+When you edit source code using Emacs, you can usually use `` to fix the
+indentation for a selected region of code -- this assumes that things like parentheses
+and curly braces, if applicable, are properly closed.
 
 ### Search and Replace
 
 To search for text, you can use the incremental search commands `C-s` and `C-r`,
 which differ only in their search direction. After pressing `C-s`, Emacs will
 display an `I-search:` prompt at the bottom of the screen. When prompted, type 
-the text you want to find, then press `RET`. If multiple occurances are found,
-then repeated calls to `C-s` will cycle through the occurances (`C-g` can be used
+the text you want to find, then press `RET`. If multiple occurences are found,
+then repeated calls to `C-s` will cycle through the occurences (`C-g` can be used
 to stop).
 
 | Binding   | Action                                                                 |
@@ -269,7 +283,8 @@ Some Unix programs recognize that they do not need to reinvent the wheel when a
 case is encountered where multi-line text entry is required. Instead of handling
 the text entry themselves, they invoke your default text editor. On most systems,
 the default text editor is `vi` or `vim`. You can change this by setting the 
-`EDITOR` environmental variable in your `~/.bash_profile` file. 
+`EDITOR` environmental variable in your `~/.bash_profile` file. We recommend adding
+the line below at the end of your current `~/.bash_profile` file:
 
 ```
 export EDITOR=emacs
diff --git a/exceptions/exceptions.md b/exceptions/exceptions1.md
similarity index 51%
rename from exceptions/exceptions.md
rename to exceptions/exceptions1.md
index 5b732674..0634f371 100644
--- a/exceptions/exceptions.md
+++ b/exceptions/exceptions1.md
@@ -1,7 +1,7 @@
 
-# Exceptions
+# Exceptions Part 1
 
-![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple)
+![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green)
 
 ## Prerequisites
 
@@ -18,45 +18,147 @@ you should follow along and take notes.
 * [Definition](#definition)
 * [Avoiding Exceptions](#avoiding-exceptions)
 * [Handling Exceptions](#handling-exceptions)
-* [Checked vs. Unchecked Exceptions](#checked-vs-unchecked-exceptions)
-* [Identifying Checked vs. Unchecked Exceptions](#identifying-checked-vs-unchecked-exceptions)
-* [Multiple Catch Blocks](#multiple-catch-blocks)
-* [Explicitly Throwing Exceptions & Exception Propagation](#explicitly-throwing-exceptions--exception-propagation)
 * [Regarding Scope](#regarding-scope)
 
-## Definition
+## Introduction
 
 In Java, an **exception** is an event that occurs during the execution of a program that
-encounters an error or some kind of exceptional situation. When an exception occurs,
-two things happen:
+encounters an error or some kind of exceptional situation. Often times, students get the
+impression that, when an exception occurs, the only outcome is that the program will crash 
+and produce an obscure error message. For this reason, students often try to avoid exceptions 
+at all costs. In this tutorial, you will see that it is almost always better to let exceptions
+occur and then properly handle them instead of trying to avoid them.
+
+We will demonstrate that exceptions, when used properly, can lead to cleaner code that has 
+fewer bugs. You will see that exceptions are a way of passing a message from one method to 
+another to indicate that something unexpected happened. Exceptions can be both informative and 
+useful and should be handled (properly) instead of avoided.
+
+When an exception occurs, two things happen:
 
 1. an **exception object** is said to be _thrown_; and
 1. the normal flow of control is disrupted.
 
+The exception object that is created contains information about the location and cause of the exception.
+
 You have likely encountered the dreaded
 [`NullPointerException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/NullPointerException.html)
-before reading this tutorial. If not, it's easy to create a program that will
-throw a `NullPointerException` object:
+before reading this tutorial. If you click on the link, you will see that `NullPointerException` is a Java class
+that has constructors and methods that can be called from your programs.
+
+If you haven't see a `NullPointerException` before, it's easy to create a program that will generate one:
 
 ```java
-String s = null;
-if (s.length() > 1) { // <------------------ throws NullPointerException object
-    System.out.println("string length > 1");
-} // if
+public class Exception {
+    public static void main(String[] args) {
+        exception();
+    } // main
+
+    public static void exception() {
+        String s = null;
+
+        if (s.length() > 1) { // causes a NullPointerException because you can't call a method on a null reference.
+            System.out.println("string length > 1");
+        } // if
+    } // exception
+} // Exception
 ```
 
 If you run this code, then the JVM:
-i) throws a `NullPointerException` object on the second line; and
+i) creates a `NullPointerException` object on the second line of the `exception` method; and
 ii) disrupts the normal flow of control to report to the
 user that the exception was thrown and abruptly terminates the program.
-Go ahead and test it out.
 
-In general, there are two ways to deal with exceptions:
+In this example, the `exception` method does not finish executing as it normally would (because of the
+exception) and the program crashes. Please note that the program doesn't crash because an exception occurred. 
+Instead, it crashes because the exception was not *handled* properly.
+
+Go ahead and test it out. Copy/paste this code into a `.java` file on Odin and try to run it. Did it
+do what you expected?
+
+Here is an annotated version of the output produced by the example code:
+
+```
+A. | Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "" is null
+B. |     at Exception.exception(Exception.java:9)
+C. |     at Exception.main(Exception.java:3)
+```
+
+When you see an error message like this, take a few seconds to read through the message to understand what it is
+saying. 
+
+A. The top line tells you that a `NullPointerException` occurred when the `length` method was invoked on
+   a `null` reference. That's very informative. With this information, we can figure out that `s` must have been `null`
+   since `s` is the only reference variable on line 9.
+
+The indented lines starting with `at` in the output are collectively referred to a **stack trace**. The stack trace tells
+the user which methods were active when the program crashed in the order that they were called (from the bottom up). 
+This facilitates faster debugging by allowing you to better understand what was happening in the application when it crashed.
+
+B. The *first* line in the stack trace indicates the **origin** of the exception; that is, it provides the class name,
+   method name, filename, and line number where the exception object was *first* thrown during program execution. Here
+   is a breakdown:
 
-1. avoid them; and
+   ```
+     class name              file name
+      ┌───┴───┐           ┌──────┴─────┐    
+   at Exception.exception(Exception.java:9)
+                └───┬───┘                │
+              method name            line number
+   ```
+
+C. The *last* line in the stack trace indicates the *last executed line* of the *first method executed* by our program;
+   in most cases, this is implictly the `main` method since most Java programs start in `main`. Here is a breakdown:
+
+   ```
+     class name         file name
+      ┌───┴───┐      ┌──────┴─────┐    
+   at Exception.main(Exception.java:3)
+                └─┬┘                │
+            method name         line number
+   ```
+
+The stack trace, when read in reverse order (i.e., from bottom to top), tells us a story about what happened 
+when we ran the program. 
+
+```
+Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "" is null
+     at Exception.exception(Exception.java:9)
+     at Exception.main(Exception.java:3)
+```
+
+In our example, the stack trace tells us that the `main` method was executed until 
+the program got to line 3, then the `exception` method (`Exception.exception`) was called and executed
+until the program got to line 9, the origin of the exception. 
+
+Since the `exception` method does not handle the exception, the exception object **propagated** (i.e., *thrown/passed back*)
+to its calling method. In general, exception objects will continue to propagation back through the calling methods in the
+call stack (i.e., the methods we see in the stack trace) until the program either: 
+i) handles the exception object; or 
+ii) lets the exception propagates out of `main`. 
+
+In our example, the exception propagated from `exception` to `main`, and since the `main` method does not 
+handle the exception, the exception continued to oropagate out of `main` and crash the program. 
+Any time an exception is allowed to propagate out of `main`, the program will crash. It's our job to 
+make sure that we catch exceptions before they cause a crash.
+
+```
+Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "" is null
+     at Exception.exception(Exception.java:9)
+     at Exception.main(Exception.java:3)
+```
+
+Error messages produced when a program crashes from an exception, like the one shown above, are *very* informative 
+for us as programmers; however, they are often confusing, startling, or even scary when encountered by end 
+users who just witnessed the program crash and have no way to use the information in the error message. 
+To prevent our users from seeing these error messages, we need to handle exceptions in one of two ways:
+
+1. avoid them; or
 2. handle them.
 
-## Avoiding Exceptions
+We will talk about each of these in detail in the next two sections. 
+
+## Approach 1: Avoiding Exceptions
 
 To *avoid the exception* in the example above, you need only ensure that you
 do not invoke members (i.e., call methods or access instance variables)
@@ -66,20 +168,20 @@ Here are some examples:
 ```java
 // use an if-statement to check
 if (s != null) {
-    if (s.length() > 1)) {
+    if (s.length() > 1) {
         System.out.println("string length > 1");
     } // if
 } // if
 ```
 
 ```java
-// avoid NPE via short circuiting
+// avoid NullPointerException via short circuiting
 if ((s != null) && (s.length() > 1)) {
     System.out.println("string length > 1");
 } // if
 ```
 
-In general, in order to avoid an exception object, you need to understand the
+In general, in order to avoid an exception, you need to understand the
 conditions in which that exception object is thrown, then write code that
 correctly identifies if those conditions are met prior to the line of code
 that throws the exception object. Although it is relatively easy to amend code
@@ -90,12 +192,12 @@ are thrown in more complicated exceptional situations. Here, we take complicated
 to mean that there are a lot of conditions to check, including some that are
 potentially tricky to identify. Such exceptions are generally handled
 instead of avoided, although there is no reason a combination of both
-handling and avoiding can be employed.
+handling and avoiding can't be employed.
 
-## Handling Exceptions
+## Approach 2: Handling Exceptions
 
 To *handle the exception* in the example above, you need to make use of a
-special control flow snytax known as a **try block** or **try-catch block**.
+special control flow syntax known as a **try block** or **try-catch block**.
 With this syntax, you place code that can throw an exception into the
 `try` block, then place code for how you want to deal with the exception
 in the `catch` block. These two go together, which is why we often
@@ -108,7 +210,7 @@ Here is an example:
 
 ```java
 try {
-    if (s.length() > 1)) {
+    if (s.length() > 1) {
         System.out.println("string length > 1");
     } // if
 } catch (NullPointerException npe) {
@@ -137,173 +239,6 @@ https://www.youtube.com/watch?v=TETdh48t4YM
 IMAGE ALT TEXT
 
 
-## Checked vs. Unchecked Exceptions
-
-In Java, exceptions are either _checked_ or _unchecked_.
-Checked exceptions must be explicitly caught or propagated by the programmer,
-whereas unchecked exceptions may or may not be handled by the programmer.
-Let's look at an example.
-
-1. On Odin, create the class `exceptions.Unchecked` containing the following code:
-
-   ```java
-   package exceptions;
-
-   public class Unchecked {
-       public static void main(String [] args) {
-          int result = 4/0;
-          System.out.println(result);
-       } // main
-   } // Test
-   ```
-
-1. Compile and run `exceptions.Unchecked`. You should get an error message similar to the following
-   when you run the program:
-
-   ```
-   Exception in thread "main" java.lang.ArithmeticException: / by zero
-      at exceptions.Unchecked.main(Unchecked.java:5)
-   ```
-   An [`ArithmeticException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.html)
-   (specifically, a divide by zero) caused our program to crash. Since `ArithmeticException` is an **unchecked exception**, the
-   Java compiler did not force us (the programmer) to catch or propagate this exception.  It is completely up to the programmer to decide
-   whether or not to handle exceptions of this type. You've probably experienced other, unchecked exceptions such as:
-   [`StringIndexOutOfBoundsException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.html),
-   [`NullPointerException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/NullPointerException.html),
-   [`NumberFormatException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/NumberFormatException.html), etc.
-
-1. On Odin, create the class `exceptions.Checked` containing the following code:
-
-   ```java
-   package exceptions;
-
-   import java.util.Scanner;
-   import java.io.File;
-
-   public class Checked {
-       public static void main (String[] args) {
-           File notesFile = new File("notes.txt");
-           Scanner input = new Scanner(notesFile);
-           System.out.println(input.nextLine());
-       } // main
-   } // Checked
-   ```
-
-   In this program, we are reading the first line of the file `notes.txt`. The first line of the `main` method creates a `File` object
-   which is referred to by `notesFile`.  Then, it passes this object reference to the `Scanner` constructor.  As you may have guessed, the
-   `input` object will read its input from the file (not the keyboard).  We will create the `notes.txt` file in a later step.
-
-1. Compile `Checked.java`.  You should get an error similar to the following:
-
-   ```
-   src/exceptions/Checked.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
-      Scanner input = new Scanner(notesFile);
-                      ^
-   ```
-   This error indicates that the `Scanner` constructor throws a `FileNotFoundException`.  `FileNotFoundException` is a
-   **checked exception**.  When a method or constructor call throws a checked exception, the programmer must either:
-      * surround the relevant call with a try-catch or
-      * add a throws clause to the enclosing method (i.e., the method containing the call) to propogate this exception if it occurs.
-
-   In `Checked.java`, the enclosing method is `main`.  We never want to add a `throws` clause to the `main` method as there is no code in
-   our program above the `main` method to handle the exception. To fix `Checked.java`, we will use the first approach.
-
-1. Now, let's modify `Checked.java` to include an appropriate try-catch:
-
-   ```java
-   import java.util.Scanner;
-   import java.io.File;
-   import java.io.FileNotFoundException;
-
-   public class Checked {
-       public static void main (String[] args) {
-           File notesFile = new File("notes.txt");
-           Scanner input = null;
-           try {
-               input = new Scanner(notesFile);
-           } catch(FileNotFoundException e) {
-               System.out.println(e.getMessage());
-           }
-           System.out.println(input.nextLine());
-       } // main
-   } // Checked
-   ```
-
-1. Create a `notes.txt` file in the directory where you will execute the program. Add a single line of text to the file.
-
-1. Execute `exceptions.Checked`.  It should print the first line of `notes.txt`.
-
-## Identifying Checked vs. Unchecked Exceptions
-
-For now, we will use a simple method for checking if an exception is checked or unchecked.
-
-1. Visit the Java API page for [`ArithmeticException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.html).
-
-1. At the top of the page, there is a hierarchy of Java classes which looks like this:
-
-   ArithmeticException Unchecked Example
-
-   You can tell that `ArithmeticException` is an unchecked exception because `java.lang.RuntimeException` is listed in the hierarchy. If
-   you cannot find `java.lang.RuntimeException` in the hierarchy for a given exception, then that tells you it is a checked exception.
-
-1. For an example of a checked exception, see
-[`FileNotFoundException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/FileNotFoundException.html)
-
-## Multiple Catch Blocks
-
-Here is a video that demonstrates how to handle multiple exceptions at the same
-time using multiple catch blocks:
-
-https://www.youtube.com/watch?v=j-GNWvLNLjs
-
-
-IMAGE ALT TEXT
-
-
-## Explicitly Throwing Exceptions & Exception Propagation
-
-Now that you have seen how to handle exceptions in code written by others
-that can throw exceptions, it's important understand how and why you can
-throw exceptions yourself. In Java, the `throw` keyword is used to explicitly
-throw an exception. Here is an example where we create an
-[`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/IllegalArgumentException.html)
-and explicitly throw it:
-
-```java
-throw new IllegalArgumentException("nums array cannot be empty");
-```
-
-Since this line of code is known to throw an exception, we would
-usually want to handle the exception by placing the line in a try block.
-That may not always be ideal. Instead of handling the exception immediately,
-let's make it someone else's responsibility using the `throws` keyword
-in the signature of the method containing the line:
-
-```java
-int computeAverage(double[] nums) throws IllegalArgumentException {
-    if (nums.length == 0) {
-        throw new IllegalArgumentException("nums array cannot be empty");
-    } // if
-    double sum = 0;
-    for (double num : nums) {
-        sum += num;
-    } // for
-    return sum / nums.length;
-} // computeAverage
-```
-
-Using the `throws` keyword, we told Java that the `IllegalArgumentException`
-will not be handled directly in this method. Intead it will be _propagated_
-up to the calling method, i.e., the method or methods, somewhere else, that are
-actually calling `computeAverage`. In that other method, the programmer
-can either handle the exception (using a try-catch) or choose to propagate it again
-by repeating the `throws` in the calling method's signature.
-
-In Java, checked exceptions must either be handled directly using a try-catch
-or progated up using `throws`. Note, while it is possible to place a `throws`
-in the signature of a program's `main` method, doing so is _strongly_ discouraged
-as exceptions propagated past `main` will always cause the program to crash.
-
 ## Regarding Scope
 
 The same basic scoping rules (i.e., what can be seen within a method when curly
@@ -336,8 +271,9 @@ public static void main(String[] args) {
 } // main
 ```
 
-When you attempt to compile this example program, the compiler will emit
-a `cannot find symbol` error similar to the following:
+We recommend trying to compile this code. To do so, you will need to create proper package directories, add your
+class declaration, and any necessary imports to the top. Once everything is in place and you attempt to compile 
+this example program, the compiler will emit a `cannot find symbol` error similar to the following:
 
 ```
 src/cs1302/scope/Example.java:22: error: cannot find symbol
@@ -348,11 +284,11 @@ src/cs1302/scope/Example.java:22: error: cannot find symbol
 1 error
 ```
 
-Issues like simple typos, missing import statements, and even an incorrect
+Issues like simple typos, missing import statements and even an incorrect
 classpath often cause the Java compiler to emit the `cannot find symbol`; however,
 the cause of this particular `cannot find symbol` error is related to the
 scope of the symbol (the variable `file`), which does not extend to a specific
-line of code that attempts to use that symbol, as indicated by error message.
+line of code that attempts to use that symbol, as indicated by the error message.
 
 Since the variable `file` is declared inside the try-block, its scope only
 extends to subsequent lines within the try-block, as illustrated below.
@@ -371,7 +307,9 @@ try {
 // <---- ✗ nor any of the lines below
 ```
 
-There are two high-level strategies for dealing with this kind of scoping issue:
+There are two high-level strategies for dealing with this kind of scoping issue. You should be aware of the first
+strategy but you should always try to use the second strategy as it leads to more elegant solutions that are
+easier to program. These two strategies are outlined below:
 
 1. Increase the symbol's scope by declaring and initializing it on a line
    that precedes the enclosing try-block and changing original declaration to a
@@ -413,10 +351,10 @@ There are two high-level strategies for dealing with this kind of scoping issue:
 
 2. Place code that depends on the symbol within the try-block with the understanding
    that it will be skipped should an exception occur within the try-block before that
-   line (as execution flows to a corresponding catch-block).
+   line (as execution flows to a corresponding catch block).
 
    * This strategy often requires changes to multiple lines of code; however, it also often
-     leads to a more elegent solution, as illustrated below:
+     leads to a more elegant solution, as illustrated below:
 
      ```java
      public static void main(String[] args) {
diff --git a/exceptions/exceptions2.md b/exceptions/exceptions2.md
new file mode 100644
index 00000000..f0b9300b
--- /dev/null
+++ b/exceptions/exceptions2.md
@@ -0,0 +1,204 @@
+
+# Exceptions Part 2
+
+![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green)
+
+## Prerequisites
+
+Before engaging with this tutorial, readers should first complete 
+[Exceptions Part 1](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/exceptions/exceptions1.md).
+To get the most out of this tutorial, you should follow along and take notes.
+
+## Course-Specific Learning Outcomes
+
+* **LO2.b:** Define, throw, and propagate exceptions appropriately in a software solution.
+
+## Table of Contents
+
+* [Checked vs. Unchecked Exceptions](#checked-vs-unchecked-exceptions)
+* [Identifying Checked vs. Unchecked Exceptions](#identifying-checked-vs-unchecked-exceptions)
+* [Multiple Catch Blocks](#multiple-catch-blocks)
+* [Explicitly Throwing Exceptions & Exception Propagation](#explicitly-throwing-exceptions--exception-propagation)
+
+## Checked vs. Unchecked Exceptions
+
+In Java, exceptions are either _checked_ or _unchecked_.
+Checked exceptions must be explicitly caught or propagated by the programmer,
+whereas unchecked exceptions may or may not be handled by the programmer.
+Let's look at an example.
+
+1. On Odin, create the class `exceptions.Unchecked` containing the following code:
+
+   ```java
+   package exceptions;
+
+   public class Unchecked {
+       public static void main(String [] args) {
+          int result = 4/0;
+          System.out.println(result);
+       } // main
+   } // Test
+   ```
+
+1. Do you see where the exception object will be created and thrown? Go ahead and 
+   compile and run `exceptions.Unchecked`. You should get an error message similar to the following
+   when you run the program:
+
+   ```
+   Exception in thread "main" java.lang.ArithmeticException: / by zero
+      at exceptions.Unchecked.main(Unchecked.java:5)
+   ```
+   An [`ArithmeticException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.html)
+   (specifically, a divide by zero) caused our program to crash. Since `ArithmeticException` is an **unchecked exception**, the
+   Java compiler did not force us (the programmer) to catch or propagate this exception.  It is completely up to the programmer to decide
+   whether or not to handle exceptions of this type. Since we didn't handle it, our program crashed. You've probably experienced other, 
+   unchecked exceptions such as:
+   [`StringIndexOutOfBoundsException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.html),
+   [`NullPointerException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/NullPointerException.html),
+   [`NumberFormatException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/NumberFormatException.html), etc.
+
+1. On Odin, create the class `exceptions.Checked` containing the following code:
+
+   ```java
+   package exceptions;
+
+   import java.util.Scanner;
+   import java.io.File;
+
+   public class Checked {
+       public static void main (String[] args) {
+           File notesFile = new File("notes.txt");
+           Scanner input = new Scanner(notesFile);
+           System.out.println(input.nextLine());
+       } // main
+   } // Checked
+   ```
+
+   In this program, we are reading the first line of the file `notes.txt`. The first line of the `main` method creates a `File` object
+   which is referred to by `notesFile`.  Then, it passes this object reference to the `Scanner` constructor.  As you may have guessed, the
+   `input` object will read its input from the file (not the keyboard).  We will create the `notes.txt` file in a later step.
+
+1. Compile `Checked.java`.  You should get an error similar to the following:
+
+   ```
+   src/exceptions/Checked.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
+      Scanner input = new Scanner(notesFile);
+                      ^
+   ```
+   This error indicates that the `Scanner` constructor throws a `FileNotFoundException`.  `FileNotFoundException` is a
+   **checked exception**.  When a method or constructor call throws a checked exception, the programmer must either:
+      * surround the relevant call with a try-catch; or
+      * add a throws clause to the enclosing method (i.e., the method containing the call) to propogate this exception if it occurs.
+
+   In `Checked.java`, the enclosing method is `main`.  We never want to add a `throws` clause to the `main` method as there is no code in
+   our program above the `main` method to handle the exception. To fix `Checked.java`, we will use the first approach.
+
+1. Now, let's modify `Checked.java` to include an appropriate try-catch:
+
+   ```java
+   package exceptions;
+
+   import java.util.Scanner;
+   import java.io.File;
+   import java.io.FileNotFoundException;
+
+   public class Checked {
+       public static void main (String[] args) {
+           File notesFile = new File("notes.txt");
+           Scanner input = null;
+           try {
+               input = new Scanner(notesFile);
+           } catch(FileNotFoundException e) {
+               System.out.println(e.getMessage());
+           }
+           System.out.println(input.nextLine());
+       } // main
+   } // Checked
+   ```
+
+1. Create a `notes.txt` file in the directory where you will execute the program and add a single line of text to the file.
+   **Important Note:** The `notes.txt` file should be in the directory where you run the `java` command to run the program. If you
+   run the program from the parent directory of `bin` and `src`, that's where the file should be.
+
+1. Execute `exceptions.Checked`.  It should print the first line of `notes.txt`.
+
+## Identifying Checked vs. Unchecked Exceptions
+
+For now, we will use a simple method for checking if an exception is checked or unchecked.
+
+1. Visit the Java API page for [`ArithmeticException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.html).
+
+1. At the top of the page, there is a hierarchy of Java classes which looks like this:
+
+   ArithmeticException Unchecked Example
+
+   You can tell that `ArithmeticException` is an unchecked exception because `java.lang.RuntimeException` is listed in the hierarchy. If
+   you cannot find `java.lang.RuntimeException` in the hierarchy for a given exception, then that tells you it is a checked exception.
+
+1. For an example of a checked exception, see
+[`FileNotFoundException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/FileNotFoundException.html)
+
+## Multiple Catch Blocks
+
+Here is a video that demonstrates how to handle multiple exceptions at the same
+time using multiple catch blocks:
+
+https://www.youtube.com/watch?v=j-GNWvLNLjs
+
+
+IMAGE ALT TEXT
+
+
+## Explicitly Throwing Exceptions & Exception Propagation
+
+Now that you have seen how to handle exceptions in code written by others
+that can throw exceptions, it's important understand how and why you can
+throw exceptions yourself. In Java, the `throw` keyword is used to explicitly
+throw an exception. Here is an example where we create an
+[`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/IllegalArgumentException.html)
+and explicitly throw it:
+
+```java
+throw new IllegalArgumentException("nums array cannot be empty");
+```
+
+Since this line of code is known to throw an exception, we would
+usually want to handle the exception by placing the line in a try block.
+That may not always be ideal. Instead of handling the exception immediately,
+let's make it someone else's responsibility using the `throws` keyword
+in the signature of the method containing the line:
+
+```java
+public int computeAverage(double[] nums) throws IllegalArgumentException {
+    if (nums.length == 0) {
+        throw new IllegalArgumentException("nums array cannot be empty");
+    } // if
+    double sum = 0;
+    for (double num : nums) {
+        sum += num;
+    } // for
+    return sum / nums.length;
+} // computeAverage
+```
+
+Using the `throws` keyword, we told Java that the `IllegalArgumentException`
+will not be handled directly in this method. Instead it will be _propagated_
+up to the calling method, i.e., the method or methods, somewhere else, that are
+actually calling `computeAverage`. In that other method, the programmer
+can either handle the exception (using a try-catch) or choose to propagate it again
+by repeating the `throws` in the calling method's signature.
+
+In Java, checked exceptions must either be handled directly using a try-catch
+or progated up using `throws`. Note that while it is possible to place a `throws`
+in the signature of a program's `main` method, doing so is _strongly_ discouraged
+as exceptions propagated past `main` will always cause the program to crash.
+
+
+ +[![License: CC BY-NC-ND 4.0](https://img.shields.io/badge/License-CC%20BY--NC--ND%204.0-lightgrey.svg)](http://creativecommons.org/licenses/by-nc-nd/4.0/) + + +Copyright © Michael E. Cotterell, Brad Barnes, and the University of Georgia. +This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License to students and the public. +The content and opinions expressed on this Web page do not necessarily reflect the views of nor are they endorsed by the University of Georgia or the University System of Georgia. + diff --git a/generics/generic-classes/generic-classes.md b/generics/generic-classes/generic-classes.md index e4ff6e1c..92712117 100644 --- a/generics/generic-classes/generic-classes.md +++ b/generics/generic-classes/generic-classes.md @@ -1,6 +1,6 @@ # Generic Classes Tutorial -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Spring 2023](https://img.shields.io/badge/Approved%20for-Spring%202023-magenta) This tutorial introduces the reader to generic classes in Java by creating a new generic class and emphasizing some of the benefits of using generics. @@ -50,7 +50,7 @@ https://youtu.be/m539u1hGP7E Generic Method Example -## Required Additional Reading +## Additional Reading with More Examples Now that you're familiar with some of the basic concepts relate to generic methods in Java, you need to read the official Oracle reading: diff --git a/generics/generic-methods/generic-methods.md b/generics/generic-methods/generic-methods.md index f2407319..f0fbd130 100644 --- a/generics/generic-methods/generic-methods.md +++ b/generics/generic-methods/generic-methods.md @@ -1,6 +1,6 @@ # Generic Methods Reading -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Spring 2023](https://img.shields.io/badge/Approved%20for-Spring%202023-magenta) This reading introduces the reader to generic methods in Java. @@ -99,7 +99,7 @@ Here are some examples: Integer int2 = sc.foo(12, "help"); // R = String ``` -## Required Additional Reading +## Additional Reading with More Examples Now that you're familiar with some of the basic concepts relate to generic methods in Java, you need to read the official Oracle reading: diff --git a/inheritance/inheritance.md b/inheritance/inheritance.md index 8c35c93f..2ee4eb59 100644 --- a/inheritance/inheritance.md +++ b/inheritance/inheritance.md @@ -1,6 +1,6 @@ # Inheritance -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) This tutorial introduces the reader to Java inheritance and polymorphism via inheritance. @@ -57,6 +57,12 @@ To follow along with the video you'll need to first: IMAGE ALT TEXT +Below is a UML diagram for the starter code. If you haven't been introduced to UML, it is just +a way to visualize classes and their relationships. We will use a few simple UML diagrams in +this reading and we will formally introduce the topic later in the semester. If you would like +to read more about it now, see the [UML Class Diagrams](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/uml/uml.md) +reading. + Here is a UML diagram for the starter code: ![Starter Code](res/Inheritance1.png) @@ -92,7 +98,7 @@ in which they are declared. According the Java Language Specification, the [`java.lang.Object`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html) -class is the superclass for all other classes [1]. Take a few moments to look through +class is the superclass for all other classes [[1]](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/inheritance/inheritance.md#references). Take a few moments to look through the `Object` class documentation. Write down any methods you recognize and may have used in the past in your notes. Remember, all classes that you create automatically inherit those methods. That is, if a class does not explicitly extend another class, then it implicitly extends `Object`. Therefore, @@ -111,7 +117,7 @@ When we say that a parent constructor is called, we don't mean something like `n no object of the parent class is made in what we're describing. Instead, "using `super` to call a parent constructor" just means that we're telling Java to execute the code that's in a parent constructor. Java does this in order to facilitate a separation of concerns; that is, it lets -each class setup/initialize their own stuff so that the child class doesn't have to duplicate the +each class setup/initialize their own variables so that the child class doesn't have to duplicate the work that's written in the parent. We'll illustrate this with a small example in just a moment, but first take care to read the following note: @@ -145,19 +151,23 @@ To work through this example, perform the following steps: Go ahead and call the `Animal` constructor from within the `Dog` constructor using `"Canis"` and `"Lupus Familiaris"` as the genus and species, respectively. This will setup the `genus` and `species` - variable within any `Dog` objects that are created - similar to what was done in the first example video. + variable within any `Dog` objects that are created — similar to what was done in the first example video. **Note: Since `genus` and `species` are declared with `private` visibility, you cannot do the following in the `Dog` constructor since you do not have direct access to those variables:** ```java super.genus = "Canis"; - super.species = "Lupus Familiaris" + super.species = "Lupus Familiaris"; ``` Even if the visibility allowed you to write the lines above, you should avoid doing so! There is already code that sets up these variables. It's in the parent constructor. - Instead of duplicating code, just call the parent constructor. + Instead of duplicating code, just call the parent constructor using: + + ```java + super("Canis", "Familiaris"); + ``` 1. Compile the `cs1302.animal.Animal` and `cs1302.animal.Dog` classes, specifying `bin` as the default package for compiled code. Since there is a dependency between those @@ -243,14 +253,14 @@ an **optional** annotation that lets the compiler know your intent is to overrid Try the following scenarios: 1. Omit the `@Override`, then recompile. -1. Omit the `@Override` and mispell the `toString` method name, then recompile. -1. Include the `@Override` and mispell the `toString` method name, then recompile. +1. Omit the `@Override` and misspell the `toString` method name, then recompile. +1. Include the `@Override` and misspell the `toString` method name, then recompile. -Notice the error that occurs in the thirs situation that did not occur in the +Notice the error that occurs in the third situation that did not occur in the second. This is the primary purpose of the annotation. Although optional, it allowed you to tell the compiler that your intent is to override. If the compiler -sees the `@Override` annotation, then it checks to make sure it's an override - and -it can let you know if you made a mistake! +sees the `@Override` annotation, then it checks to make sure it's an override and +will let you know if you made a mistake! ### References diff --git a/interfaces/interfaces.md b/interfaces/interfaces.md index fdaa8c0c..396c8366 100644 --- a/interfaces/interfaces.md +++ b/interfaces/interfaces.md @@ -1,6 +1,6 @@ # Interfaces Tutorial -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) This tutorial introduces the reader to Java interfaces and polymorphism. @@ -46,42 +46,79 @@ The steps in this tutorial assume that you are logged into the Odin server. reference type in Java, including classes, interfaces, and class-based enumerations. A **reference type** in Java is any type that can serve as the type for a variable that refers to an object. Such a variable is known as a **reference variable**. We will elaborate on this - terminology a little more later in this tutorial. + terminology in the context of interfaces a little more later in this tutorial. If you are + unfamiliar with these terms in general, please review the + [Reference Variable Refresher](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/refresher/variables.md) + from last week. You are encouraged to ask questions about any parts that you find confusing. ### What is an Interface? -In its simplest form, a Java **interface** is a reference type composed of abstract methods and -constants. An **abstract method** is a non-static method without an implementation (body). Constants +In its simplest form, a Java **interface** is a reference type composed of **abstract methods** and +**constants**. An **abstract method** is a non-static method without an implementation (body). Think of +creating a class, adding the method signatures, but not putting any code in the methods. This will seem +strange at first but the benefit should become clear as you work through the example. **Constants** are variables (static or not) that are declared using the `final` keyword. As of Java 8, the technical definition for an *interface* allows it to contain only the following: -abstract methods, constants, static methods, nested types, and default implementation -methods [[2]](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html). -Nested types and default methods will not be covered in this tutorial. Java 9 added support -for private methods within an interface. +abstract methods, constants, private methods, static methods, nested types, and default implementation +methods [[2]](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html). In 1302, our interfaces +will mostly contain only abstract methods and constants. Nested types and default methods will not +be covered in this tutorial. Interfaces are used to specify that a type *can do* a set of things specified by its -abstract methods and constants. An interface serves as a contract for the classes that +abstract methods and constants. An interface serves as a *contract* for the classes that claim to implement the interface. Multiple classes can implement the same interface, each providing their own implementation of the contracted functionality. For this reason, it is important that the documentation for an interface describe *what* a method does and not necessarily *how* it should do it. Such documentation is usually written using Javadoc comments in the interface. +### Real World Example + +Remember, we said an interface is a *contract* for the classes that claim to implement it. Take a +moment to think about how contracts are used in the real world (forget Java for a minute). + +Hopefully, you came up with a definition of the word contract and maybe a few situations where +contracts are used. + +In the real world, we think of a contract as a formal and binding agreement +between two or more parties. Let's use the professional athlete as an example. Athletes sign a contract which is a +binding agreement between the athlete and the team/organization that ensures the athlete will compete +in his/her sport. The contract states that the athlete must "compete" but it doesn't say specifically +*how* they will compete. The details of exactly how an athlete should compete are usually not mentioned in the contract. +The contract simply binds the athlete to compete. The specific details and decisions that occur while the competition +is ongoing is up to the athlete. Once the contract is written, it could be signed by athletes +in a wide variety of sports. The signer could be a track athlete, a baseball player, a football +player, a racecar driver, etc. Again, the signer determines the details of how they will compete. The contract only +binds them to the action of competing. + +Now, let's tie this back to programming. In the example above, `compete` is the abstract method +that would be placed in the `Athlete` interface (contract) since all athletes must be able to compete. +The abstract method represents the action that is required of the signer of the contract. In other words, +the method is what the signer is obligated to do when they agree to implement the interface (a.k.a. +sign the contract). The implementation details of the `compete` method area not given in the interface +itself but instead they are written in the implementing class (signer). Again, the implementing class +(contract signer) can be any type of athlete as they are all required to compete. + +This may all still seem a bit strange and why we do this in programming may not yet be clear. +Hang in there! Let's work through an example in Java. Try to keep this terminology in mind as you work +through this tutorial. + ### Declaring an Interface 1. Interfaces, just like classes, have a fully qualified name. Their source code should be positioned and named within your project the same as with classes. That is, an interface called `cs1302.interfaces.contract.Styleable` has an implied position within the package - directories of your source code and should be placed in a `Styleable.java` file. - The first big syntax difference between a class and an interface is illustrated in + directories of your source code (`cs1302/interfaces/contract`) and should be placed + in a `Styleable.java` file within the implied directory. The first big syntax difference + between a class and an interface is illustrated in [`Styleable.java`](src/cs1302/interfaces/contract/Styleable.java): ```java public interface Styleable { ``` - Note the use of the `interface` keyword instead of `class` in the type header. - + Note the use of the `interface` keyword instead of `class` in the type header. In this example, + `Styleable` is the contract that can be signed by other classes. 1. The second big syntax difference involves the inclusion of abstract methods, illustrated by the `style()` method in [`Styleable.java`](src/cs1302/interfaces/contract/Styleable.java). @@ -91,7 +128,7 @@ Javadoc comments in the interface. ``` Notice that the `style()` method does not contain an implementation. The signature of the method - ends with a semicolon. An abstract method may not have an implementation. The following is **NOT** an + ends with a semicolon. An abstract method must not have an implementation. The following is **NOT** an abstract method: ```java @@ -102,6 +139,12 @@ Javadoc comments in the interface. to the actual abstract method signature presented above that ends with a semicolon, thus lacking an implementation. + If you open the `Styleable.java` file, you will see that it also contains an abstract `unstyle` method. + Remember, that the abstract method(s) represent what the signer of the contract must be able to do. If a class + implements the `Styleable` interface, it is obligated to have a concrete (non-abstract) `style` and a concreate + `unstyle` method. If an implementing class does not have implementations for one or both of these methods, + it will not compile. + **NOTE:** In Java, the declaration of an abstract method in the source code for an interface may omit the `public` visibility modifier. If `public` is omitted in this context, the abstract method is still assumed to have `public` visibility. This behavior is different for classes, a topic that will @@ -111,11 +154,16 @@ Javadoc comments in the interface. Find the `Styleable` interface on the website and compare the documentation provided there with what you see in the Javadoc comments included in `Styleable.java`. If you don't remember how to do this, then please refer back to your notes for the - [Javadoc and API Documentation](https://github.com/cs1302uga/cs1302-tutorials/blob/master/javadoc/javadoc.md) + [Javadoc and API Documentation](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/javadoc/javadoc.md) tutorial. ### Implementing an Interface +Remember, the `Styleable` interface is just the contract. We also need to have at least one class +that implements (signs) the contract. We will use two different implementing classes to demonstrate +that the implementation specifics are up to the implementing class (not the interface) just as the +specific details regarding how an athlete will compete are up to the athlete (not the contract). + 1. In Java, a class can implement an interface using the `implements` keyword, e.g., as seen in [`Fancy.java`](src/cs1302/interfaces/impl/Fancy.java): @@ -123,12 +171,17 @@ Javadoc comments in the interface. public class Fancy implements Styleable { ``` - If the interface is not in the same package as the implementing class, then you will need to add + In this example, `Fancy` is the implementing class that has signed the `Styleable` contract. It signs + the contract as soon as you add `implements Styleable` to the class declaration as seen above. Again, `Fancy` + will not compile unless it has a concrete (non-abstract) implementation of both the `style` and `unstyle` methods. + + **Note:** If the interface is not in the same package as the implementing class, then you will need to add an `import` statement or use the fully qualified name of the interface. If more than one interface is being implemented, then they can be written in a comma separated list following the `implements` keyword. -1. When a class properly implements an interface in Java, it is required to provide implementations +1. As we mentioned before, when a class properly implements an interface in Java, it is required to + provide implementations for each of the abstract methods defined in the interface. If you inspect the source code for the `cs1302.interfaces.impl.Fancy` class, you will see the abstract methods from `Styleable` implemented. Notice that the implementatons contain method bodies (instead of their signatures @@ -140,12 +193,12 @@ Javadoc comments in the interface. ``` Again, this differs from the abstract method defined in the interface only in so far as it has an - implementation. The other aspects of the method signature are the same. + implementation. The other aspects of the method signature (return type, visibility, name) are the same. **NOTE:** As mentioned earlier, it is syntactically correct for an abstract method in an interface to omit the `public` keyword. Remember, in this context, the method is still assumed to have - public visibility. Therefore, the implementation of such a method in an implementing class will - need to include the `public` visibility modifier. + public visibility. Therefore, the implementation of such a method in **an implementing class will + need to include the `public` visibility modifier**. 1. Compare the Javadoc comments in the source code for the `Styleable` interface with the comments written in the source code for the implementing `Fancy` class. In some cases, new comments are @@ -165,7 +218,15 @@ Javadoc comments in the interface. ### Using an Interface -1. As mentioned earlier, interfaces are reference types in Java. This means that they can be serve as +In this section, we will motivate **why** we set up the interface/implementing class relationship. The main +benefit is type compatibility between the interface type and the implementing class type(s). Leveraging this +compatibility will lead to more elegant code that works with objects of any class that implement the interface. +Connecting this to our real world example, we could write code that works with all athletes instead of having +to write separate (but similar) code for each type of athlete. Would you rather write one method that works +for all athletes or write individual methods for basketball players, football players, track athletes, golfers, +etc.? With that in mind, let's go back to our code example: + +1. Interfaces are reference types in Java. This means that they can be serve as the type for a reference variable. You should be familiar with the use of class names for reference variable types. The code snippet below illustrates both scenarios: @@ -175,7 +236,7 @@ Javadoc comments in the interface. ``` 1. Reference variables are called as such because they refer to objects. However, you can only create - objects from classes! Therefore, what can an `Styleable` variable refer to? The answer is that + objects from classes (not interfaces)! Therefore, what can a `Styleable` variable refer to? The answer is that a variable with an interface as its type can refer to an object of any class that implements that interface. The code snippet below illustrates this: @@ -259,7 +320,8 @@ Javadoc comments in the interface. Remember, you may need to specify the class path in addition to the destination when using `javac` to compile Java code that depends on other Java code. If you need a refresher on this subject, then refer to the - [Java Packages Tutorial](https://github.com/cs1302uga/cs1302-tutorials/blob/master/packages.md). + [Java Packages Tutorial Part 1](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/packages1.md) and + [Java Packages Tutorial Part 2](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/packages2.md). ### Common Functionality among Disparate Classes @@ -271,7 +333,7 @@ functionality. https://www.youtube.com/watch?v=kcBV6tlg44I -The source code for the video can be accessed [here](https://github.com/cs1302uga/cs1302-tutorials/tree/master/interfaces/donator/src/cs1302/interfaces). +The source code for the video can be accessed [here](https://github.com/cs1302uga/cs1302-tutorials/tree/alsi/interfaces/donator/src/cs1302/interfaces). IMAGE ALT TEXT diff --git a/javadoc/javadoc.md b/javadoc/javadoc.md index 9aa04e14..aecf1220 100644 --- a/javadoc/javadoc.md +++ b/javadoc/javadoc.md @@ -1,6 +1,6 @@ # Javadoc and API Documentation -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) ## Prerequisites @@ -58,7 +58,7 @@ The steps in this tutorial assume that you are logged into the Odin server. called `cs1302-javadoc`: ``` - $ curl -s -L https://git.io/fh0nG | bash + $ curl -s -L https://raw.githubusercontent.com/cs1302uga/cs1302-tutorials/alsi/javadoc/setup.sh | bash ``` 1. Change into the `cs1302-javadoc` directory that was just created and look around. There should be @@ -110,31 +110,57 @@ to the explicit instructions provided below are explored in the FAQ section towa this tutorial. 1. Ensure that you have a `public_html` directory in your home directory. If the `~/public_html` - directory does not exist, then you should create it. The purpose of this directory on Odin (and + directory does not exist, you should create it. The purpose of this directory on Odin (and on many systems) is to support user websites, which will be illustrated in the following steps. - You are fully responsible for anything that you host through your Odin website. + Please note that you are fully responsible for anything that you host through your Odin website. -1. Use `ln`, as described below, to **create a symbolic link** (shortcut) in your `public_html` - directory to the `doc` subdirectory containing the API documentation website that you - created in a previous step. The exact command is presented below--it assumes you are currently - in the `cs1302-javadoc` directory. +1. To make our documentation publicly available on the web, we will set up a **symbolic link** to + the `doc` directory you created in the previous steps. You can think of a symbolic link as a + shortcut to those files. The symbolic link will need to be placed in the `~/public_html` folder + but the `doc` directory you created will not move. + + The syntax for the command to create a symbolic link is: + + ``` + ln -s + ``` + + Notice that the first path must be an absolute path and that the second path can be a relative + path. For example, if I were running the `ln` command from within the `cs1302-javadoc` directory + that contains my `doc` folder, my command might look something like this: ``` - $ ln -s $(pwd)/doc ~/public_html/cs1302-javadoc-doc + ln -s /absolute/path/to/cs1302-javadoc/doc ~/public_html/cs1302-javadoc-doc ``` + + where `/absolute/path/to/cs1302-javadoc/doc` is replaced with the real absolute path to `doc` and + `cs1302-javadoc-doc` is the name of the symbolic link being created. The absolute path required will + depend on your username and the name of the link can be anything you like (although we generally + recommend using the same names we use in the tutorial). + + * Optional Shortcut (avoids typing the full absolute path) + + If you want to avoid typing the absolute path every time, you can try the command below. However, + for this command to work properly, it must be executed from the directory that contains the `doc` + directory. In this example, **the command must be run from the `cs1302-javadoc` directory**. + + ``` + $ ln -s $(pwd)/doc ~/public_html/cs1302-javadoc-doc + ``` - **Note:** The `ln` command requires the **absolute path** to our link's target (in this case, `doc`). - Since our intended target is in the current directory, we know that its absolute path - is the same as the absolute path of the current directory followed by `/` followed by - the name of our target. We could manually figure out the desired path with the help of `pwd` - or we can use `$(pwd)`, as seen above, to fill in the output of `pwd` instead. You could also - type out the entire absolute path but that would be tedious and error-prone. + **Explanation:** As previously stated, the `ln` command requires the absolute path to our link's + target (in this case, `doc`). + Since our intended target is in the current directory, we know that its absolute path + is the same as the absolute path of the current directory followed by `/` followed by + the name of our target. We could manually figure out the desired path with the help of `pwd` + or we can use `$(pwd)`, as seen above, to fill in the output of `pwd` instead. You could also + type out the entire absolute path but that would be tedious and error-prone. - In this scenario, the symbolic link is called `cs1302-javadoc-doc`. You can see it if you - change into your `public_html` directory and perform an `ls -l`. The entry for - `cs1302-javadoc-doc` in the long listing indicates that the file is a symbolic link in - two different ways: i) an `l` is prefixed in the mode instead of `-` or `d`; and ii) the - filename lists an arrow pointing to the link target. + In this scenario, the symbolic link is called `cs1302-javadoc-doc`. You can see it if you + change into your `public_html` directory and perform an `ls -l`. The entry for + `cs1302-javadoc-doc` in the long listing indicates that the file is a symbolic link in + two different ways: i) an `l` is prefixed in the mode instead of `-` or `d`; and ii) the + filename lists an arrow pointing to the link target. 1. Navigate to the following URL in your web browser, replacing `user` with your Odin username: @@ -196,14 +222,14 @@ this tutorial. 1. __What is the difference between `throw`, `throws`, and `@throws`?__ * The `throw` keyword is used in a block of code to - [explicitly throw an exception](https://github.com/cs1302uga/cs1302-tutorials/blob/master/exceptions/exceptions.md#explicitly-throwing-exceptions--exception-propagation). + [explicitly throw an exception](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/exceptions/exceptions2.md#explicitly-throwing-exceptions--exception-propagation). This is desirable when you want your method to throw an exception under some predefined conditions. If the exception object being thrown using `throw` - is a [checked exception](https://github.com/cs1302uga/cs1302-tutorials/blob/master/exceptions/exceptions.md#checked-vs-unchecked-exceptions), + is a [checked exception](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/exceptions/exceptions2.md#checked-vs-unchecked-exceptions), then you might also need to include `throws` in the method signature. * The `throws` keyword is used in a method or constructor signature to list the checked exceptions - that the method is allowed to [propagate](https://github.com/cs1302uga/cs1302-tutorials/blob/master/exceptions/exceptions.md#explicitly-throwing-exceptions--exception-propagation). + that the method is allowed to [propagate](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/exceptions/exceptions2.md#explicitly-throwing-exceptions--exception-propagation). * The `@throws` tag is a Javadoc tag that is used in the Javadoc comment associated with a method (or constructor) to document that it can throw an exception under certain circumstances. diff --git a/javadoc/setup.sh b/javadoc/setup.sh index e8fb529d..ea8dee5d 100644 --- a/javadoc/setup.sh +++ b/javadoc/setup.sh @@ -1,15 +1,33 @@ #!/bin/bash -if [ ! -d "cs1302-javadoc" ]; then - git clone --depth 1 --no-checkout https://github.com/cs1302uga/cs1302-tutorials.git cs1302-javadoc - cd cs1302-javadoc - git checkout master -- javadoc - rm -f javadoc/setup.sh - mv javadoc/* ./ - rm -rf javadoc - rm -rf .git - mkdir bin doc - echo "subdirectory cs1302-javadoc successfully created" +# setup info +REPO=https://github.com/cs1302uga/cs1302-tutorials.git +BRANCH=alsi +FROMDIR=javadoc +TODIR=cs1302-javadoc + +FILESTOREMOVE=".git javadoc-figure.png javadoc-figure.pptx javadoc.md" # do not leave empty +DIRSTOMAKE="bin doc" # do not leave empty + +if [ ! -d "${TODIR}" ]; then + # get tutorial starter code + git clone --depth 1 --no-checkout --branch ${BRANCH} ${REPO} ${TODIR} + pushd ${TODIR} &>/dev/null + git checkout ${BRANCH} -- ${FROMDIR} + # clean up what we got + rm -f ${FROMDIR}/setup.sh + mv ${FROMDIR}/* ./ + rm -rf ${FROMDIR} + rm -rf ${FILESTOREMOVE} + # create bin and doc + mkdir -p ${DIRSTOMAKE} + popd &>/dev/null + # if tree is available, show the directory + if command -v tree &>/dev/null; then + tree ${TODIR} + fi + echo "subdirectory ${TODIR} successfully created" else - >&2 echo "subdirectory cs1302-javadoc already exists" + >&2 echo "subdirectory ${TODIR} already exists" + >&2 echo "if you want to start over, delete or rename the existing directory" fi diff --git a/javafx/javafx.md b/javafx/javafx.md index 1c059381..09012d3d 100644 --- a/javafx/javafx.md +++ b/javafx/javafx.md @@ -1,6 +1,6 @@ # JavaFX Starter Tutorial -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Spring 2023](https://img.shields.io/badge/Approved%20for-Spring%202023-magenta) JavaFX is a library for creating and delivering applications with graphical user interfaces (GUIs) in Java. In this tutorial, we will use JavaFX 17 along with Java 17. The API documentation for @@ -23,8 +23,8 @@ page for direct links to commonly used classes. If you encounter problems in this step, then please ensure that you have followed the instructions provided at the beginning of the semester for - [MacOS users](https://github.com/cs1302uga/cs1302-exercises/blob/master/misc/MacOS.md) or - [Windows 10 users](https://github.com/cs1302uga/cs1302-exercises/blob/master/misc/Windows10.md). + [MacOS users](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/setup/MacOS.md) or + [Windows 10 users](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/setup/Windows.md). Also, the `-X` and `-Y` options can be used individually with or without each other. See the manual page for `ssh` for more information about the differences between @@ -64,7 +64,7 @@ page for direct links to commonly used classes. 1. Run the compiled code using the command below: ``` - java -cp bin -p $JAVAFX_HOME/lib --add-modules javafx.controls cs1302.gui.ExampleDriver + java -cp bin -Dprism.order=sw -p $JAVAFX_HOME/lib --add-modules javafx.controls cs1302.gui.ExampleDriver ``` Notice the use of the `-p` and `add-modules` command line arguments as in the previous step. @@ -98,14 +98,9 @@ page for direct links to commonly used classes. Current serial number in output stream: 24 ``` - **If you receive an error message in the terminal,** then this error message is related to the - JavaFX graphics renderer. By default, it attempts to perform hardware-accelerated rendering. - However, we need to enable to software-based rendering in order for it to work nicely with X-forwarding. - Close out of the small GUI app. - -1. Regardless of whether you got an error, **rerun the driver but add `-Dprism.order=sw` in addition to - the usual options when executing the related `java` command** to enable the software-based renderer. You may - still receive a slightly shorter error message but your application will run smoother (less lag) with this +1. **If you receive an error message in the terminal,** then this error message is related to the + JavaFX graphics renderer. **rerun the driver and make sure you correctly typed the `-Dprism.order=sw` option properly.**. + You may still receive a slightly shorter error message but your application will run smoother (less lag) with this option set. 1. If the small GUI app containing a nice message appears with or without a small error message, then you are okay to proceed! @@ -115,7 +110,7 @@ page for direct links to commonly used classes. or second time that you attempt to run the program, then please ensure that you have followed the instructions provided at the beginning of the semester for - [MacOS users](https://github.com/cs1302uga/cs1302-exercises/blob/master/misc/MacOS.md). + [MacOS users](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/setup/MacOS.md). In particular, you really do need to restart your Mac after installing XQuartz via Homebrew. diff --git a/lambda/lambda.rst b/lambda/lambda.rst index 746a500a..7f85c99a 100644 --- a/lambda/lambda.rst +++ b/lambda/lambda.rst @@ -1,6 +1,6 @@ .. rst setup .. sectnum:: -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple +.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202023-magenta .. copyright and license information .. |copy| unicode:: U+000A9 .. COPYRIGHT SIGN .. |copyright| replace:: Copyright |copy| Michael E. Cotterell, Bradley J. Barnes, and the University of Georgia. @@ -222,7 +222,7 @@ Let's break it down: 2. A lambda expression is used to **create an object** that has one method by defining what that method should do. In this case, we want the - method's type layout o match the abstract method ``accept`` in + method's type layout to match the abstract method ``accept`` in ``Consumer``, and it does. 3. Assign the object's reference to the variable. @@ -291,7 +291,7 @@ however, there's still room for improvement. If we don't include the parameter types in our lambda expression, then Java will try to determine what they are based on context. For example, if we're assigning the created object to a ``Consumer`` variable, - then Java knows that the parameter list for ``aceppt`` is ``(String t)`` + then Java knows that the parameter list for ``accept`` is ``(String t)`` and will automatically convert ``(t)`` to ``(String t)``. 3. If there is exactly one method parameter, then the parentheses for the @@ -366,4 +366,4 @@ four (unnamed) classes are created and instantiated using a single Video Examples ============== -**Coming Soon** +**Coming Soon** Attend class for live examples. diff --git a/maven.md b/maven.md index 7c8f74c1..723e3cb0 100644 --- a/maven.md +++ b/maven.md @@ -1,6 +1,6 @@ # Maven Tutorial -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Spring 2023](https://img.shields.io/badge/Approved%20for-Spring%202023-magenta) ## Maven @@ -27,16 +27,16 @@ $ mvn --version It should print out your installed version of Maven, for example: ``` -Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d) +Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) Maven home: /usr/local/mepcott/cs1302/apache-maven -Java version: 11.0.10, vendor: Oracle Corporation, runtime: /usr/local/mepcott/jdk/jdk-11.0.10 +Java version: 17.0.4.1, vendor: Oracle Corporation, runtime: /usr/local/mepcott/jdk/jdk-17.0.4.1 Default locale: en_US, platform encoding: UTF-8 -OS name: "linux", version: "3.10.0-1160.el7.x86_64", arch: "amd64", family: "unix" +OS name: "linux", version: "3.10.0-1160.42.2.el7.x86_64", arch: "amd64", family: "unix" ``` If you are on Odin and the `mvn` command is not recognized, then please ensure that you have setup the CSCI 1302 shell profile according to the -instructions provided [here](https://github.com/cs1302uga/cs1302-tutorials/blob/master/unix/unix-tutorial.rst#bash-profile). +instructions provided [here](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/unix/unix-getting-started.rst#75bash_profile-required-command). ## Creating a Project @@ -124,21 +124,21 @@ mode later in this tutorial once you are more familiar with the tool. ## Updating the POM By default, the `maven-archetype-quickstart` archetype (version `1.4`) is configured -to use Java 7 (`1.7`)! We can remedy this by updating the project's `pom.xml` file. +to use Java 7 (`1.7`)! We can remedy this by updating the project's `pom.xml` file using Emacs. 1. Change into the `cs1302-mvn` directory, then change the values of the - `maven.compiler.source` and `maven.compiler.target` to `11` for Java 11. It should look + `maven.compiler.source` and `maven.compiler.target` to `17` for Java 17. It should look similar to the following: ```xml UTF-8 - 11 - 11 + 17 + 17 ``` - That's it! After making that change, your project is now setup to use Java 11. + That's it! After making that change, your project is now setup to use Java 17. 1. You can also add / update project dependencies. In the past, you may have done this by manually including a JAR file on your class path. With Maven, we can add the @@ -162,7 +162,7 @@ to use Java 7 (`1.7`)! We can remedy this by updating the project's `pom.xml` fi with appropriate values before the closing `` tag. Many libraries are packages for Maven. You can try searching for some on [Maven Central](https://search.maven.org/). -1. When using Maven with your JavaFX projects, you would need to add the JavaFX 11 dependency to your +1. When using Maven with your JavaFX projects, you would need to add the JavaFX 17 dependency to your `pom.xml` file. Adding this dependency to the existing `junit` dependency would look like this: ```xml @@ -174,9 +174,9 @@ to use Java 7 (`1.7`)! We can remedy this by updating the project's `pom.xml` fi test - org.openjfx - javafx-controls - 11 + org.openjfx + javafx-controls + 17.0.2 ``` diff --git a/octal-mode.md b/octal-mode.md index 270d72b4..875ceeb6 100644 --- a/octal-mode.md +++ b/octal-mode.md @@ -1,6 +1,6 @@ # Octal Mode -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) ## Prerequisites @@ -37,12 +37,44 @@ On Odin, try the following: $ stat newfile ``` -## Octal Mode +## Mode One very important part of a file's status information is its _mode_, which contains information -about the file's type (e.g., regular file or directory file) and its associated permissions. In -the output to `ls -l`, you see the symbolic mode. However, another way to express the permission -portion of the mode is using octal notation. +about the file's type (e.g., regular file or directory file) and its associated permissions. + +The first character of the mode denotes the file type. In Unix, file type refers to how the file +behaves from the file system's perspective. Common file types include: + + |Character |File Type |Description | + |----------- |---------------- |---------------------| + |`-` |regular file |text or binary data | + |`d` |directory file |collection of files. | + |`l` |symbolic link |shortcut to a file | + +The next nine (9) characters denote the read (``r``), write (``w``), and execute (``x``) permissions +for the file's user (``u``), group (``g``), and others (``o``). We will go into more detail regarding +file permissions later in this tutorial, but here is a quick breakdown for ``rw-r--r--``: + + |User |Group |Others | + |--------------------- |------------------- |-------------------| + |R W X |R W X |R W X | + |`r` `w` `-` |`r` `-` `-` |`r` `-` `-` | + |✓ ✓ ✗ |✓ ✗ ✗ |✓ ✗ ✗ | + +File type cannot usually be changed after a file has been created; however, a file's permissions +can always be changed by its owner, a superuser (administrator), or a program acting on behalf +of either the owner or a superuser. It is also worth noting that superusers are usually not +subject to permission restrictions. + +The eleventh (11) character specifies whether an alternate access method such as an access control list +applies to the file in addition to the displayed permissions. This topic is beyond the scope of this +reading, but for those who are curious, the ``.`` indicates that a file has an SELinux security context +and no other alternate access method. + +## Octal Mode + +In the output to `ls -l` and in the examples above, you see the symbolic mode. However, another way to +express the permission portion of the mode is using octal notation. **NOTE:** Although the symoblic mode may be more readable in many cases, octal notation is vastly more prevalent in literature and examples that you may find online. diff --git a/packages.md b/packages1.md similarity index 63% rename from packages.md rename to packages1.md index cd716d44..3e90b00c 100644 --- a/packages.md +++ b/packages1.md @@ -1,6 +1,6 @@ -# Java Packages Tutorial +# Java Packages Tutorial - Part 1 -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) ## Prerequisites @@ -18,12 +18,18 @@ run any code examples, repeat as necessary**. Simply reading (or skimming) is no ## Java Packages In Java, a **package** is a grouping of related types providing access protection and name space management. -Note that types refers to classes, interfaces, enumerations, and annotation types [[1]](https://docs.oracle.com/javase/tutorial/java/package/packages.html). +Note that types refers to classes, interfaces, enumerations, and annotation types [[1]](https://docs.oracle.com/javase/tutorial/java/package/packages.html). In other words, a package allows you to +organize your source code. Proper code organization becomes increasingly important as the size of the project +increases. + The two primary benefits of packages are: * **Name Space Management:** Packages allow you to give a common name to a group of related types. For example, `java.util.Scanner` and `java.util.Random` are two utility classes provided in the `java.util` package. - You and other programmers can easily determine that these types are related. + You and other programmers can easily determine that these types are related. They are both utilities that you have + probably used in your code. It is important to note that you could have two types with the same simple name that + are located in different packages. For example, you could have a `java.util.Random` class and a `edu.cs.uga.Random` + class. Both classes have the same name (`Random`) but they can be differentiated by their package names. * **Access Protection:** Visibility in Java is not limited to `public` and `private`. Packages and additional visibility modifiers enable programmers to declare things as visible only within a package. @@ -60,16 +66,19 @@ You should ask questions on Piazza if you are unable to proceed or if some aspec ## Default Package Here, the `src` directory is the location of the **default package** (proper noun) -for source code. The default package contains classes (and other types) that are -not in a named package. When developing small or temporary applications, it is a -convenient place for package-less `.java` files +for source code. The default package for source code serves as the base directory +for named packages that you will create. You can think of it as the top-level directory +for your package directories (more soon). The default package can also contain classes +(and other types) that are not in a named package. When developing small or temporary +applications, it is a convenient place for package-less `.java` files [[2]](https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html). -The default package location for source code also serves as the base directory -for named packages that you will create. -Let's dive in! The steps below show you how to create, compile, and execute a class -in the default package (i.e., a class in a package-less `.java` file). Once you -are comfortable with that, move on to the next section to learn about +Let's dive in! Before we get into creating named packages, we will start by compiling +directly into the default package as a warmup. To be clear, you won't need to use the +`cs1302` or `hello` directories in this step. You will use them in the next part of the tutorial. +The steps below show you how to create, +compile, and execute a class in the default package (i.e., a class in a package-less +`.java` file). Once you are comfortable with that, move on to the next section to learn about named packages. 1. Using Emacs, create a basic "Hello, World!" program in a driver class @@ -84,7 +93,7 @@ named packages. } // HelloWorld ``` -2. Change directly into the default package directory (`src`) and compile the program using `javac`: +2. Change directories into the default package directory (`src`) and compile the program using `javac`: ``` $ javac HelloWorld.java @@ -160,6 +169,12 @@ named packages. `HelloWorld.java` file is not in that directory, we had to specify the relative path `src/HelloWorld.java` to tell the compiler how to find that file relative to the pwd. We're telling the compiler "first, go into the `src` directory and then you'll see the file `HelloWorld.java`". + + **Important Note:** `bin` is just the relative path to the directory where the compiled `.class` files will + be placed. In this example, `bin` is a directory located inside of the present working directory. You can + replace `bin` with any relative or absolute path to any directory that you have permission to write to. For + example, if we had a direcory called `class_files` in our present working directory, we could compile + the code with `-d class_files` and our `.class` files would be placed in that directory. Now, if you list the contents of the `bin` directory, you will see that it contains `HelloWorld.class`. Listing the `src` directory contents will show only `HelloWorld.java`. @@ -201,6 +216,7 @@ named packages. ## Named Package Now let's create a named package. To place a class (or interface) in named package, you must do two things: + 1. Place the `.java` file in the appropriate package directory; and 2. Include a `package` statement at the top of the `.java` file. @@ -209,6 +225,8 @@ Let's try it by placing the `HelloWorld` class into the `cs1302.hello` package! 1. Change directly into `cs1302-packages` directory. 2. Move the `HelloWorld.java` file into the `cs1302.hello` package directory. + You may need to create both the `cs1302` and `hello` directories before + executing the following command. ``` $ mv src/HelloWorld.java src/cs1302/hello/ @@ -235,53 +253,14 @@ Let's try it by placing the `HelloWorld` class into the `cs1302.hello` package! ``` 5. Execute the `find` command. Note that the `HelloWorld.class` file was created under `bin/cs1302/hello`. - The compiler automatically created the necessary package directories for our compiled code under `bin`! - -5. Try to run the program using `javac` specify the classpath using `-cp` and include the - fully qualified name (explained below) of the class containing the `main` method: - - ``` - $ java -cp bin cs1302.hello.HelloWorld - ``` - - In this example, `cs1302.hello.HelloWorld` is known as the **fully qualified name** of the - `HelloWorld` class in the `cs1302.hello` package. You have seen fully qualified names before--they - are often used with `import` statements (remember `java.util.Scanner`?). When you import a class, you - can use the simple class name in that file instead of having to type the fully qualified name each time. - In this case, `HelloWorld` is known as the **name** or **simple name** of the class. - - **PROTIP:** Although packages correspond to directories, a fully qualified name uses `.` (dot) - for the name separator and not a slash. - -## Code Dependencies - -When Java code uses other Java code, that creates a dependency. Most of the programs that you've -written have used code provided by Oracle under the various `java` subpackages. When you compile, -those dependencies are automatically included on the class path. However, when your code depends -on code that's not included with Java (e.g., code that you or someone else has written), you need -to let `javac` know where the _compiled_ version of that depedency is. - -1. Let's extend the code we just finished. Create a `cs1302.util.HelloUtility` class under `src`. - **Remember,** the fully qualified name implies a specific directory structure and package statement - requirement with respect to `HelloUtility.java`. You will need to add the `util` directory in the proper - place in your current directory hierarchy. - -1. Write the code to declare the `cs1302.util.HelloUtility` class making sure to include the proper - class declaration and package statement at the top. Then, within the class declaration, add the - following method: - - ```java - public static void excitingHello() { - System.out.println("HELLO!!!!"); - } // excitingHello - ``` - -1. Save, then compile the `.java` file for the `cs1302.util.HelloUtility` class as usual, - using `bin` as the destination for the compiled code. Once it compiles, make sure that the - output from `find` matches the output below: + The output of `find` should look the same as the output below. Notice that the compiler automatically + created the necessary package directories for our compiled code under `bin`! **Note:** If you see any tilde (~) files, those are just backup copies of older versions - of your files. You can ignore those. + of your files. You can ignore those. If you see any other differences between your + output and the output below, you likely had a small error in a command or in your package statement in + the `HelloWorld.java` file. Double check that you did everything correctly and, if you need assistance, + post a screenshot of your `find` output to Piazza. ``` . @@ -289,115 +268,43 @@ to let `javac` know where the _compiled_ version of that depedency is. ./bin/cs1302 ./bin/cs1302/hello ./bin/cs1302/hello/HelloWorld.class - ./bin/cs1302/util - ./bin/cs1302/util/HelloUtility.class ./src ./src/cs1302 ./src/cs1302/hello ./src/cs1302/hello/HelloWorld.java - ./src/cs1302/util - ./src/cs1302/util/HelloUtility.java ``` + -1. Now, modify the source code for your `cs1302.hello.HelloWorld` class to call the static method in - `cs1302.util.HelloUtility`. To do this, you may: - - 1. Add an import statement between the `package` statement and class declation: - - ```java - import cs1302.util.HelloUtility; - ``` - - 1. Call the method in `main` using the simple class name: - - ```java - HelloUtility.excitingHello(); - ``` - - Completing these two steps create a **dependency**. Now, the `cs1302.hello.HelloWorld` class - **depends** on the `cs1302.util.HelloUtility` class because it uses a method defined within that - class. - -1. If you try to compile the source code for your `cs1302.hello.HelloWorld` class exactly as you - did before, then it will not work because the compiler cannot find `cs1302.util.HelloUtility` - class on which `cs1302.hello.HelloWorld` depends. Try it! The error message should look like: +6. Run the program using `javac` with the classpath using `-cp` and include the + fully qualified name (explained below) of the class containing the `main` method: ``` - src/cs1302/hello/HelloWorld.java:3: error: package cs1302.util does not exist - import cs1302.util.HelloUtility; - ^ - src/cs1302/hello/HelloWorld.java:8: error: cannot find symbol - HelloUtility.excitingHello(); - ^ - symbol: variable HelloUtility - location: class HelloWorld + $ java -cp bin cs1302.hello.HelloWorld ``` + + In this example, `cs1302.hello.HelloWorld` is known as the **fully qualified name (or FQN)** of the + `HelloWorld` class in the `cs1302.hello` package. You have seen fully qualified names before--they + are often used with `import` statements (remember `java.util.Scanner`?). When you import a class, you + can use the simple class name in that file instead of having to type the fully qualified name each time. + In this case, `HelloWorld` is known as the **name** or **simple name** of the class. - The error output is just `javac` saying that it cannot find something. In this case, it cannot - find `cs1302.util.HelloUtility` as it is not in the same package as `cs1302.hello.HelloWorld`. - Since we know it actually exists, we can just tell `javac` where to find it using `-cp`. - - Remember that when your code depends on other code that you have written, you need to let - `javac` know where the _compiled_ version of that depedency is. Since you compiled under `bin`, - that's where you should tell `javac` to look. Try to compile it again, but this time, be sure - to include the `-cp bin` option in addition to `-d bin` option. The program should now run as expected. - -## Further Important Notes - -### Setting the Class Path - -Both `javac` and `java` allow you specify the class path using the `-cp` or `-classpath` command-line -option. The usual syntax is as follows: - -``` --cp some/path -``` - -If more than one default package is needed, then a colon `:` can be used to separate each path in a -list of multiple paths: - -``` --cp path1:path2 -``` - -Each path can be a path to a directory or a `.jar` file (usually used for third party libraries). - -**VERY IMPORTANT NOTE:** The class path should always point to a default package for _compiled_ code. -If you are compiling a `.java` file that depends on an already compiled class, then you will need to -specifiy the class path to the corresponding default package for that dependency when -invoking `javac`. - -### Import Statements - -In Java, you do not have to import classes that are in the same package. However, it's interesting to -note that `import` statements are actually never required in Java. We just use them for convenience. -Assuming the corresponding default package for class's package is on the class path when compiling -and/or running, you can always refer to a class by its fully qualified name. Consider two uses of -[`java.util.Random`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Random.html) below: - -```java -// assuming the class was imported -Random rng = new Random(); -``` - -```java -// assuming the class was NOT imported -java.util.Random rng = new java.util.Random(); -``` - -As you can imagine, the latter (without an import statement) might get annoying and repetetive. -Therefore, we usually prefer to use an `import` statement for the convenience it provides. -Why would anyone prefer to use the fully qualified name instead of the simple name for a class? -It enables you to use two classes from different packages with the same simple name at the -same time! + **PROTIP:** Although packages correspond to directories, a fully qualified name (FQN) uses `.` (dot) + for the name separator and not a slash. -### The `java.lang` Package +7. Congratulations on compiling your code to a named package! **Don't delete your work** unless you want to work + through the tutorial again for extra practice. The next tutorial will continue where this one left off. + + ## Video Demo + + 1. Follow along with Dr. Barnes as he works through another example of creating a named package in Java: -Java automatically performs a wildcard import of the `java.lang` package (i.e., `import java.lang.*;`) in -every Java file, without requiring the programmer to explicitly write it. That is why you can use classes -such as `java.lang.String` and `java.lang.System` by their simple names without importing! + https://www.youtube.com/watch?v=vuenX567T6c -## References + + IMAGE ALT TEXT + + + ## References * [[1] Creating and Using Packages](https://docs.oracle.com/javase/tutorial/java/package/packages.html) * [[2] Packages](https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html) diff --git a/packages2.md b/packages2.md new file mode 100644 index 00000000..3aa4398e --- /dev/null +++ b/packages2.md @@ -0,0 +1,208 @@ +# Java Packages Tutorial - Part 2 + +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) + +## Prerequisites + +This tutorial assumes that the reader has completed +[Java Packages Tutorial - Part 1](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/packages1.md). +If you haven't completed that tutorial, please do so before moving on. + +This tutorial also, assumes that the reader has a knowledge of basic Unix commands and experience working with a command-line +text editor (e.g. emacs, vi, etc.). To get the most out of this tutorial, you should **follow along, take notes, execute any given commands, +run any code examples, repeat as necessary**. Simply reading (or skimming) is not sufficient for learning this material. + +## Course-Specific Learning Outcomes + +* **LO1.a:** Navigate and modify files, directories, and permissions in a multi-user Unix-like environment. +* **LO1.c:** Create and modify textfiles and source code using a powerful terminal-based text editor such as Emacs or Vi. +* **LO1.d:** Use shell commands to compile new and existing software solutions that are organized into multi-level packages + and have external dependencies. + +## Introduction + +In the previous tutorial, [Java Packages Tutorial - Part 1](https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/packages1.md), +you compiled and ran code that you placed into a named package. In that tutorial, you were working with a single Java +file. In this tutorial, we will compile and run an application that depends on code located in multiple Java files. +When one Java file requires access to another file in order to run, it is called a **code dependency**. When there are +dependencies in our projects, we need to make sure to consider these dependencies when compiling and running our code. +This tutorial will walk you through this process. + +**Note:** This tutorial picks up where the last tutorial left off. You should start by logging into Odin and changing +directories into the `cs1302-packages` directory you created while working through that tutorial. + +## Code Dependencies + +When Java code uses other Java code, that creates a dependency. Most of the programs that you've +written have used code provided by Oracle under the various `java` subpackages. When you compile, +those dependencies are automatically included on the class path. However, when your code depends +on code that's not included with Java (e.g., code that you or someone else has written), you need +to let `javac` know where the _compiled_ version of that depedency is. + +1. Let's extend the code we wrote in the previous tutorial. Create a `cs1302.util.HelloUtility` class under `src`. + **Remember,** the fully qualified name (FQN) implies a specific directory structure and package statement + requirement with respect to `HelloUtility.java`. You will need to add the `util` directory in the proper + place in your current directory hierarchy. + +1. Write the code to declare the `cs1302.util.HelloUtility` class making sure to include the proper + class declaration and package statement at the top. Then, within the class declaration, add the + following method: + + ```java + public static void excitingHello() { + System.out.println("HELLO!!!!"); + } // excitingHello + ``` + +1. Save, then compile the `.java` file for the `cs1302.util.HelloUtility` class as usual, + using `bin` as the destination for the compiled code. Once it compiles, make sure that the + output from `find` matches the output below: + + **Note:** If you see any tilde (~) files, those are just backup copies of older versions + of your files. You can ignore those. + + ``` + . + ./bin + ./bin/cs1302 + ./bin/cs1302/hello + ./bin/cs1302/hello/HelloWorld.class + ./bin/cs1302/util + ./bin/cs1302/util/HelloUtility.class + ./src + ./src/cs1302 + ./src/cs1302/hello + ./src/cs1302/hello/HelloWorld.java + ./src/cs1302/util + ./src/cs1302/util/HelloUtility.java + ``` + +1. Now, modify the source code for your `cs1302.hello.HelloWorld` class to call the static method in + `cs1302.util.HelloUtility`. To do this, you may: + + 1. Add an import statement between the `package` statement and class declation: + + ```java + import cs1302.util.HelloUtility; + ``` + + 1. Call the method in `main` using the simple class name: + + ```java + HelloUtility.excitingHello(); + ``` + + Completing these two steps create a **dependency**. Now, the `cs1302.hello.HelloWorld` class + **depends** on the `cs1302.util.HelloUtility` class because it uses a method defined within that + class. + +1. If you try to compile the source code for your `cs1302.hello.HelloWorld` class exactly as you + did before, then it will not work because the compiler cannot find `cs1302.util.HelloUtility` + class on which `cs1302.hello.HelloWorld` depends. Try it! The error message should look like: + + ``` + src/cs1302/hello/HelloWorld.java:3: error: package cs1302.util does not exist + import cs1302.util.HelloUtility; + ^ + src/cs1302/hello/HelloWorld.java:8: error: cannot find symbol + HelloUtility.excitingHello(); + ^ + symbol: variable HelloUtility + location: class HelloWorld + ``` + + The error output is just `javac` saying that it cannot find something. In this case, it cannot + find `cs1302.util.HelloUtility` as it is not in the same package as `cs1302.hello.HelloWorld`. + Since we know it actually exists, we can just tell `javac` where to find it using `-cp`. + + Remember that when your code depends on other code that you have written, you need to let + `javac` know where the _compiled_ version of that depedency is. Since you compiled under `bin`, + that's where you should tell `javac` to look. Try to compile it again, but this time, be sure + to include the `-cp bin` option in addition to `-d bin` option. The program should now run as expected. + + The correct compilation command for `HelloWorld.java` is: + + ``` + javac -d bin -cp bin src/cs1302/hello/HelloWorld.java + ``` + + With the addition of `-cp bin`, it will be able to find the `HelloUtility` class that it is dependent on. + +1. Run the code to make sure it works. Since we're running the `HelloWorld` class (it has the `main` method), + the command to run will not change from part 1 of this tutorial. Remember, the basic idea is to use the + `java` command along with the FQN of the class you want to run. You will also need `-cp` to tell Java + where to find the class to run. + +## Further Important Notes + +### Setting the Class Path + +Both `javac` and `java` allow you to specify the class path using the `-cp` or `-classpath` command-line +option. The usual syntax is as follows: + +``` +-cp some/path +``` + +If more than one default package is needed, then a colon `:` can be used to separate each path in a +list of multiple paths: + +``` +-cp path1:path2 +``` + +Each path can be a path to a directory or a `.jar` file (usually used for third party libraries). + +**VERY IMPORTANT NOTE:** The class path should always point to a default package for _compiled_ code. +If you are compiling a `.java` file that depends on an already compiled class, then you will need to +specify the class path to the corresponding default package for that dependency when +invoking `javac`. + +### Import Statements + +In Java, you do not have to import classes that are in the same package. However, it's interesting to +note that `import` statements are actually never required in Java. We just use them for convenience. +Assuming the corresponding default package for class's package is on the class path when compiling +and/or running, you can always refer to a class by its fully qualified name. Consider two uses of +[`java.util.Random`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Random.html) below: + +```java +// assuming the class was imported +Random rng = new Random(); +``` + +```java +// assuming the class was NOT imported +java.util.Random rng = new java.util.Random(); +``` + +As you can imagine, the latter (without an import statement) might get annoying and repetitive. +Therefore, we usually prefer to use an `import` statement for the convenience it provides. +Why would anyone prefer to use the fully qualified name instead of the simple name for a class? +It enables you to use two classes from different packages with the same simple name at the +same time! + +### The `java.lang` Package + +Java automatically performs a wildcard import of the `java.lang` package (i.e., `import java.lang.*;`) in +every Java file, without requiring the programmer to explicitly write it. That is why you can use classes +such as `java.lang.String` and `java.lang.System` by their simple names without importing! + +
+ +**Feedback?** +Please help us make this better! +If you have any feedback or suggestions for this reading or tutorial, then use +the link below to reach the feedback form. + +[![Submit Feedback](https://img.shields.io/badge/-Submit Feedback-red.svg?style=for-the-badge)](https://docs.google.com/forms/d/e/1FAIpQLSfBgZM_-G-9nKmX7F83k0Tgp1OlqBnrkt6vsxlIqLypc_keUQ/viewform?usp=pp_url&entry.1081181680=cs1302-packages&entry.1901270436=https://github.com/cs1302uga/cs1302-tutorials/blob/master/packages.md) + +
+ +[![License: CC BY-NC-ND 4.0](https://img.shields.io/badge/License-CC%20BY--NC--ND%204.0-lightgrey.svg)](http://creativecommons.org/licenses/by-nc-nd/4.0/) + + +Copyright © Michael E. Cotterell, Brad Barnes, and the University of Georgia. +This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License to students and the public. +The content and opinions expressed on this Web page do not necessarily reflect the views of nor are they endorsed by the University of Georgia or the University System of Georgia. + diff --git a/refresher/variables.md b/refresher/variables.md index 45d388f7..9f5b1a73 100644 --- a/refresher/variables.md +++ b/refresher/variables.md @@ -1,18 +1,24 @@ # Refresher: Reference Variables -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green)
+## Prerequisite Information + +This tutorial requires a basic understanding of variables, classes, and objects in the Java programming language. + +Before starting this tutorial, please make sure to watch the 1301 review videos on eLC under +"Content" -> "1301 Videos". Specifically, videos 14-22 will help you understand these concepts. + ## Introduction In computer programming, a **variable** is just an alias for a location in memory. Instead of requiring programmers to remember explicit memory -addresses, we let them use variables as a matter of convenience. Some -languages (e.g., C and C++) also allow programmers to deal directly with -memory addresses. Every declared variable has the following: +addresses, we let them use variables as a matter of convenience. Every +declared variable has the following: - a **value**, the actual data stored in some memory location; - a **type**, an attribute that tells the computer how to interpret @@ -20,38 +26,59 @@ memory addresses. Every declared variable has the following: - a **name**, an attribute that tells the computer the word that we want to use to refer to the associated data. -According to [Chapter 4 of the Java Language -Specification](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.10.1), - -> There are two kinds of types in the Java programming language: -> primitive types -> ([§4.2](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.2)) -> and reference types -> ([§4.3](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.3)). -> There are, correspondingly, two kinds of data values that can be -> stored in variables, passed as arguments, returned by methods, and -> operated on: primitive values -> ([§4.2](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.2)) -> and reference values -> ([§4.3](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.3)). +Take a moment to identify the value, type, and name of the variables declared +and initialized below. Before looking ahead, write your answers in your notes. + +```java +int x = 17; +String s = "Hello!"; +``` + +Did you come up with the answers below? + + +| Declaration | Value | Type | Name | +|---------------------|--------|-------|------| +|`int x = 17` | 17 | int | x | +|`String s = "Hello"` | "Hello"| String| s | + + +Notice the type of the two variables above. The first, `int`, is a primitive type and the second, +`String`, is a reference type. You can immediately tell that `String` is a reference type by the +fact that it start with a capital letter. These two variables both contain values but they work +very differently under the hood. In this tutorial, we will demonstrate the important +differences between these two types of variables. ## Reference Types Overview In Java, the **reference types** ([§4.3](https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html#jls-4.3)) -are class types, interface types, and array types. +are class types, interface types, and array types. Of these three, you are likely familiar +with creating variables of both class and array types. Below are two examples: -An **object** is really just a collection of variables that are defined -by a class. It is not uncommon to describe Java objects as dynamically -constructed instances of a class. When an object is constructed, its -collection of variables is stored contiguously in some location in +```java +Person ada; // A class type variable (valid only if we have a class called Person on the classpath) +double[] array; // An array type variable +``` + +Both of the above types are reference types which means that the variables +contain the memory address (location) of the object that they refer to - not +the object itself. + +An **object** is really just a collection +of variables that are defined by a class. It is not uncommon to describe Java +objects as dynamically constructed instances of a class. When an object is +constructed, its collection of variables is stored contiguously in some location in memory, which we usually call the object’s **reference**. This is important because, in Java, the possible values of a reference type are references to compatible objects (or `null`). +Below we describe various scenarios in which you may encounter/use reference variables +in your code. + ### Example 1: Refer to No Object -Consider the following initialization: +Consider the following declaration and initialization: ``` java Scanner s = null; diff --git a/scripts/scripts.md b/scripts/scripts.md index c25e6689..5bd12f68 100644 --- a/scripts/scripts.md +++ b/scripts/scripts.md @@ -1,6 +1,6 @@ # Interpreter Scripts -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) ## What is an Interpreter Script? @@ -17,7 +17,7 @@ An interpreter script needs to satisfy the following requirements: #! interpreter [optional-arg] ``` - Historically, his first line is known as a _shebang_ since it starts with + Historically, this first line is known as a _shebang_ since it starts with the number sign followed by an exclamation mark. The interpreter must be a valid pathname for an executable program which is not @@ -52,7 +52,8 @@ terminal shell. Let's create one! $ stat /path/to/bash ``` -1. Create a regular text file called `cs1302-script.sh` and setup the first +1. By convention, the `.sh` file extension is used for shell scripts. + Create a regular text file called `cs1302-script.sh` and setup the first line so that it conforms to the beforementioned requirements for an interpreter script. Replace `interpreter` with the output of `which`, and exclude an optional arguments for now. It should look this: @@ -81,10 +82,15 @@ terminal shell. Let's create one! ``` 1. From the terminal shell itself, use the `chmod` command to enable - user execute permission for `cs1302-script.sh`. Verify that change - using `ls -l` or `stat`. + user execute permission for `cs1302-script.sh`: -1. Execute the script. To do this simple provide an absolute path to + ``` + chmod u+x cs1302-script.sh + ``` + +1. Verify that the permissions are changed using `ls -l` or `stat`. + +1. Execute the script. To do this, simply provide an absolute path to the script name or an abbreviated absolute path using the `.` directory. For example, you might try one of the following, the first of which will need to be modified slightly based on the @@ -106,7 +112,7 @@ terminal shell. Let's create one! 1. Notice the output. It executed both commands! - 1. That's it! You now know know the basics of Bash scripts. There is a lot + 1. That's it! You now know the basics of Bash scripts. There is a lot more than can be done, but we recommend that you look those things up when you need them. For further reading, the nicely written and free _BASH Programming_ book by Mike G can be found diff --git a/setup/MacOS.md b/setup/MacOS.md new file mode 100644 index 00000000..8497682c --- /dev/null +++ b/setup/MacOS.md @@ -0,0 +1,125 @@ +# Setup on macOS + +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) + +The following instructions are designed to help get you up and running with macOS for development +in CSCI 1302. The majority of the time, you will not be developing directly on your Mac. Instead, +you will use your Mac to connect to a remote server via a terminal emulator. Once connected, the +commands that you type and the programs that you run will be executed on the remote server instead +of on your local machine. + +## Setup `Ctrl-` + +If typing `Ctrl-` (i.e., `⌃Space`) changes your keyboard layout, then you will need to +adjust some settings as that keyboard shortcut is used heavily in one of the programs we'll +be using this semester. **If it doesn't, then you can skip to the next section.** + +To fix `Ctrl-`, click the apple icon in the top-left of your screen then select "System Preferences". +From there, go to the "Keyboard Settings" which may be just called "Keyboard", then select the +"Shortcuts" tab. Find the shortcut that is mapped to `⌃Space` and either change it +or disable it. Once you've made the change, you should be all set as far as +`Ctrl-` is concerned. + +## Open Terminal + +The macOS operating system comes with a [terminal emulator](https://en.wikipedia.org/wiki/Terminal_emulator) +called [Terminal](https://support.apple.com/guide/terminal/welcome/mac). + +1. **Open Terminal.** On your Mac, do one of the following: + * Click the Launchpad icon + + in the Dock, type `Terminal` in the search field, then click **Terminal**. + * Click the Spotlight icon + + in the upper-right corner of the menu bar (or press Command-Space), type `Terminal` in the search field, + then click **Terminal**. + * In the Finder + , + open the `/Applications/Utilities` folder, then double-click **Terminal**. + +2. **Explore.** At its core, macOS is powered by a powerful Unix-like kernel called + [Darwin](https://en.wikipedia.org/wiki/Darwin_(operating_system)). + Using Terminal, you can interact with your system using most Unix commands. + +## Use Option as Meta + +Some of the programs that you will use this semester will require the use of the META key. +On some systems, this is the same as the ESC or ALT key. On a Mac, you can set Terminal to +use the OPTION key as META. + +1. **Open Terminal.** +2. In the menu bar, click **Terminal**, then click **Settings...**. +3. In the window that appears, select the **Profiles** option at the top. +4. In the tabs that appear below **Profiles**, select the **Keyboard** tab. +5. Near the bottom of the pane, check the box for **Use Option as Meta key.** + - **The setting does not take effect immediately!** + It will take effect the next time you open **Terminal**. +6. Quit the **Terminal** app by selecting **Quit Terminal** from the **File** menu (or by + pressing ⌘Q). + +## Install Homebrew + +[Homebrew](https://brew.sh) is a package manager for MacOS. It makes it really easy to install programs +on your Mac via [Terminal](https://support.apple.com/guide/terminal/welcome/mac). + +1. **Open Terminal.** + +2. **Install Homebrew.** + To do this, you will need to type a command at the prompt. + + 1. When presenting commands, we often prepend the start of a command line with a `$` + to denote the shell prompt. The `$` lets you know that the line that follows is + something that you should type into your terminal emulator at the shell prompt, + which usually ends with `$` pr `%` followed by a white-space. + **Do not type or copy the `$` before the command name as it is not part of the command.** + + 2. When installing Homebrew, the installer may ask you for a password. If it does, then + it is referring to the password for your Mac. + + 3. To run the Homebrew installer, type the following command: + + ``` + $ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" + ``` + + 4. Homebrew must be installed to continue. If installation fails, inspect the messages emitted + by the installer -- in most cases, it will tell you what you need to do in order to fix + the issues that are preventing installation. + +3. **Install Utilities via Homebrew.** Type the following command to install [git](https://git-scm.com/) + and [wget](https://www.gnu.org/software/wget/): + + ``` + $ brew install git wget + ``` + + **If you run into issues with `brew install`**, then please try running `brew doctor` first to see + if it has a suggested fix. If it does, then try the fix. If it doesn't or if it does but that doesn't + resolve your issue, then you may need to ask Piazza or see instructor during office hours. + +## Install XQuartz + +[XQuartz](https://www.xquartz.org) is an open-source version of the +[X.Org X Window System](http://www.x.org/) that runs on MacOS. +Installing XQuartz will enable you to forward the graphical user interface +for remote programs that you write later in the semester to your local machine. + +1. **Open Terminal.** + +2. **Install XQuartz.** Type the following command: +3. + ``` + $ brew install --cask xquartz + ``` + +3. **Restart your Mac.** The best way to restart your Mac is to choose Restart from the Apple () menu. + +
+ +[![License: CC BY-NC-ND 4.0](https://img.shields.io/badge/License-CC%20BY--NC--ND%204.0-lightgrey.svg)](http://creativecommons.org/licenses/by-nc-nd/4.0/) + + +Copyright © Michael E. Cotterell, Bradley J. Barnes, and the University of Georgia. +This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License to students and the public. +The content and opinions expressed on this Web page do not necessarily reflect the views of nor are they endorsed by the University of Georgia or the University System of Georgia. + diff --git a/setup/Windows.md b/setup/Windows.md new file mode 100644 index 00000000..017823ca --- /dev/null +++ b/setup/Windows.md @@ -0,0 +1,93 @@ +# Setup on Windows 10 & 11 + +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) + +The following instructions are designed to help get you up and running with a Windows 10 or 11 +PC for development in CSCI 1302. The majority of the time, you will not be developing directly on +your PC. Instead, you will use your PC to connect to a remote server via a terminal emulator. Once +connected, the commands that you type and the programs that you run will be executed on the remote +server instead of on your local machine. + +## Install MobaXterm + +For Windows 10, we recommend the use of a [terminal emulator](https://en.wikipedia.org/wiki/Terminal_emulator) +called [MobaXterm](https://mobaxterm.mobatek.net). + +1. Download and install the free Home version of MobaXterm (Installer edition) at the link presented below: + + **WARNING:** If you download a `.zip` file for one of the MobaXterm installers, then you need to fully + extract the `.zip` file into a folder before attempting to install. Do not attempt to run the installer + from within the `.zip` file. Instead, run the installer program from within the folder that you extract to. + + **Note:** Your window may look slightly different than below. If you see "Extract All" instead of "Extract", go + ahead and click that button. You can choose the default location as the place to extract. It will likely use + your `Downloads` folder for the extracted files. Once it's extracted, you can double-click the installer to begin + the installation process. + + ![WARNING](in-zip-file.png) + + MobaXterm Website: https://mobaxterm.mobatek.net/download-home-edition.html + +## Setup Backspace (Required) + +MobaXterm often modifies the backspace key to send `C-h` (`^H`) instead of the +proper backspace key code. This can cause problems if you regularly use the +backspace key to perform backward deletions (very common). To fix this issue, +follow these steps: + +1. Open **MobaXterm**. +2. In the menu bar, click **Settings**, then click **Configuration**. +3. In the window that appears, select the **Terminal** tab if not selected already. +4. Near the bottom of the window, make sure the checkbox for **Backspace sends ^H** is + *unchecked*, then click the **OK** button to close the window. + - **The setting does not take effect immediately!** + It will take effect the next time you open **MobaXterm**. +6. Quit **MobaXterm** app by selecting **Quit** from the **Terminal** menu. + +If this is the first time you are reading these instructions, then make a note +to yourself to return to this section if you encounter backspace issues with +MobaXterm in the future. The steps below should only be taken if you +are returning here to resolve a backspace issue: + +1. First, try repeating the steps above to *uncheck* the **Backspace sends ^H** + setting -- remember to quit and relaunch **MobaXterm** before attempting to + verify that your issue is fixed. + +2. If you still encounter backspace issues, then **MobaXterm** may not be honoring + the *unchecked* state of the **Backspace sends ^H** setting. To remedy that, + open **MobaXterm**, launch a local terminal, but **do NOT connect to Odin**. + Instead, enter the commands below to deploy a configuration file that should + fix the issue: + + ``` + $ wget http://cobweb.cs.uga.edu/~mec/cs1302/mobaxterm.bashrc + $ mv mobaxterm.bashrc .bashrc + $ source .bashrc + ``` + + Now, you should be able to `ssh` into Odin with MobaXterm and have your + beautiful backspace key work as intended! + +## Setup `Ctrl-` and `Ctrl-X` (Required) + +In newer versions of MobaXterm, `Ctrl-` (`Ctrl + SPACE`) and `Ctrl-X` (`Ctrl + Shift + X`) +may be mapped to MobaXterm-specific shortcuts. This will cause problems when it comes time to +work in Emacs as those key combinations are used quite often. Please update +your MobaXterm settings by doing the following steps: + + 1. Select "Settings" from the menu bar, then "Keyboard shortcuts". + 1. In the window that appears, find and select the shortcut for "Ctrl-SPACE" or "Ctrl + SPACE". + 1. Once selected, find the "Edit keyboard shortcut" dropdown list and + change it to "" or `` (which should be at the top of the list). + 1. Repeat the previous step on the shortcut for "Ctrl-X" or "Ctrl + Shift + X". + 1. Select "OK". The issue should now be resolved. + +
+ +[![License: CC BY-NC-ND 4.0](https://img.shields.io/badge/License-CC%20BY--NC--ND%204.0-lightgrey.svg)](http://creativecommons.org/licenses/by-nc-nd/4.0/) + + +Copyright © Michael E. Cotterell, Bradley J. Barnes, and the University of Georgia. +This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License to students and the public. +The content and opinions expressed on this Web page do not necessarily reflect the views of nor are they endorsed by the University of Georgia or the University System of Georgia. + diff --git a/setup/in-zip-file.png b/setup/in-zip-file.png new file mode 100644 index 00000000..19af666a Binary files /dev/null and b/setup/in-zip-file.png differ diff --git a/threads/brief-intro-threads.md b/threads/brief-intro-threads.md index e7b03a7f..4b64f21c 100644 --- a/threads/brief-intro-threads.md +++ b/threads/brief-intro-threads.md @@ -1,6 +1,6 @@ # Brief Introduction to Java Threads -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Spring 2023](https://img.shields.io/badge/Approved%20for-Spring%202023-magenta) ## Prerequisites diff --git a/uml/uml.md b/uml/uml.md index 463aec53..f74c549e 100644 --- a/uml/uml.md +++ b/uml/uml.md @@ -1,12 +1,12 @@ # UML Class Diagrams -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) ## Introduction In object-oriented programming, it's not uncommon to visualize classes and their relationships using the Unified Modeling Language (UML). -While UML has many different types of diagrams, this reading focusses only +While UML has many different types of diagrams, this reading focuses only on UML class diagrams. ### Basic Class Diagram @@ -73,7 +73,8 @@ UML supports the standard four visibilities: | protected | `protected` | `#` | | public | `public` | `+` | -For an in-depth discussion on visibilities, see the [Visibility Reading](/visibility/). +You should be familiar with at least two of these visibilities (`public` and `private`). If you would like to read ahead to +learn about the other two, see the [Visibility Reading](/visibility/) which we will cover soon. ### Atributes and Parameters (Variables) diff --git a/unix/unix-getting-started.rst b/unix/unix-getting-started.rst index bcba4cf6..c47c2ea8 100644 --- a/unix/unix-getting-started.rst +++ b/unix/unix-getting-started.rst @@ -1,5 +1,5 @@ .. sectnum:: -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple +.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Fall%202023-green ======================= Unix: Getting Started @@ -10,6 +10,20 @@ .. contents:: **Table of Contents** :depth: 3 +How to engage with this tutorial +================================ + +When working through any tutorial in 1302, it is expected that you will fully engage with the material. In +other words, it is not sufficient to skim read the content. You should carefully read and process +and then follow along by typing the commands into your terminal emulator, taking notes as you go. +We recommend writing the answers to any questions asked in this tutorial in your notes along with some +context. These notes will be helpful for studying. If you have any questions as you are working through +the tutorial, you are encouraged to post on the course Piazza page. Your questions will not only help +you fill gaps in your knowledge but also give us insight on potential updates to the tutorials. + +Fully engaging with the content will improve your understanding of the content and help you retain +the information long term. + Introduction ============ @@ -32,8 +46,10 @@ Here are some examples of what such a prompt might look like: zsh% -The shell is just another way to interact with computer. These days, all -students are familiar with the point-and-click graphical windowing systems +The shell is just another way to interact with computer. Think of it as an interface +that allows you to type your commands on the keyboard instead of clicking icons on the +screen. Both interfaces allow you to do the same things, just in a different way. +These days, all students are familiar with the point-and-click graphical windowing systems provided in operating systems like Windows, macOS, and even phones. However, only some realize that the windowing system they're used to is only one way to interact with a computer. Consider the figure below. @@ -47,7 +63,10 @@ emulator (or a "terminal window," for short) is displayed containing the output of the commands ``ls`` and ``tree`` (discussed later). On the right, the graphical Finder app is displayed containing some of the same information. Take a moment to convince yourself that both images are displaying roughly the same information -in two different ways. +in two different ways. On the left, the output of the ``tree`` command looks very +similar to the output on the right. The only difference is that the user typed +the command with the keyboard instead of double-clicking a folder icon as they would +on the right. Prompt and Circumstance ======================= @@ -96,8 +115,8 @@ that you can follow along with the tutorial. If you are using a Windows computer or a Mac, then please follow the instructions below that best match your computer's operating system. -* `Setup on macOS `__ -* `Setup on Windows 10 `__ +* `Setup on macOS `__ +* `Setup on Windows 10 `__ (should also work for Windows 11) If you are using a Linux computer or a computer running a Unix-like operating @@ -109,9 +128,12 @@ system's documentation. Local Terminal ============== -When you run a terminal emulator, the usual default is for it -to connect to the same computer it is running on. This *local terminal* -provides a shell with a command-line interface to that computer. Consider the +When you run a terminal emulator on your local (personal) computer (laptop or desktop), +the default is for it to connect to the same computer it is running on. In other +words, any commands you type will execute on your local computer. For example, +executing the ``ls`` command will list all of the files in the directory the shell +is working from on your local computer. This *local terminal* +provides a shell with a command-line interface to your computer. Consider the figure below. .. figure:: img/local-terminals.png @@ -131,11 +153,14 @@ operating system. Remote Terminal =============== -To make sure that readers all have roughly the same experience with the tutorial, -we will instruct them to use a local terminal to launch a program that will +In this course, you will rarely be working from your local computer. Instead, +we will instruct you to use a local terminal to launch a program that will connect their terminal emulator to a remote computer (often referred to as a server). Once connected, that *remote terminal* provides a shell with a command-line -interface to that remote computer. Consider the figure below. +interface to that remote computer. Once connected, any commands you type will execute +on the remote computer instead of on your local machine. So, typing ``ls`` will list +the contents of the remote directory instead of a directory found on your computer. +Consider the figure below. .. figure:: img/remote-terminals.png :alt: iTerm 2 on macOS Big Sur (left) and MobaXterm 21.2 on Windows 10 (right) @@ -156,9 +181,174 @@ as illustrated in the figure below. all connected to a remote computer (center). Most Unix-like operating systems support multiple users and multiple sessions -per user. The tutorial will show you how to establish a remote terminal -session. After that, you are encouraged to try logging in more than once to -see what it's like. +per user. Next, we will show you how to establish a remote terminal +session with our departmental server. After that, you are encouraged to try logging +in more than once to see what it's like. + +Logging into a Remote Unix Machine +================================== + +In this section, you will log into your account on the computer science departmental server called +Odin. We will do all of our programming this semester on this Unix server so you become comfortable +working in a command-line Unix environment. + +Access to Odin is restricted behind a firewall. In order to access Odin from off-campus, you +will need to connect to UGA's remote access VPN using the instructions found +`here `_. + +Important Note +++++++++++++++ + +For CSCI 1302, you are expected to connect to Odin using SSH and the programs +desribed in the instructions provided by your instructor. While other programs may exist +that also allow you to establish an SSH connection to Odin, use of certain programs +is explicitly forbidden in CSCI 1302 since they consume large amounts of remote system +resources, disrupting other students' use of the system. +You should NOT use any of the following programs to connect to Odin: + +* `Video Studio Code Remote Development Extension `_ +* `code-server `_ +* `JetBrains Remote Development Toolset `_ + +Using the programs mentioned above or programs like the ones mentioned above +without permission violates sections 4.2 and 4.3 of the +`UGA Policies on the Use of Computers `_. + + +``ssh`` ++++++++ + +Your username on Odin is your UGA MyID and the password is the same one that +is associated with your MyID. Once you are successfully logged into the VPN, +open up a local terminal in your terminal emulator and execute the ``ssh`` +(secure shell) command shown below to establish a secure connection -- be +sure to replace ``username`` with your MyID. When you type in your password, +it will not display anything to the screen -- this is the expected behavior. +Simply type in your password, then press the return key to continue. + +.. code-block:: shell + + $ ssh username@odin.cs.uga.edu + +.. figure:: img/login-demo.svg + +If you have trouble logging into Odin, then please +contact support@cs.uga.edu as soon as possible. + +Remember, when typing into a remote terminal, the commands that you enter +are executed on the remote computer - not on your personal computer. + +.. table:: + + ===================== ====================================================================== + Command Description + ===================== ====================================================================== + ``ssh user@hostname`` Start a secure shell connection to ``hostname`` and login as ``user``. + ===================== ====================================================================== + +``pwd`` ++++++++ + +When you login to Odin, you are placed in your *home directory* (home folder). +You can think of this as your own personal folder where your files will be stored +on Odin. Any code you write in 1302 will be in a subfolder of your home directory. + +You can see where your home directory is on the system with the help of the +``pwd`` (print working directory) command. It always displays the absolute +"path" of the directory that you are presently in. It is called an absolute +path, because it describes the path of directories that you would need to +traverse to get from the root of the file system (i.e., the ``/`` directory) +to the current working directory one directory at a time. + +.. code-block:: shell + + $ pwd + +.. figure:: img/pwd-demo.svg?1 + +.. code-block:: plain + + / + └── home + └── myid + └── mepcott + +* What is the absolute path of your home directory? +* What character does an absolute path always start with, and + what does it represent? + +.. table:: + + ======== ====================================================================== + Command Description + ======== ====================================================================== + ``pwd`` Print absolute path of current working directory. + ======== ====================================================================== + +``date``, ``exit``, ``whoami`` +++++++++++++++++++++++++++++++ + +Listed below are some easy commands that you can try out immediately, some +of which you may have seen in earlier examples. + +.. table:: + + ========== ====================================================================================== + Command Description + ========== ====================================================================================== + ``date`` Print the system date and time. + ``exit`` Exit the current shell. + ``whoami`` Print the user name associated with the current user. + ========== ====================================================================================== + +``.bash_profile`` (Required Command) +++++++++++++++++++++++++++++++++++++ + +To continue with this tutorial, the **CSCI 1302 shell profile** needs +to be enabled on your Odin account. Enabling this profile is also required +to complete coursework in CSCI 1302. A *shell profile* includes commands +and setting customizations that take effect when the profile is *sourced* (loaded). +This step will set up your programming environment for 1302. It will tell the system +where to find the java compiler and other tools that we will use throughout the +semester. + +If you see something similar to what is presented below when you login, +then the CSCI 1302 shell profile is enabled on your account, and you should +proceed immediately to the next section of this tutorial. + +.. figure:: img/cs1302-profile-check-demo.svg?1 + + +* If you do not see any of that when you login, then the CSCI 1302 shell profile + is not enabled on your account. To enable it, execute the command below. The + command adds a line to the ``.bash_profile`` file in your home directory so + that the profile is sourced each time you login. You won't have to run this command + again this semester. + + **NOTE:** Unlike some of the examples you've seen with ``mepcott`` (i.e., Dr. Cotterell's + username), the ``mepcott`` in the following command should NOT be replaced with + your username. The command is provided by Dr. Cotterell to enable the + CSCI 1302 shell profile on your account. + + .. code-block:: shell + + $ /usr/local/mepcott/cs1302.enable + + .. code-block:: shell + + # |-------| + # | + # MUST USE "mepcott" HERE + + .. figure:: img/cs1302-profile-enable-demo.svg + + +**Make sure that you logout, then login again before continuing.** +When you log back in, you should see output similar to what is shown in the video +at the start of this section. + +Congratulations! If you see the output above when you log into Odin, you have set up your +Odin account. You're now ready to log into a remote computer and develop software! .. copyright and license information .. |copy| unicode:: U+000A9 .. COPYRIGHT SIGN diff --git a/unix/unix-tutorial.rst b/unix/unix-tutorial.rst index 2876685e..e1f96f9c 100644 --- a/unix/unix-tutorial.rst +++ b/unix/unix-tutorial.rst @@ -1,5 +1,5 @@ .. sectnum:: -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple +.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Fall%202023-green ================ Unix: Tutorial @@ -12,172 +12,30 @@ ---- -This tutorial assumes that the reader is a Computer Science student -at the University of Georgia with access to the department's -instructional server called Odin. If you were assigned this reading in a -CSCI class at UGA, then you probably have access. We recommend writing the -answers to any questions asked in this tutorial in your notes along with some -context. These notes will be helpful for studying. -Logging into a Unix Machine ---------------------------- +How to engage with this tutorial +--------------------------------- -Access to Odin is restricted behind a firewall. In order to access Odin off-campus, you -will need to connect to UGA's remote access VPN using the instructions found -`here `_. +**Important:** If you have not completed the +`Unix: Getting Started `_ +tutorial, please complete that before beginning this tutorial. -``ssh`` -+++++++ - -Your username on Odin is your UGA MyID and the password is the same one that -is associated with your MyID. Once you are successfully logged into the VPN, -open up a local terminal in your terminal emulator and execute the ``ssh`` -(secure shell) command shown below to establish a secure connection -- be -sure to replace ``username`` with your MyID. When you type in your password, -it will not display anything to the screen -- this is the expected behavior. -Simply type in your password, then press the return key to continue. - -.. code-block:: shell - - $ ssh username@odin.cs.uga.edu - -.. figure:: img/login-demo.svg - -If you have trouble logging into Odin, then please -contact support@cs.uga.edu as soon as possible. - -When typing into a remote terminal, the commands that you enter -are executed on the remote computer. It might look like you are -running programs locally, but they are simply being displayed -locally. - -.. table:: +When working through any tutorial in 1302, it is expected that you will fully engage with the material. In +other words, it is not sufficient to skim read the content. You should carefully read and process +and then follow along by typing the commands into your terminal emulator, taking notes as you go. +We recommend writing the answers to any questions asked in this tutorial in your notes along with some +context. For this tutorial, **we recommend logging into Odin and typing the commands as you work through +the examples**. If you have any questions as you are working through +the tutorial, you are encouraged to post on the course Piazza page. Your questions will not only help +you fill gaps in your knowledge but also give us insight on potential updates to the tutorials. - ===================== ====================================================================== - Command Description - ===================== ====================================================================== - ``ssh user@hostname`` Start a secure shell connection to ``hostname`` and login as ``user``. - ===================== ====================================================================== - -Important Note -++++++++++++++ - -For CSCI 1302, you are expected to connect to Odin using SSH and the programs -desribed in the instructions provided by your instructor. While other programs may exist -that also allow you to establish an SSH connection to Odin, use of certain programs -is explicitly forbidden in CSCI 1302 since they consume large amounts of remote system -resources, disrupting other students' use of the system. -You should NOT use any of the following programs to connect to Odin: - -* `Video Studio Code Remote Development Extension `_ -* `code-server `_ - -Using the programs mentioned above or programs like the ones mentioned above -without permission violates sections 4.2 and 4.3 of the -`UGA Policies on the Use of Computers `_. - -``pwd`` -+++++++ - -When you login to Odin, you are placed in your *home directory* (home folder). -You can see where your home directory is on the system with the help of the -``pwd`` (print working directory) command. It always displays the absolute -"path" of the directory that you are presently in. It is called an absolute -path, because it describes the path of directories that you would need to -traverse to get from the root of the file system (i.e., the ``/`` directory) -to the current working directory one directory at a time. - -.. code-block:: shell - - $ pwd - -.. figure:: img/pwd-demo.svg?1 - -.. code-block:: plain - - / - └── home - └── myid - └── mepcott - -* What is the absolute path of your home directory? -* What character does an absolute path always start with, and - what does it represent? - -.. table:: - - ======== ====================================================================== - Command Description - ======== ====================================================================== - ``pwd`` Print absolute path of current working directory. - ======== ====================================================================== - -``date``, ``exit``, ``whoami`` -++++++++++++++++++++++++++++++ - -Listed below are some easy commands that you can try out immediately, some -of which you may have seen in earlier examples. - -.. table:: - - ========== ====================================================================================== - Command Description - ========== ====================================================================================== - ``date`` Print the system date and time. - ``exit`` Exit the current shell. - ``whoami`` Print the user name associated with the current user. - ========== ====================================================================================== - -``.bash_profile`` -+++++++++++++++++ - -To continue with this tutorial, the **CSCI 1302 shell profile** needs -to be enabled on your Odin account. Enabling this profile is also required -to complete coursework in CSCI 1302. A *shell profile* includes commands -and setting customizations that take effect when the profile is *sourced* (loaded). -When ``bash`` is launched as a login shell, it sources a default system profile, -then it looks in the user's home directory for ``.bash_profile``, ``.bash_login``, -and ``.profile`` files, in that order, and sources the first one that is available. - -You may already have the CSCI 1302 shell profile enabled. If you do, then -you will see ``Setting up environment for CSCI 1302...`` -followed by lines prefixed with ``[cs1302]`` when you login to Odin. - -.. figure:: img/cs1302-profile-check-demo.svg?1 - -* If you see something similar to what is presented above when you login, - then the CSCI 1302 shell profile is enabled on your account, and you should - proceed immediately to the next section of this tutorial. - -* If you do not see any of that when you login, then the CSCI 1302 shell profile - is not enabled on your account. To enable it, execute the command below. The - command adds a line to the ``.bash_profile`` file in your home directory so - that the profile is sourced each time you login. You won't have to run this command - again this semester. - - **NOTE:** Unlike some of the examples you've seen with ``mepcott`` (i.e., Dr. Cotterell's - username), the ``mepcott`` in the following command should NOT be replaced with - your username. The command is provided by Dr. Cotterell to enable the - CSCI 1302 shell profile on your account. - - .. code-block:: shell - - $ /usr/local/mepcott/cs1302.enable - - .. code-block:: shell - - # |-------| - # | - # MUST USE "mepcott" HERE - - .. figure:: img/cs1302-profile-enable-demo.svg - - * **Make sure that you logout, then login again before continuing.** +Fully engaging with the content will improve your understanding of the content and help you retain +the information long term. Navigating the File System ------------------------- -Earlier in this tutorial, you experienced the ``pwd`` (print working directory) +In the previous tutorial, you experienced the ``pwd`` (print working directory) command and were provided a brief introduction to absolute paths. In Unix, a *directory file* or *directory* is the same concept as a folder in other operating systems; that is, in most cases the words "directory" and "folder" @@ -233,7 +91,7 @@ path to that directory as a command-line argument. absolute path? While ``ls`` is nice and probably one of the most used Unix commands of all time, -it doesn't really let us see the whole picture without us issuing repetetive +it doesn't really let us see the whole picture without us issuing repetitive ``ls`` commands. To see the bigger picture, use the ``tree`` command, which lists the contents of a directory in a tree-like format. @@ -252,7 +110,7 @@ lists the contents of a directory in a tree-like format. =============== ====================================================================================================== ``ls`` List contents of current working directory. ``ls PATH`` List contents of the last directory in the provided ``PATH`` (e.g., ``c`` in ``a/b/c`` or ``/a/b/c``). - ``tree PATH`` List contents of the last directory in the provided ``PATH`` and its subdirecoties, in a tree format. + ``tree PATH`` List contents of the last directory in the provided ``PATH`` and its subdirectories, in a tree format. =============== ====================================================================================================== ``ls -l``, ``ls -lh`` @@ -297,48 +155,18 @@ is included in the "long" output format, as described below the next few example .. [1] .. rubric:: **Mode** - The file type and permissions. The first character denotes the file type. - In Unix, file type refers to how the file behaves from the file system's perspective. - File type and content format are different concepts. File suffixes like ``.txt``, - ``.mp3``, ``.pdf``, etc. are all naming conventions for the content formats of certain - regular files. Common file types include: - - ========= ============== =================== - Character File Type Description - ========= ============== =================== - ``-`` regular file text or binary data - ``d`` directory file collection of files - ``l`` symbolic link shortcut to a file - ========= ============== =================== - - The next nine (9) characters denote the read (``r``), write (``w``), and execute (``x``) permissions - for the file's user (``u``), group (``g``), and others (``o``). We will go into more detail regarding - file permissions later, but here is a quick breakdown for ``rw-r--r--``: - - ===== ===== ===== ===== ===== ===== ===== ===== ===== - User Group Others - ------------------- ------------------- ------------------- - R W X R W X R W X - ===== ===== ===== ===== ===== ===== ===== ===== ===== - ``r`` ``w`` ``-`` ``r`` ``-`` ``-`` ``r`` ``-`` ``-`` - ✓ ✓ ✗ ✓ ✗ ✗ ✓ ✗ ✗ - ===== ===== ===== ===== ===== ===== ===== ===== ===== - - File type cannot usually be changed after a file has been created; however, a file's permissions - can always be changed by its owner, a superuser (administrator), or a program acting on behalf - of either the owner or a superuser. It is also worth noting that superusers are usually not - subject to permission restrictions. - - The eleventh (11) character specifies whether an alternate access method such as an access control list - applies to the file in addition to the displayed permissions. This topic is beyond the scope of this - reading, but for those who are curious, the ``.`` indicates that a file has an SELinux security context - and no other alternate access method. + The mode specifies the file type and permissions. The first character tells you what type of file is listed. + In most cases, this character will be either ``-`` for regular files and ``d`` for directories. + The rest of the bits represent the permissions of the file; in other words, which users on the system are + allowed to read, modify, and execute the file. We will talk about permissions in more detail in a few weeks. + If you are interested in reading ahead, please see the + `1302 Octal Mode Tutorial `_. .. [2] .. rubric:: **Hard Links** This topic is outside the scope of this reading. If you are interested in hard links, then you are encouraged to read about them `here `_. - Symbolic links are more common, and will discussed in a future reading. + Symbolic links are more common, and will be discussed in a future reading. .. [3] .. rubric:: **User / Owner** @@ -359,7 +187,7 @@ is included in the "long" output format, as described below the next few example Normally the size is printed as a byte count or block count without punctuation. These days, byte counts are not very readable, especially for larger file sizes. You can make the output more human-readable by supplying the ``-h`` (human-readable) option as a command-line - argument to ``ls -l``. The human-readable output uses unites like ``K`` (kilobyte), ``M`` (megabyte), + argument to ``ls -l``. The human-readable output uses units like ``K`` (kilobyte), ``M`` (megabyte), ``G`` (gigabyte), etc. whenever they apply. Block counts are usually shown for directories, but that topic is outside the scope of this reading. @@ -443,7 +271,7 @@ then supply ``-`` (minus sign) as a command-line argument to ``cd``. .. figure:: img/cd-minus-demo.svg -On most Unix systems, ``~`` (tilde) is an alias for the absolute path of your home directoy. +On most Unix systems, ``~`` (tilde) is an alias for the absolute path of your home directory. While you can use it with ``cd`` to change directly to your home directory, it's more commonly used to change to directories nested under your home directory. @@ -470,7 +298,7 @@ to your home directory. How convenient! ``cd`` home directory ``cd -`` last previous working directory ``cd a/b/dest`` ``dest``, assuming ``a`` is in the current directory and ``a/b/dest`` is a valid *relative* path - ``cd /a/b/dest`` ``dest``, assuming ``/path/to/dest`` is a valid *absolute* path + ``cd /a/b/dest`` ``dest``, assuming ``/a/b/dest`` is a valid *absolute* path ``cd ~/a/b/dest`` ``dest``, assuming ``a`` is in your home directory and ``~/a/b/dest`` is a valid path ================= ================================================================================================ @@ -487,7 +315,7 @@ as a command-line argument. .. figure:: img/ls-all-demo.svg -Every directy on a Unix system has two special hidden files +Every directory on a Unix system has two special hidden files named ``.`` and ``..``. .. table:: @@ -565,7 +393,7 @@ Keyboard Shortcuts ======== ==================================================== Key Description ======== ==================================================== - ``C`` ``CRTL`` (control) + ``C`` ``CTRL`` (control) ``M`` ``META`` (meta): usually ``ALT``, ``OPT`` or ``ESC`` ======== ==================================================== @@ -634,7 +462,7 @@ a path to the file you want to view as a command-line argument. ++++++++ The ``cat`` command displays the entire contents of a file all at once, -which may not be desirabe for large files. To display the contents of +which may not be desirable for large files. To display the contents of a regular file one page (or screen) at a time, use the ``less`` command and supply a path to the file you want to view as a command-line argument. To quit out of ``less``, press the ``q`` key. To move up and down one @@ -732,8 +560,8 @@ using ASCII characters:: dirname basename Understanding this split is important when it comes to -moving and renaming file as both concepts deal -with the modification of a file's absolute path. +moving and renaming a file as both of those tasks modify +a file's absolute path when performed successfully. .. |Y| replace:: ✓ .. |N| replace:: ✗ @@ -742,7 +570,7 @@ with the modification of a file's absolute path. ======= ======== ====================== If you modify Related ----------------- ---------------------- - dirname basename Concept + dirname basename Task ======= ======== ====================== |Y| |N| move a file |N| |Y| rename a file @@ -752,7 +580,7 @@ with the modification of a file's absolute path. If you are unsure what the absolute path for a file is, but you do know some relative path for it, then you can print its absolute path using the ``realpath`` command, -supplying the relative path as a command-line argument. +supplying the relative path as a command-line argument: .. code-block:: shell @@ -762,8 +590,7 @@ supplying the relative path as a command-line argument. .. figure:: img/realpath-demo.svg To move or rename a file in Unix, use the ``mv`` (move) command. -Here is some of usage information adapted from the -manual: +Here is some usage information adapted from the manual: .. table:: @@ -819,7 +646,7 @@ using ``man mv``. +++++++++++++++++ To copy a file in Unix, use the ``cp`` (copy) command. -Here is some of usage information adapted from the +Here is some usage information adapted from the manual: .. table:: diff --git a/varargs/varargs.md b/varargs/varargs.md index 61dd4f78..ae7eafd5 100644 --- a/varargs/varargs.md +++ b/varargs/varargs.md @@ -1,6 +1,6 @@ # Variable Arguments (Varargs) Reading -![Approved for: Spring 2022](https://img.shields.io/badge/Approved%20for-Spring%202022-purple) +![Approved for: Fall 2023](https://img.shields.io/badge/Approved%20for-Fall%202023-green) ## Introduction @@ -26,7 +26,7 @@ public static void printlns(PrintStream out, String[] args) { Then, [elsewhere](src/cs1302/util/Driver.java), you might call the `printlns` method like this: -``` +```java // elsewhere Helper.printlns(System.out, new String[] { "a", "b", "c" }); Helper.printlns(System.out, new String[] { "d", "e" }); @@ -47,10 +47,10 @@ Helper.printlns(System.out, new String[] { "g", "h", "i", "j", "k" }); ``` To facilitate this, your first instinct might be to create a set -of method _overloads_ for the `printlns` method. That's a good thought, +of method _overloads_ for the `printlns` method. That's a good thought; however, it would also be tedious. How many parameters will the method need? Is it three? Two? One? We don't really know ahead of time. -This is where a **varags declaration** comes into play: +This is where a **varargs declaration** comes into play: ```java /** diff --git a/visibility/package-private.rst b/visibility/package-private.rst index ebdfc0f5..0e3bf10e 100644 --- a/visibility/package-private.rst +++ b/visibility/package-private.rst @@ -1,5 +1,5 @@ -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple - :alt: Approved for: Spring 2022 +.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Fall%202023-green + :alt: Approved for: Fall 2023 Visibility Reading ################## @@ -122,7 +122,7 @@ Example 2 In this example, we'll see how package private visibility can be used at the member-level for access control. Suppose a factory has a contract with a store to -produce some product. Throughout the year, the store mfay need to request +produce some product. Throughout the year, the store may need to request changes to its contract based on sales, buyer interest, etc. The driver program on the factory's side should be able to access methods to request, approve, and deny contract-related changes; however, the overall class design diff --git a/visibility/protected.rst b/visibility/protected.rst index ccc2b7ca..9b695037 100644 --- a/visibility/protected.rst +++ b/visibility/protected.rst @@ -1,5 +1,5 @@ -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple - :alt: Approved for: Spring 2022 +.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Fall%202023-green + :alt: Approved for: Fall 2023 Visibility Reading ################## @@ -204,7 +204,7 @@ Perhaps that's a little dense. You may find it easier to remember this: Non-Visible Inherited Members ============================= -It's often possible to access access non-visible inherited members indirectly +It's often possible to access non-visible inherited members indirectly via a member that is visible. * For inherited variables, the child class might utilize a visible getter or setter. @@ -216,7 +216,7 @@ via a member that is visible. If we apply the second idea to constructors, then a child class constructor may be able to access non-visible inherited variables (e.g., to initialize them) using a call to a visible ``super()`` (or some overload of ``super``); this works really well when -the parent constructor initializes it's own declared instance variables. +the parent constructor initializes its own declared instance variables. This is considered **a common pattern** that exemplifies *separation of concerns* and *encapsulation* as each class is responsible for its own variables. diff --git a/visibility/private.rst b/visibility/public-and-private.rst similarity index 84% rename from visibility/private.rst rename to visibility/public-and-private.rst index 20cf583a..41e0f514 100644 --- a/visibility/private.rst +++ b/visibility/public-and-private.rst @@ -1,5 +1,5 @@ -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple - :alt: Approved for: Spring 2022 +.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Fall%202023-green + :alt: Approved for: Fall 2023 .. external links .. |jls11_access_control| replace:: The Java Language Specification (JLS) 11 Section 6.6 @@ -12,6 +12,33 @@ Visibility Reading |approval_notice| +Public Visibility +***************** + +Instead of saying that something has **public** visibility, we usually +just say that it's public. In Java, only top-level and member-level declarations +are allowed to be public. Things that are public are considered +to be the most visible; they are **always visible**. + +=============== ========== ============ =========== ========= +Visibility Visible From +--------------- ------------------------------------------------ +Name Same Class Same Package Child Class Elsewhere +=============== ========== ============ =========== ========= +public |Y| |Y| |Y| |Y| +=============== ========== ============ =========== ========= + +* In Java, the ``public`` modifier must be included in a declaration for + it to be considered public by the compiler. +* In UML, the ``+`` symbol is used just before a member's identifier to + illustrate that it's public. It is also common practice to assume + that a class in a UML class diagram is public if no visibility + symbol is included. +* The ``javadoc`` program includes public declarations in a + documentation website by default. If you want ``javadoc`` + to only include public declarations, then the ``-public`` + command-line argument can be used. + Private Visibility ****************** @@ -29,14 +56,14 @@ Name Same Class Same Package Child Class Elsewhere private |Y| |N| |N| |N| =============== ========== ============ =========== ========= -* In Java, the ``private`` modifier must be included in a member's declararion for +* In Java, the ``private`` modifier must be included in a member's declaration for it to be considered private by the compiler. * In UML, the ``-`` symbol is used just before a member's identifier to illustrate that it's private. * The ``javadoc`` program does not include private declarations in a documentation website by default; however, they can be included by adding the ``-private`` command-line argument (that option will - also include anything that is more visible than private -- so + also include anything that is more visible than private — so everything). Example 1 @@ -65,7 +92,7 @@ the same as ``this.checkAge``) declared within the same class. Although that method is private, it's visible from ``LINE1`` because private members are always visible from within the same class. A similar argument can be made for the code on ``LINE2``, -which attempts to access the private intance variable ``age``. +which attempts to access the private instance variable ``age``. Example 2 ========= @@ -109,7 +136,7 @@ to ``setAge`` on the next line (see the previous example for the inside of ``set We're not sure how the author of ``OtherClass`` knew about the ``checkAge`` method, but the error message lets them know that it's not for them to use. Had they referred to the Javadoc/API documentation for the ``Person`` class, it's unlikely that the private method -would have been included (private members are not included in the `javadoc` output by default). +would have been included (private members are not included in the ``javadoc`` output by default). If it's private, then it's not for others, and if it's not even listed in the documentation, then that's less stuff that other programmers need to understand before they're able to use your code. diff --git a/visibility/public.rst b/visibility/public.rst deleted file mode 100644 index 493f2892..00000000 --- a/visibility/public.rst +++ /dev/null @@ -1,55 +0,0 @@ -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple - :alt: Approved for: Spring 2022 - -Visibility Reading -################## - -|approval_notice| - -Public Visibility -***************** - -Instead of saying that something has **public** visibility, we usually -just say that it's public. In Java, only top-level and member-level declarations -are allowed to be public. Things that are public are considered -to be the most visible; they are **always visible**. - -=============== ========== ============ =========== ========= -Visibility Visible From ---------------- ------------------------------------------------ -Name Same Class Same Package Child Class Elsewhere -=============== ========== ============ =========== ========= -public |Y| |Y| |Y| |Y| -=============== ========== ============ =========== ========= - -* In Java, the ``public`` modifier must be included in a declararion for - it to be considered public by the compiler. -* In UML, the ``+`` symbol is used just before a member's identifier to - illustrate that it's public. It is also common practice to assume - that a class in a UML class diagram is public if no visibility - symbol is included. -* The ``javadoc`` program includes public declarations in a - documentation website by default. If you want ``javadoc`` - to only include public declarations, then the ``-public`` - command-line argument can be used. - -.. ############################################################################# - -.. util -.. |Y| unicode:: U+2713 -.. |N| unicode:: U+2717 - -.. copyright and license information -.. |copy| unicode:: U+000A9 .. COPYRIGHT SIGN -.. |copyright| replace:: Copyright |copy| Michael E. Cotterell, Bradley J. Barnes, and the University of Georgia. -.. |license| replace:: CC BY-NC-ND 4.0 -.. _license: http://creativecommons.org/licenses/by-nc-nd/4.0/ -.. |license_image| image:: https://img.shields.io/badge/License-CC%20BY--NC--ND%204.0-lightgrey.svg - :target: http://creativecommons.org/licenses/by-nc-nd/4.0/ -.. standard footer -.. footer:: |license_image| - - |copyright| This work is licensed under a |license|_ license to students - and the public. The content and opinions expressed on this Web page do not necessarily - reflect the views of nor are they endorsed by the University of Georgia or the University - System of Georgia. diff --git a/visibility/visibility.rst b/visibility/visibility.rst index 9ff0b888..6148840b 100644 --- a/visibility/visibility.rst +++ b/visibility/visibility.rst @@ -1,19 +1,17 @@ -.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Spring%202022-purple - :alt: Approved for: Spring 2022 +.. |approval_notice| image:: https://img.shields.io/badge/Approved%20for-Fall%202023-green + :alt: Approved for: Fall 2023 .. external links .. |uml_tutorial| replace:: UML Class Diagrams -.. _uml_tutorial: https://github.com/cs1302uga/cs1302-tutorials/blob/master/uml/uml.md +.. _uml_tutorial: https://github.com/cs1302uga/cs1302-tutorials/blob/alsi/uml/uml.md .. internal links -.. |reading_private| replace:: Private Visibility -.. _reading_private: private.rst +.. |reading_public_and_private| replace:: Public and Private Visibility +.. _reading_public_and_private: public-and-private.rst .. |reading_package| replace:: Package Private Visibility .. _reading_package: package-private.rst .. |reading_protected| replace:: Protected Visibility .. _reading_protected: protected.rst -.. |reading_public| replace:: Public Visibility -.. _reading_public: public.rst .. image:: img/in-progress.svg @@ -67,11 +65,11 @@ public ``public`` ``+`` |Y| |Y| interfaces. .. [2] A **member-level declaration** is any declaration of a class or interface member. - Members can include, where applicable, the constructors, methods, variables, constants, - etc. (both static or non-static/instance) of the class or interface; however, they - never includes Local-level declarations. + Members can include, where applicable, the constructors, methods, variables, and constants + (both static or non-static/instance) of a class or interface. However, they + never include local-level declarations. -.. [3] A **local-level declaration** is any variable declaration that is local, in +.. [3] A **local-level declaration** is any variable declaration that is local, or in scope, to a particular method. The local variables of a method include its parameter and any variables declared within the body of the method. @@ -89,7 +87,7 @@ public ``public`` ``+`` |Y| |Y| } // Person In this tutorial, we cover each available visibility option with a few examples, -often illustrated using a combination of `UML diagrams `__ and code +often illustrated using a combination of `UML diagrams `__ and code snippets. We will take some liberties when discussing examples involving multiple @@ -117,10 +115,10 @@ and help others to understand the important details of visibility. Individual Readings ******************* -* |reading_private|_ +* |reading_public_and_private|_ * |reading_package|_ * |reading_protected|_ -* |reading_public|_ + Summary of Visibilities ***********************