# Unit 1 - Primitive Types ## 1.1 Why Programming Why Java - [ ] Learn about the Java™ programming language and create your first Java program. - [ ] I will be able to write a basic java program - [ ] Learn some basic rules of Java programming by identifying and correcting errors in code. - [ ] I will be able to indentify basic syntax of a java program - [ ] Generate outputs to a console by calling System class methods. - [ ] Understand the difference between the `print()` method and the `println()` method. Java is an Object Oriented Program. Within every Java program begins with the creation of a class. Consider a class as a blueprint for your program. In this instance, we created a class called *MyFirstClass*. Within the class there is a main method that is required to execute the program. Below is a simple program that will print "Hello, World".  Notice that with every { , there is a corresponding } . You may hear me refer to it as a curly brace. A missing a curly brace is one of the most common errors among new programmers. The name 'public' allows users to be able to see the specific parts of your program. Notice also that the name of the class starts with a **capital letter**. The main class will always start with a capital letter. In Java there is a "main method" that is required for all java programs. The code will always be the same. It looks like: ```java public static void main(String args[]) ``` **`public`** is an access specifier. As you may infer, public is public and everyone will have access to it. **`static`** is a keyword in java. A `static` method belongs to the class and not to the object (We will learn more about this later!). A `static` method can **only** access static data. It is a method which belongs to the class and not to the instaniation of the object. There are differences between `static` nested class and `non-static` nested class. | | Static method | Non-static method | | ----- | ----- | ----- | | Definition | A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. | Every method in Java defaults to a non-static method without a static keyword preceding it. non-static methods can access any static method and static variable also, without using the object of the class. | | Accessing members and methods | In the static method, the method can only access only static data members and static methods of another class or the same class but cannot access non-static methods and variables. | In the non-static method, the method can access static data members and static methods as well as non-static members and methods of another class or the same class. | | Binding process | The static method uses compile-time or early binding. | The non-static method uses runtime or dynamic binding. | | Overriding | The static method cannot be overridden because of early binding. | The non-static method can be overridden because of runtime binding. | | Memory allocation| In the static method, less memory is used for execution because memory allocation happens only once because the static keyword fixed a particular memory for that method in ram. | In the non-static method, much memory is used for execution because here memory allocation happens when the method is invoked and the memory is allocated every time when the method is called. | **`void`** is also a keyword. It is a 'return type'. What does `void` return? Nothing! It is used to specify that a method **does not** return anything. If the main method is not void, it will return an error. **`main`** is the name of the Java main method. It identifies the starting point of a Java program. If we change the name while initiating the main method, it will return an error. **`String[] args`** It is an array of string type. It stores Java command-line arguments and is an array of type `java.lang.String` class. The name of the String array is `args`. It is not fixed and the user can use any name in place of it (It is not recommended as some IDEs will require args in the main method.). Notice that within the main method there is a print statement. Let's break down this print statement.
System.out.println("Hello, World");
- [ ] System is a class defined in the java lang package. - [ ] out is a public static field of the PrintStream type. - [ ] println() is invoked by the PrintStream class. - [ ] NOTE println() when executed will return to the next line. Whereas print() will execute the string literal but not return to the next line. You can also create a new line inside a print statement by adding \n anywhere inside the quotation marks of a print statement. ------------------------------------------------------------------------------------------------------------------- Take a look at the diagram below:  What observations can you make about the diagram? A powerful tool that you can use in OOP is the concept of `inheritance`. `Inheritance` is the concept where a Java Class can inherit properties from another class. You can think of this as a child inheritiing characteristics of a parent. Java refers to this as **extending** a class. The Class that is being extended or "inherited" is called a **superclass**. The class that extends or "inherits" is referred to as a **subclass**. We will explore this in more detail in Chapter 4.----------------------------------------------------------------------------
## 2.1 Instances of Classes - [ ] Explain the relationship between a class and an object - [ ] I will be able to create a poster demonstrating classes and objects As stated earlier, a *class* is a blueprint of an object. So we can also say that an *object* is an instance of a class. What we define as a class determines what objects that will be associated with the class and how things will operate within it. For example, we can define `human` as a class. We can assign attributes to that class like a nose, ears, eyes, hands, feet, etc. **NOTE:** Attribute and state are interchangable terms. We can also create a *method* that will call the attributes within a class. For example, we can create a method called running or sleeping. Now each of these methods will use an attribute or attributes of its class to perform something within the `human` class. If we create an instance of the `human` class, let say Object John , then John will have all the attributes (nose , ears, eyes, hands, legs) unique to it and will also have access to these methods to carry out basic functions. **NOTE:** Method and behavior are interchangable terms. The value of the attributes define the state of the object. What makes this efficient is that the class does not hold any space in the memory because we just create a definition. The moment we *instantiate* the class the object will require a dedicated space in memory. Thus we can say that a Class defines how the object should look and object is the actual representation of the same. ------------------------------------------------------------------------------------------- **Mr Potato Head Activity:** Supplies will be provide for you to complete this activity. Split into pairs. Each pair will create: a potato head character. a list describing what it is, what characteristics it has, and what it can do(actions). write PROPERTIES/ characteristics write METHODS/ actions What are the object oriented concepts to your Mr. Potato Head? Class: Object: Properties: Methods: Visually demonstrate the properties of inheritance by creating a subclass(es) of your Superclass. Include the Characteristics and actions of the subclass(es). ------------------------------------------------------------------------------------------- **Example:** ```java class Bicycle { // attribute or state int gear = 1; String color = white; // behavior or method public void pedaling() { System.out.println("Pedaling to accelerate!"); } } ``` **Sample Output** ```java My bicycle has 1 gear and is painted white! Pedaling to accelerate! ```----------------------------------------------------------------------------
## 5.3 Documentation with Comments - [ ] Understand how to properly comment code. - [ ] Implement precondition and postcondition commenting to summarize methods. - [ ] Use single-line comments to make code more readable and understand what tasks it performs. - [ ] I will practice industry standard commenting standards in my programs. Typing comments within your program is considered a professional practice, and I expect you to comment your code as appropriate throughtout the year. When other people read your program, they may not understand the purpose of the variables and/ or methods in your program. That's why it's important to document your code with comments. A comment is a piece of text that the computer will not recognize as code and will not execute. It's only there for the other programmers to read. While you can write whatever you want inside a comment, you should stick to explaining what your code does to document it properly. There are three ways in Java to create a comment: // Using these two slashes will create a single-line comment. /* Using the slash and an asterisk will create a multi-line comment for longer explanations. Be sure to close it with an asterisk, then a slash. */ /** Using the slash and two asterisks will create a Java API documentation comment. In these comments, you can use tags to specify the parameters of a method and the return values of the method. These comments aren't as important for the AP CSA curriculum. **/ @param -- explanation of parameter @return -- explanation of what the method returns Example of appropriate comments with a program: With **every** program that you submit, I want you to list the following: - your name/ partners name (if applicable) - the date of submission - Period - and the assignment Please follow the convention shown below. **Main() Block method** At the top of the file containing your program's main() block method, place an `external' block comment containing the following content. ``` /*============================================================================= | Assignment: Program #[n]: [Assignment Title] | Author: [Your Name ] | Partner: [Partner's Name ] | | Course Name: [Course Name] | Instructor: John Smith | Due Date: [Due Date and Time] | | Description: [Describe the program's goal, IN DETAIL.] | | Language: [ Java version 8] | Ex. Packages: [List names and sources of all external packages | required by this program.] | | Deficiencies: [If you know of any problems with the code, provide | details here, otherwise clearly state that you know | of no unsatisfied requirements and no logic errors.] *===========================================================================*/ ``` ### Practice 1.1.1  Create the happy face image above using the following criteria: - [ ] Create a class - [ ] Create a main method - [ ] Use System.out.print at least two lines - [ ] Use System.out.println at least three times----------------------------------------------------------------------------
### Assignment 1.4.2 **Average Test Score** Directions: Write two programs that will do the following: **Average Test Score** - [ ] ask the user for four test scores - [ ] calculate and show the result **Cashier Totals** - [ ] ask the user for the number of burgers sold and how much each one costs - [ ] ask the user for the number of fries sold and how much each costs - [ ] display the total items sold - [ ] display the total sales **Sample Output:** ``` Enter the first test score: 95 Enter the second test score: 87 Enter the third test score: 74 Enter the forth test score: 75 Average test score: 82.75% --------------------------------- Enter the number of burgers ordered: 10 Price of a burger: 5.65 Enter the number of fries ordered: 4 Price of fries: 1.95 Total Items Sold: 14 Total Sales: $64.3 ``` ## 1.5 Casting and Range of Variables - [ ] Evaluate arithmetic expressions that use manual and automatic casting. - [ ] Perform mathematical rounding. - [ ] I will be able to explain why a code segment will not compile or work as intended. There are some unique features to Java that help programmers create programs that are flexible in how they display data. We learned earlier that we need to declare a variable by it's type. It can be an `int` or a `double`. As you may remember, an `int` is any whole negative or positive number. A `double` is any number with a decimal. 1.0 is a whole number, but it has a decimal. So, Java considers 1.0 as a `double`. We can convert the `double` by declaring a new variable that changes the `double` to an `int`. ```java double temp = 98.6; int newTemp = (int)temp; ``` What is the value of newTemp? Did you guess 99? The actual value of newTemp is 98. The variable is not **rounded** it is *truncated*. Java does not round unless you tell it to round. ```java double a = 3.9; int b = (int) a; System.out.println(b); // b is 3 double c = -4.8; int d = (int) c; System.out.println(d); // d is -4 ``` In both cases, the digits to the right of the decimal are is just chopped off: > > To fix this, you can use `Math.round(x)` ***(we will get to this later, as a class)*** > or you can add .5 to correct the problem. > > > `double a = 3.9;` > > `int b = (int) a + .5;` > > `System.out.println(b); // b is 4` > > `double c = -4.8;` > > `int d = (int) c + .5;` > > `System.out.println(d); // d is -5` > You will need to be familiar with some terms: - [ ] **widening** - converting from a smaller data type (int) to a larger data type (double). - [ ] `byte` -> `short` -> `char` -> `int` -> `long` -> `float` -> `double` - [ ] **narrowing** - converting a larger data type (double) to a smaller data type (int). - [ ] `double` -> `float` -> `long` -> `int` -> `char` -> `short` -> `byte` In this instance, we 'narrowed' the value of temp. There is another term that you need to be familiar with and it is called **casting**. Casting is converting from one data type to another, such as from a *double* to an *int*, potentially losing data. Take a look at this program: ```java public class CastingEggs { public static void main(String args[]) { int eggs = 9; int dozen = 12;// the variable dozen will not change System.out.println("Total eggs = " + eggs/dozen + " dozen"); System.out.println("Total eggs = " + eggs/ (double)dozen + " dozen"); System.out.println("Total eggs = " + (double)eggs/ dozen + " dozen"); // Example output: // Total eggs = 0 dozen // Total eggs = 0.75 dozen // Total eggs = 0.75 dozen ``` We know that we don't have 0 eggs. We can rewrite our program to show how many eggs we have in decimal form. ### Assignment 1.5.1 You will explore the PlanetTravel program called FivePlanetTravel. The program is set up to plan a five-planet tour!: ``` /* * Activity 1.1.5 */ public class FivePlanetTravel { public static void main(String[] args) { // theplanets.org average distance from earth to the planets int mercury = 56974146; int venus = 25724767; int mars = 48678219; int jupiter = 390674710; int saturn = 792248270; // number of planets to visit int numPlanets = 5; // speed of light and our speed int lightSpeed = 670616629; lightSpeed /= 10; // total travel time double total = 0; /* your code here */ System.out.println("Travel time to ..."); System.out.println("Mars: " + mars / (double) lightSpeed + " hours"); total += mars / (double) lightSpeed; int average = (int)(total / numPlanets); System.out.println("Total travel time:" + total); System.out.println("Average travel time: " + average); } } ``` **Example Output:** ```java Travel time to ... Mercury 0 hours Venus: 0 hours Mars: 0 hours Jupiter: 5 hours Saturn:11 hours Total travel time:16.0 Travel time to ... Mercury: 0.8495784968765016 hours Venus: 0.38359870949813324 hours Mars: 0.7258725410056196 hours Jupiter: 5.825604352006665 hours Saturn: 11.813728535388819 hours Total travel time:19.59838263477574 Average travel time: approximatley 4 hours. ``` *Your output should look similar to the example above.* You will write a widening algorithm that will show the travel time to and from all planets. You will write a casting version without new variables to show the travel times. The one rule is that you must use the provided code and not change any provided data types. ### Numbers Riddle Project - [ ] Apply coding concepts you have learned up to this point. - [ ] Apply a programming development process to create your first project. - [ ] Capture your project and communicate how each part of your program works. - [ ] I will demonstrate my understanding of a Unit 1 by writing a program In this project, you will write a program that incorporates the Java™ concepts you have learned throughout this unit. Your program will include: - [ ] Use of the [camelCase](https://betterprogramming.pub/string-case-styles-camel-pascal-snake-and-kebab-case-981407998841) naming convention - [ ] Both multiline and inline comments -- **see below** - [ ] The print and printtln methods - [ ] Variables (appropriately named) - [ ] Arithmetic expressions - [ ] The compound assignment operator - [ ] Conversion between int and double data types **The Numbers Riddle**Choose any integer, double it, add six, divide it in half, and subtract the number you started with. The answer is always three!
**Example:** ```java x = 3 // choose an integer x = 3 * 2 // double it x = 6 + 6 // add six x = 12 / 2 // divide it in half x = 6 - 3 // subtract the number you started with x = 3 // answer is always three! ``` **Important:** No shortcuts! You know the answer to the riddle will always be three, but your program is being used to test and validate the riddle. You should print the result of all calculations, not just “3.” **Requirements of this project** Your program should allow any number to be stored in a variable and printed out. Then, the program should output its double, output six added to it, output that number divided in half, and, finally, output that number subtracted by the original number. In this way, the program displays each calculation, and of course, the final result of three. Looking back at previous programs and the requirements stated above, you know you will need: - [ ] a class definition header that matches the file name - [ ] the main method of the program - [ ] a variable defined as the “starting number you choose” - [ ] You may use a `scanner` class - [ ] an algorithm(s) that processes the chosen number - [ ] a print statement displaying the number you chose - [ ] a print statement displaying each calculation and the final result - [ ] comments in your code - [ ] use of camelCase when appropriate **Test Cases** Create variables and choose numbers that match the following number types to verify your program works for each. - [ ] Positive Integer - [ ] Negative Integer - [ ] Zero - [ ] Positive Double - [ ] Negative Double **Document the output and submit your program as a java file.**