π1.1: Algorithms & Programming
Table of Contents
π This page is a condensed version of CSAwesome Topic 1.1
β΄β΄β΄ NEW UNIT/SECTION! β΄β΄β΄
Create a blank Java program to take your class notes in for the next few lessons.
Click on the collapsed heading below for GitHub instructions ‡
π NOTES PROGRAM SETUP INSTRUCTIONS
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository
- Specify the repository name:
CS2-Unit1PartA-Notes
- For the description, write:
Primitive data types, variables, printing output
- Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositories
section of GitHub! π - Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
and wait for the environment to load, then youβre ready to code! - π Take notes in this Codespace during class, writing code & comments along with the instructor.
π When class ends, donβt forget to SAVE YOUR WORK! Codespaces are TEMPORARY editing environments, so you need to COMMIT changes properly in order to update the main repository for your program.
There are multiple steps to saving in GitHub Codespaces:
- Navigate to the
Source Control
menu on the LEFT sidebar - Click the button on the LEFT menu
- Type a brief commit message at the top of the file that opens, for example:
updated Main.java
- Click the small
βοΈ
checkmark in the TOP RIGHT corner - Click the button on the LEFT menu
- Finally you can close your Codespace!
βοΈ What do Android phones, Minecraft, and Netflix have in common? Theyβre all coded in Java
! Many of the apps you use in an Android phone or tablet are written in Java. Netflix uses Java for some of its software too. Java is a programming language that is used worldwide to create software that we all use.
INTRODUCTORY ACTIVITY
- Form pairs, then pick a role:
- π£οΈ Instructor: Will give simple verbal instructions on how to draw some secret thing, without revealing what the thing is.
- βοΈ Drawer: Will follow the instructions to create the drawing exactly as the instructor describes.
- DRAWERS leave the room while INSTRUCTORS are told about the secret thing to draw.
- When the partner returns, move your chairs so you are sitting back-to-back with your teammate.
- If you are the DRAWER:
- Have a blank sheet of paper and a pencil or pen ready.
- You will not know what you are drawing.
- DO NOT ask any questions during the instructions!
- If you are the INSTRUCTOR:
- Give directions step-by-step, as detailed as possible.
- You can only describe shapes, sizes, and positions.
- DO NOT use any specific words for objects, body parts, comparisons, etc!!!
- Once the drawing is complete, hand it in, then move your chairs back to normal.
- π¬ As a group, go through each of the drawings and discuss:
- Was the drawing correct? Can you tell what it is?
- How precise did the instructions need to be?
- Did the order of the instructions matter?
- What problems came from vague language?
Algorithms
Algorithms define step-by-step processes in order to complete a specific task or solve a problem in a certain way. Algorithms are used in many areas of life, not just in computer science:
- A recipe is an algorithm for cooking a meal.
- A set of directions to a friendβs house is an algorithm for getting there.
Algorithms can be used to plan and design code by writing the steps down in English or another language or in a diagram or in pseudocode, which is writing simplified code on paper. Itβs important to plan the algorithm step by step where each step can be implemented by a line of code. Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.
Java Programs (Classes)
Every program in Java is written as a CLASS. Java is an object-oriented language, and classes and objects created from classes are the basic building blocks in object-oriented programming.
Inside the class, there can be a main method that starts the program.
- A method is a block of code that performs a specific task.
- In other programming languages, methods are called functions or procedures.
- The
main()
method is the entry point for the program.
Template for a simple Java program with a main()
method:
public class MyClass
{
public static void main(String[] args)
{
System.out.println("Hi there!");
}
}
Note: In Java every open curly brace
{
must have a matched close curly brace}
.
Compiling and Running Java Programs
An Integrated Development Environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile, and run code.
Computers donβt actually speak Java, so we have to compile (translate) our .java
source files into .class
files, which a computer can understand and run. A compiler checks your code for errors and translates it to executable code.
From the intro activity:
- The π£οΈ INSTRUCTOR represents the source code - all the statements we write in a
.java
file.- The βοΈ DRAWER represents the execution of a program.
- The way the drawer interprets the instructions is like the compiler.
Java Syntax Overview
Every programming language has its own syntax, which is like its βgrammarβ rules. Here are some of Javaβs most important rules:
- Single-line comment:
// comment
- Multi-line comment:
/* comment text */
-
Keywords are reserved words that have special meaning in Java. Keywords such as
public
,class
, andvoid
must be in lowercase, but class names such asSystem
andString
are capitalized. - Lines in a Java program that express a complete action must end with a semicolon (
;
). Such a line is called a statement.You can think of the semicolon (
;
) in Java like a period (.
) in English. The same way you use a period to end a sentence in English, you use a semicolon to end a statement in Java.
Note also that not every line of Java ends with a semicolon! If the line starts a block like an if
statement, there is no semicolon before the opening curly brace {
nor one after the closing }
.
Syntax Errors and Debugging
Syntax errors are reported by the compiler if your Java code is not correctly written. Syntax errors cause a programβs execution to STOP βπ, either before the program starts running or at a certain point during the run.
In contrast, a logic error would be an issue in a working algorithm or program that causes unexpected behavior.
Examples of common syntax errors:
- Missing semicolon
;
at the end of a statement - Missing closing curly brace
}
around a block - Missing closing quote
"
around aString
π Informally, a syntax error is called a bug, and the process of removing errors is called debugging.
An early computer science pioneer Grace Hopper documented a real bug, a moth that flew into a computer in 1947!
Compile-Time Errors
Example error message:
MyClass.java:5: error: unclosed string literal
System.out.println("Hi there!);
^
1 error
The filename, line number, error type, and caret
^
help locate the issue.
Error messages arenβt always 100% accurate about where the error actually is; sometimes you actually need to change something a bit earlier in the program and sometimes a bit later. But the line number is the best place to start looking.
After the line number, you will find the actual error type. These can be kind of cryptic at first, but they almost always contain some useful π clues, like in the example above:
unclosed string literal
- you may not know what a string literal is (yet) but βunclosedβ suggests something was opened and then not closed.- The caret (
^
) under the line of code is positioned to point at exactly where in the line the Java compiler thinks the problem is. In this case itβs pointing at the quotation mark (β
) before βHiββ¦
- Type out the code below exactly, run it, and look at the error message. Then fix it so it prints
Hi there!
.System.out.println("Hi there!);
- Repeat for this line of code, making sure to look at the error message before fixing it:
System.out.println("Hi there!";
- This version has TWO errors. Can you fix them?
system.out.println("Hi there!")
Run-Time Errors
Some errors cannot be detected by the compiler. These are called run-time errors. These errors occur while the program is running, after the code has been compiled.
They can be caused by a variety of things, such as dividing by zero or trying to read from a file that doesnβt exist or a logic error in the code.
β οΈ An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the programβs execution.
Type these two lines into your program and run it. What happens? Why?
System.out.println("It makes no sense to divide a number by zero!");
System.out.println(3/0);
Summary
-
(AP 1.1.A.1) Algorithms define step-by-step processes to follow when completing a task or solving a problem. These algorithms can be represented using written language or diagrams.
-
(AP 1.1.A.2) Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.
-
(AP 1.1.B.1) An Integrated Development Environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile, and run code.
- A basic Java program looks like the following:
public class MyClass { public static void main(String[] args) { System.out.println("Hi there!"); } }
-
A Java program starts with public class NameOfClass { }. If you are using your own files for your code, each class should be in a separate file that matches the class name inside it, for example NameOfClass.java.
-
Most Java classes have a main method that will be run automatically. It looks like this: public static void main(String[] args) { }.
-
The System.out.println() method displays information given inside the parentheses on the computer monitor.
-
Java statements end in
;
(semicolon).{ }
are used to enclose blocks of code.//
and/* */
are used for comments. -
(AP 1.1.B.2) A compiler translates Java code into a class file that can be run on your computer and checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.
-
(AP 1.1.C.1) A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler. Some things to check for are
;
at end of lines containing complete statements and matching{ }
,()
, and""
. -
(AP 1.1.C.2) A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
-
(AP 1.1.C.3) A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
- (AP 1.1.C.4) An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the programβs execution.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.