AP Computer Science A -- Unit 2

The information that we manage in a Java program is either represented as primitive data or as objects.


Introduction to Objects | Introduction to Primitive Data | Arithmetic Expressions & Data Conversions | Reference Data Types


Introduction to Objects

The information we manage in a Java program is either represented as primitive data or as objects. Objects are the building blocks of object-oriented programing. Software objects are conceptually similar to real-world objects in that objects consist of states and related behavior. An object stores its state in fields (such as variables) and exposes its behavior through methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation - a fundamental principle of object-oriented programming.

Practice: String Literals and Concatenation

Directions: Download the String Literals and Concatenation practice handout and write the output for the println methods. Hand the worksheet in or take a clear picture and upload to itsLearning textbox.

Exercise: Two Meanings of Plus

Directions: In Java, the symbol + can be used to add numbers or to concatenate strings. This exercise illustrates both uses. When using a string literal (a sequence of characters enclosed in double quotation marks) in Java the complete string must fit on one line. The following is NOT legal (it would result in a compile-time error). The solution is to break the long string up into two shorter strings that are joined using the concatenation operator (which is the + symbol). So, when working with strings the + symbol means to concatenate the strings (join them). BUT, when working with numbers the + means what it has always meant-add!

Download the Two Meanings of Plus exercise and complete. Write the answers to questions 1, 2 & 3 under C in the instructions (paste directly into the itsLearning textbox) and paste in your code from #2 as well as embed a screenshot from the BlueJ terminal window to the itsLearning textbox.


Introduction to Primitive Data

comparison table of primitive data typesJava has eight primitive data types. They have not changed much over time--there are six numeric primitives, one character primitive, and one logical primitive as shown in the picture on the right. These are the only types actually built into the programming language.

Assignment: Data Types Review

Directions: Review the different data types by completing the Data Types Review in itsLearning.


Variables

Java key concept

A variable is a simple data structure that allows the programmer to store a value in the computer. The programmer can retrieve or modify the variable at any time in the program.

Discussion: What is the Escape Sequence?

Directions: Explain what an Escape Sequence is and why it is necessary. Give an example of a line of code using an escape sequence but you cannot repeat the same line as another classmate.

Exercise: Names and Places

Java key conceptDirections: The goal in this exercise is to develop a program that will print out a list of student names together with other information for each. The tab character (an escape sequence) is helpful in getting the list to line up nicely. A program with only two names is in the file Names.java. Download the Names and Places directions and submit the code to the itsLearning textbox and a screenshot of your code from the BlueJ terminal window. Don't forget to update the comment at the top of the page with your name and the date.

Exercise: Student Grades

Directions: Write a Java program that prints a table with a list of at least 5 students together with their grades earned (lab points, bonus points, and the total) in the format shown in the Student Grades assignment sheet. Submit the code to the itsLearning textbox and a screenshot of your code from the BlueJ terminal window. Don't forget to update the comment at the top of the page with your name and the date.


Arithmetic Expressions & Data Conversions

Java's arithmetic operatorsJava does its calculations in program code called expressions. An expression is a combination of one or more operands and their operators and follow the order of operations similar to other forms of math. Expressions use operators to indicate what calculations to do and operands to provide information for the calculation.


Casting

Java is a strongly typed language, which means the type of a name is very important to how we use it. We can't mix most types, and for some that seem like we should be able to, we can't without telling Java that we really mean to. For example, I can't assign a double value to an integer variable without telling Java that is exactly what I want to do.

Java allows you to convert a value of one data type to another data type in a process called casting. There are two kinds of casting:

Assignment: Expressions Worksheet

Directions: You will be given declarations and asked to indicate the results of the presented expressions. You should review int division and casting. Make sure you correctly follow the order of operations. Make sure integer answers are indicated by having no decimal, and that floating point answers are indicated by having a decimal. For example, the values 0 and 0.0 are two different values.

Practice: Modulus Operator Worksheet

Directions: Complete the Modulus Operator worksheet located in itsLearning. Remember that any time the second operand is larger than the first operand in the expression, the modulus operator will return in the first operand.

Quiz: Expressions & Casting

Directions: Complete the Expressions & Casting quiz. This quiz will cover the concepts of expressions, order of operation, casting, and modulus.

Reference Data Types

Recall from the beginning of the unit that the information that we manage in a Java program is either represented as primitive data or as objects. In Java, everything that is not a primitive data type is an Object. The first type of object that we have seen so far is a String. Strings are made up of characters.

Java key conceptA reference variable does not contain its object's actual data in its memory location, since object sizes can vary. Instead, the variable contains the reference (also referred to as "memory address") of the object it refers to. After an object reference variable has been declared, it must be initialized before it can be used. For an object, initializing means we must make sure the variable refers to a valid object prior to using it.

We create an object with the new operator, and this is called instantiation. An object is an instance of a particular class. After the new operator creates the object, a constructor helps set it up. A constructor has the same name as the class and is like a method.

After an object has been instantiated, we use the dot operator to get its methods. The dot operator is added right after the object reference and is followed by the method being invoked. In the example below, we use the dot operator to separate the println method from the System.out object reference.

Example of using the dot operator

String Class Methods

There are a number of useful methods when working with Strings.

Creating Objects ~ Scanner, Math, & Wrapper Classes

high levelAn object reference variable stores the address where the object is stored in memory.

Scanner

The Scanner class allows us to create a scanner to allow input from the user. This will make it possible for the user to type information using the keyboard in order to interact with our programs.

To use the Scanner class, you will need to import it from the Java.util library.

To create a Scanner object, you will need this line of code:

Scanner scan = new Scanner (System.in);

The Scanner class has a number of methods that allow it to be useful. For example, if you wanted to accept anticipated input from the user as an interger, you might use this line (scan only needs to be declared and instiated one time in your program):

System.out.println("Enter an integer: ");
variableName = scan.nextInt();

The lines of code above, allow the user to enter a value (of whatever data type variableName is declared as and that value to be stored in the variable variableName. The .nextInt method allows us to receive and store an integer.

Wrapper Class

Each of the wrapper classes also has a toString() method that converts a value from a primitive type into a String object. Calling Integer.toString(999) will, for example, return the string "999".

Each of the numeric wrapper classes also has two useful constants that let us know the minimum and maximum values for that type. The constants have the names MAX_VALUE and MIN_VALUE. So Byte.MIN_VALUE would tell us the smallest type value, and Float.MAX_VALUE would tell us the largest float value.

Wrapper classes were one of the FRQ questions on the 2017 AP Test.

Lab: Working with Strings

Directions: Download the Working with Strings document and StringManips.java file. Follow the instructions to carefully study the Java application in BlueJ and then modify the file. When you are finished, copy and paste your code into the itsLearning textbox and embed a screenshot from BlueJ. Make sure you have updated the comment at the top of the code.

Assignment: Intro to Strings Worksheet

Directions: Complete the worksheet in itsLearning. Given the following variable declarations, evaluate each of the given expressions. Any whitespace shown in a String is a single space character, unless otherwise indicated. Remember that char values have single quotes around them: 'c' is a single primitive character, while Strings with double quotes around them: "C" is a String that happens to have only one character in it. There is a difference!

int a = 5, b = 12, i0 = 0, il = 1, i2 = 2, i3 = 3;

char c = 'u', d = ',';

String s1 = "Hello, world!", s2 = "I love Computer Science.";

Assignment: Question for Thought 2.1

Directions: Answer the following questions:

  1. How do you compute total square feet?
  2. How do you compute circumference?
  3. Research java.util.Scanner; What does it do and why do you need to use it?
  4. Define each primitive data type and give an example:

Lab: Painting a Room

Directions: Download the Painting a Room Lab. Follow the instructions on the lab sheet to create a program that will calculate the number of gallons of paint needed to paint a room. Submit your code as well as a screenshot from the BlueJ terminal window. Here is the Paint.java file for you to download. Do not remove the comments. They indicate where to put the code.

Lab: Area and Circumference of a Circle

Directions: Download the Area and Circumference of a Circle Lab. Follow the instructions on the lab sheet to create a program that will calculate the area and circumference of a circle. Submit your code as well as a screenshot from the BlueJ terminal window. Here is the Circle.java file for you to download. Do not remove any the comments. They indicate where to put the code.


The Math Class

Math.random( ) returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Each run should produce a different sequence of pseudo-random numbers.

Discussion: Random Method

Directions: Look through the AP Computer Science Quick Reference Guide for all of the places that the random method is used. Post your findings under the Discussions.

Assignment: Generating Random Numbers Worksheet

Directions: Download the Math.random instruction sheet and the Random Numbers Worksheet. Use the Math Random Instruction Sheet to complete the Math Random Methods Worksheet in itsLearning. For exercises 1 to 5, indicate the range of the possible result of each expression. For exercises 6 to 13, write an expression using the Math.random ( ) generates.

Complete the worksheet and submit your answers in itsLearning.

dice

Lab: Rolling Dice

Directions: Download the Rolling Dice Lab. Write a complete Java program that simulates the rolling of a pair of dice. For each die in the pair, the program should generate a random number between 1 and 6 (inclusive). It should print out the result of the roll for each die and the total roll (the sum of the two dice), all appropriately labeled. You must use the random method from the Math class. Submit your code as well as a screenshot from the BlueJ terminal window. Don't forget to update the comment at the top of the code with your name and date.

Assignment: Unit 2 Review Worksheet

Directions: Complete the Unit 2 review worksheet in itsLearning to review for the unit assessment.


Review

Flash Card Deck created by sarush with GoConqr

Resources

Introduction to Objects presentation

Introduction to Primitive Data types presentation

Variables presentation

Arithmetic Expressions & Data Conversion presentation

String Objects & Methods presentation

Classes, Libraries, & Packages presentation

The Math Class presentation


Sources

Primitive Data Types - Summary image: https://corejava25hours.com/category/java/

Autoboxing image: https://corejava25hours.com/category/java/