AP Computer Science A Ultimate Guide (copy)

# Primitive Types

## **The Basics**

* Commenting, or using comments is your best friend. It’s a very effective tool, and it’s a good idea to get into the habit of commenting.
* It allows programmers to make “notes” in the program so they can reference them later.
* Other people viewing your code won’t have trouble interpreting it.
* __**Types of commenting:**__
* **In-line/short comments-** They appear after or near a statement and are followed by 2 forward slashes.
* **Ex:**

```java
//this is a short comment
```

* **Long comments-** They go beyond more than one line of code that is surrounded by special characters; they begin with (/*) and end off with (/*).
* **Ex:**

```java
/* this is a
long comment*/
```

## **Identifiers:**

* Identifiers are names that are given to show data that are stored in the memory of a computer when a program is being executed in a computer.
* \*\***Java is special because it lets the program name the identifier based on its role.**
* The guidelines below are guidelines to make it easier on us when coding, and its rules that Collegeboard expects us to follow.
* An identifier needs to have a combination of letters, numbers, and underscores(_). However, they must begin with a letter, and can’t have other characters listed.
* This includes spaces!!
* An identifier should be named logically, and it should correspond to the data that it is holding.
* An identifier should begin with a lowercase letter, and if there are several words used to name the identifier, then the words after the first should be capitalized.
* **Ex:** `numOfSides, or testScores`
* White space- It doesn’t affect the functionality of the program. It just makes the code easily readable, because it lets the programmer space out code to separate statements or tasks.

## **Compiling and Errors:**

* **Remember that when a programmer writes in Java, these lines of code are understood by a Java development environment.**
* **An interpreter is used to change this code into binary(zeros and ones) which is what the computer understands.**
* This process is called compiling.
* We use IDEs to write out code, or interactive development environments.
* The code will be checked for programming errors.
* If any sort of errors are found, then the code stops compiling, and an error message appears.
* This would be a compile-time error.  The computer is unable to compile or understand what the code is trying to do, which is why it’s unable to execute properly.
* **Logical error**- This is based on the logic of the code. The way that the code is structured, is incorrect.
* **Run-time error**- A compiler doesn’t catch this error. It just causes an error with the execution of the program.

## **Outputs and Inputs:**

* There are 2 ways to produce an output on the screen:
* Using `System.out.print;`
* Using `System.out.println;`
* What’s the difference?
* The print() returns the cursor to the same line after it’s done executing. The println() statement moves the cursor to the next line.
* There are different ways you would print out specific types of outputs.
* **Ex**:

```java
System.out.println(“Quotes are used because a string is being printed. Otherwise it will simply print whatever is put in the brackets.”);
```

\
* If you want to put a line break in a piece of code just use *\n.*
* **Ex**:

```java
System.out.print(“The first line\nThe second line”)
```

## **Variables and Assignment:**

* To create an identifier we need to assign a value to the identifier.
* **Note:** `type identifier = data;`
* **Ex**: `int side1 = 2;`
* This specifically tells the compiler that the identifier is *side1,* and the value that’s being assigned to it is 2. The data has the integer type.
* **Note**: The equal sign, is an assignment operator, and is very important to have!!
* **Note**: The semicolon’s that we have at the end of each statement mean that the specific statement is completed.
* Assignment statements DON’T print anything out as output!
* Whenever data is associated with an identifier, it’s referred to as a variable.
* **Ex**:

```java
int myFavoriteNumber = 22;
myFavoriteNumber = 78;
System.out.print(“My favorite number is “ + myFavoriteNumber);
```

__Output__: My favorite number is 78

* ==Important things to remember:==
* Once a variable is assigned a given type, it can’t be changed.
* The quotation is used so that it specifies what sentence to print out, and what variable value to print out.
* Use concatenation, when you want to combine variables of 2 different types. - The plus sign is used for this, just like in the example above.

## **The 4 Data Types:**

* **Primitive Data- The basic type of data.**
* **Integer**(int)**- It represents any number that is an integer. So all positive and negative numbers and zero. Integers can’t store decimals!!**
* **Double**(double)**- A number that can be positive, negative, or zero, and it can be a fraction or decimal.**
* \*\*Boolean(\*\****boolean)-*** **A value that is either true or false. True = 1, False = 0 in machine code.**
* \*\*Character(\*\****char)-*** **It represents a single character that can be represented on a computer. It includes any character that you type on the keyboard. All the way from letters, numbers, spaces, and special characters.** ***char*** **values are stored with the use of single quotation marks or an apostrophe.**

## **Arithmetic Operators:**

* **Note**: *The different operators that are used in Java are the +. - , ,/, and %.*
* **The plus sign is used for addition.**
* **Ex:**

```java
sumOfSides = side2 + side3;
```

* **The subtraction sign is used for subtraction.**
* **Ex:**

```java
differenceOfSides = side1 - side3;
```

* **The asterisk or the star is used for multiplication.**
* **Ex:**

```java
side1 * side2 = productSide;
```

* **The slash, or (/) is used for division.**
* **Ex:**

```java
side3/side2 = quotientSide;
```

* **The percent sign, (%), is called a modulus operator. It does the division of the numbers, and it returns the remainder.**
* **Ex:**

```java
sumOfSides % differenceOfSides;
```

* Just like in normal math, Java also follows an order in which it conducts its operations.
* Java performs multiplication and division operators, as well as modulus from left to right, then it does addition and subtraction in the same order.
* If you want to change the order that the operation occurs, just use parentheses to separate the expression out.
* Java likes to do something special with some of its integers. Say that you are dividing 3/2 in reality the answer is actually 1.5, but Java truncates the 0.5 off. It will display the answer as 1, because it was described as in integer type, not a double.
* Negative numbers also work out the same way.
* The only way to get over this portable is with casting.
* **Casting-** A process in which data is forced to look like another type of data to the compiler.

```java
System.out.print(3 - (double) (4)/5);
System.out.print( 3 - 4/(double)5);
```

* Both of the examples are the proper way to do casting so that it produces the desired result.
* **Note:** In the order of operations in Java, casting will be done first because it has higher precedence.
* ==Other operators:==
* Increment operator(*++)*- This increases the value of a number by one. It’s just a shorthand of the addition operator that can sometimes be used.
* Ex: `x++;` is the same as `x = x+1;`
* Decrement operator(- -)- This decreases the value of a number by one.
* Ex: `x- - ;` is the same as `x = x -1;`
* Other Shortcut Commands:

| __**Shortcut Command**__ | __**Equivalent Command**__ |
|----|----|
| `a += b` | `a = a + b` |
| `a -= b` | `a = a - b` |
| `a *= b` | `a = a * b` |
| `a /= b` | `a = a/b` |
| `a %= b` | `a = a % b` |

## Using Classes and Objects

## **Objects and Classes Overview**

* **Object- A data type that is created in Java.**
* There is a class that is used to build more objects in Java specifically.
* Classes have instance fields or data that belong to objects and methods that are used to help change the data.

## ***Math Class***

* ***This store's common numbers used in mathematical calculations and methods to have mathematical functions.***
* *These methods are static.*
* ***Note***: Static methods, belong to a class, but it doesn’t belong to any instances of that specific class. This type of method can be called without the class's instance or object.\*
* *We don’t need to create the objects in this class.*
* ***Here are the main ones used on the AP Exam:***
* ***Ex: Say you want to calculate the amount of candy each person gets amongst your group of 5 friends. You have 14 chocolates, and you didn’t feel like doing the math so you decide on using your amazing IDE to help you out. What line of code would best fit your needs?***

```java
a. Math.abs(14/5);

b.Math.pow(14,5);

c. double chocAmount = 14.0/5.0;

//chose between these 3 options
```

__Answer__: C would be the only option that fits your needs because you don’t want an absolute value for your number of chocolates. It has to be accurate, and you don’t need exponents either. You just want to find out how to split the chocolate amount. So, this would be your answer.

## ***String Class***

* *A string is also an object data type, which means it has a class with many methods that describe the behavior of an object.*
* ***Here are some commonly used methods for the AP Exam:***
* ***Ex: Consider the following code segment, What will be the value of n?***

```java
String s = “This is the beginning”;

String t = s.substring(5);

int n = t.indexOf(“the”);
```

__Answer__: The value of n will be 3. The question is asking for the value of n, which is the indexOf “the” in String t, which is essentially just a substring of string s. Determine t first, which is the substring that begins at the index 5 of s. Start at 0 and count the spaces as different characters. Index 5 is the letter i, at the beginning of the word is. Since string t is a substring of s, the sentence for this substring would be “is the beginning”. the index of “the” is 3 because it begins at index 3.

* There are a lot more methods that are in the *String* class. However, these are just the main ones.
* **Remember that the data in the String class is just an array of characters. This means that String’s have similar functions to arrays.**
* *IndexOutOfBoundsException’s occur when the index that you use in any of the methods above goes beyond the index of the String.*
* The String class is an **immutable class.** This means that if you would like to change the values or content of a String object the new contents need to be rearranged to help find the variable.
* **Note**: When using methods found in any class, you should remember that parameters that are used to call the method need to match the data types of the arguments that are found in that specific method.
* Make sure that parameters match the correct data types so there are no issues with the execution of the code.

\
\
# Using Classes and Objects

## **Objects and Classes Overview**

* **Object- A data type that is created in Java.**
* There is a class that is used to build more objects in Java specifically.
* Classes have instance fields or data that belong to objects and methods that are used to help change the data.

## ***Math Class***

* ***This store's common numbers used in mathematical calculations and methods to have mathematical functions.***
* *These methods are static.*
* ***Note***: Static methods, belong to a class, but it doesn’t belong to any instances of that specific class. This type of method can be called without the class's instance or object.\*
* *We don’t need to create the objects in this class.*
* ***Here are the main ones used on the AP Exam:***
* ***Ex: Say you want to calculate the amount of candy each person gets amongst your group of 5 friends. You have 14 chocolates, and you didn’t feel like doing the math so you decide on using your amazing IDE to help you out. What line of code would best fit your needs?***

```java
a. Math.abs(14/5);

b.Math.pow(14,5);

c. double chocAmount = 14.0/5.0;

//chose between these 3 options
```

__Answer__: C would be the only option that fits your needs because you don’t want an absolute value for your number of chocolates. It has to be accurate, and you don’t need exponents either. You just want to find out how to split the chocolate amount. So, this would be your answer.

## ***String Class***

* *A string is also an object data type, which means it has a class with many methods that describe the behavior of an object.*
* ***Here are some commonly used methods for the AP Exam:***
* ***Ex: Consider the following code segment, What will be the value of n?***

```java
String s = “This is the beginning”;

String t = s.substring(5);

int n = t.indexOf(“the”);
```

__Answer__: The value of n will be 3. The question is asking for the value of n, which is the indexOf “the” in String t, which is essentially just a substring of string s. Determine t first, which is the substring that begins at the index 5 of s. Start at 0 and count the spaces as different characters. Index 5 is the letter i, at the beginning of the word is. Since string t is a substring of s, the sentence for this substring would be “is the beginning”. the index of “the” is 3 because it begins at index 3.

* There are a lot more methods that are in the *String* class. However, these are just the main ones.
* **Remember that the data in the String class is just an array of characters. This means that String’s have similar functions to arrays.**
* *IndexOutOfBoundsException’s occur when the index that you use in any of the methods above goes beyond the index of the String.*
* The String class is an **immutable class.** This means that if you would like to change the values or content of a String object the new contents need to be rearranged to help find the variable.
* **Note**: When using methods found in any class, you should remember that parameters that are used to call the method need to match the data types of the arguments that are found in that specific method.
* Make sure that parameters match the correct data types so there are no issues with the execution of the code.

# Boolean Expressions and If Statements

## **If Statements**

* An *if* statement is just like it sounds. It’s a conditional statement that is used in Java to help control the flow of the program.
* For example, your parents tell you, you can only watch a movie __if__ you finish cleaning your room.
* Cleaning your room is the condition for you to be able to watch the movie.
* You won't get to go if you don’t clean your room.
* The else statement in the example below is used for what results to produce when the if condition isn’t being satisfied.
* Ex:

```java
int num1 = 4, num2 = 5;

if( num1 == num2)

System.out.print(“The numbers are the same.”);

else

System.out.print(“The numbers aren’t the same”);
```

* **Note**: The boolean operator( ==), isn’t the same as the assignment operator(=).
* A boolean operator asks a question, while an assignment operator executes a command. The boolean operator in this example determines if *num1* is equal to *num2.*
* The assignment statement doesn’t produce other results.

## Boolean Expressions
* **Values that can be compared using boolean statements:**
* `==`**(equal)**
* `!=`**(not equal)**
* `
robot