AP Computer Science A

Similar documents
CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Full file at

Chapter 2: Data and Expressions

A variable is a name for a location in memory A variable must be declared

Chapter 2: Data and Expressions

ECE 122 Engineering Problem Solving with Java

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

CS313D: ADVANCED PROGRAMMING LANGUAGE

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Using Java Classes Fall 2018 Margaret Reid-Miller

Computational Expression

Chapter. Let's explore some other fundamental programming concepts

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Programming with Java

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Chapter 2 Primitive Data Types and Operations. Objectives

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

Lecture Set 2: Starting Java

Program Fundamentals

Chapter 2: Data and Expressions

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Lecture Set 2: Starting Java

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Program Elements -- Introduction

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Computational Expression

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

COMP Primitive and Class Types. Yi Hong May 14, 2015

Visual C# Instructor s Manual Table of Contents

Basic Computation. Chapter 2

Data Conversion & Scanner Class

Chapter 2 ELEMENTARY PROGRAMMING

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Basic Computation. Chapter 2

2: Basics of Java Programming

4 Programming Fundamentals. Introduction to Programming 1 1

Introduction to Java & Fundamental Data Types

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

CS 302: Introduction to Programming

Chapter 2 Elementary Programming

Ex: If you use a program to record sales, you will want to remember data:

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

c) And last but not least, there are javadoc comments. See Weiss.

AP Computer Science Unit 1. Programs

CS 106 Introduction to Computer Science I

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

What did we talk about last time? Examples switch statements

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

DATA TYPES AND EXPRESSIONS

Mr. Monroe s Guide to Mastering Java Syntax

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

Basics of Java Programming

We now start exploring some key elements of the Java programming language and ways of performing I/O

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Unit 4: Classes and Objects Notes

Declaration and Memory

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Full file at

Course Outline. Introduction to java

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Section 2: Introduction to Java. Historical note

Homework Set 1- Fundamentals

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

CMPT 125: Lecture 3 Data and Expressions

JAVA Programming Fundamentals

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Zheng-Liang Lu Java Programming 45 / 79

Object-Oriented Programming

First Java Program - Output to the Screen

double float char In a method: final typename variablename = expression ;

Basics of Java Programming variables, assignment, and input

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Primitive Data Types: Intro

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Language Reference Manual

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

CIS 110: Introduction to Computer Programming

Week 6: Review. Java is Case Sensitive

JAVA Programming Concepts

Chapter 2. Elementary Programming

Transcription:

AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive and Reference Variables Key words / Reserved words Naming Conventions Comments Assignment and Operands Date: 9/11/2017 Aim: Method Declarations Date: 9/14/2017 Aim: Calling Methods Date : 10/2/2017 Aim : Loops ( for ) & Decisions ( if ) for statement: if-then-else statement: Modulo operator (%): Relational Operators: Increment and Decrement: Error Types: Syntax and Logical Date : 10/12/2017 Aim : String Operations String Operations: Escape Sequences: Date: 10/17/2017 Aim: Math & Numbers (lesson 4) Multiple declarations The assignment operator Fundamental arithmetic operations PEMDAS Increment & Decrement Compound Operators Integer Division Truncation Date: 10/19/2017 Aim: Numbers: Mixed Data Types, Casting, and Constants (lesson 5) Mixed data types Casting Constants

Date: 10/25/2017 Aim: Boolean Operators (lesson 8) & Keyboard Input (lesson 7) Boolean Operators: Keyboard Input: String equality: Date: 10/30/2017 Aim: Switch & While (lessons 10 & 12) if versus switch Another if versus switch for versus while while versus do-while Compound Control Expressions More fun stuff Math.random( ); return; if (word.equalsignorecase( hello ))... char letter = word.charat(1); // returns e int offset = word.indexof( e ); // returns 1 int offset = word.tolowerc ase().indexof( h ); // returns 0 (zero) More java string methods: https://www.javatpoint.com/java-string

Date : 9/8/2017 Aim : Java Basics Why Java? Java is platform independent - it runs on any computer with a Java interpreter. Almost every browser includes a Java interpreter; therefore almost every computer can interpret Java code. MyProgram.java MyProgram.class My Program (Source code) (Java byte code) (Runs) Objects and Classes All code is written inside Classes We can create a penguin class Classes create Objects We can create penguins named Blackbeard, Bruce, Einstein, Gandhi, and Lindsey. These are all unique objects of the same class. Objects have Properties and Behaviors Properties define what the object has : hat, coat, beard, glasses, shoes, age, etc. Behaviors define what the object does : talk, write, ski, work, etc. Data types: Primitive and Reference Eight primitive data types exist as part of the Java language (we ll use the boldface data types): boolean - true or false byte - integer, 8 bits of storage char - single Unicode character short - integer, 16 bits int - integer, 32 bits long - integer, 64 bits float - decimal, 32 bits double - decimal, 64 bits Reference data types are user-defined classes created using primitive data types Many are available from the Java API library for general use Examples: String Scanner Random Math

Variables A Variable is a space in memory that stores a data value of a particular data type. Variables are used to store information which the program needs to do its job. Data types may be defined as a primitive type ( int ), or as an object type ( String ). Examples: boolean hat = false; String job = Scientist ; // double quotes char gender = f ; // single quotes Penguin huey = new Penguin( ); Key words / Reserved words These are words that mean something in Java, and they cannot be used to name anything else. Examples: boolean case class public for do Naming Conventions Naming conventions are not important to Java; they are important to programmers. Class names begin with Uppercase letters Method names begin with lowercase letters Variable names begin with lowercase letters All names MUST be descriptive and can be a combination of two or more words: the words are joined, but the start of each new word is uppercase (ie- typeofcar ) Java is CASE SENSITIVE ( cat!= Cat ) Comments Three types of comments: Single line: // comment, explanation, etc. Multiple line: /* * comment, etc */ JavaDoc (for Documentation Generator): /** * @param hat the type of hat */

Assignment and Operands Variables are assigned values using a SINGLE equal sign. char myinitial = W ; String thisschool = CMHS ; double addhalf +=.5; // same as addhalf = addhalf +.5; The right side is evaluated first, and the resulting value is stored in the variable. Operands: + - * / % (addition, subtraction, multiplication, division, modulo) Date : 9/11/2017 Aim : Method Declarations The method declaration requires modifier (public or private) return type name a pair of parentheses ( ) a body between braces { } public int addtwonumbers (int a, int b) { return a + b; } Date : 9/14/2017 Aim : Calling Methods p1.getname(); vs. getname();

Date : 10/2/2017 Aim : Loops ( for ) & Decisions ( if ) for loop: Repeats the statement(s) while a given condition is true. if statement: executes a section of code only if a test evaluates to true. else statement: a secondary path when an "if" clause evaluates to false for statement: // initialize the loop control variable for (initialization; BooleanExpression; update) { // Statements } // i is the loop control variable for (int i=0; i < 3; i++) { System.out.println(i); } Program Trace i i < 3 result 0 true 0 1 true 1 2 true 2 3 false if-then-else statement: if (condition) { // statements else if (condition) { // statements else if (condition) { // statements else { // statements if (grade==100) { letter = A+ else if (grade>=90) { letter = A ; else if (grade>=80) { letter = B ; else { // grade < 80 letter = C ; Modulo operator (%): Returns the remainder of two numbers: 1 R 2 12 % 10 = 2 10 )12-10 2 Often used to determine if a number is odd or even (if the number % 2 is 0 it s even) Relational Operators: < > <= >= ==!= Note: Equality contains TWO equal signs Not is always represented with an exclamation point

Increment and Decrement: Increment: add 1 long way: i = i + 1; abbreviated: ++i; i++; Decrement: subtract 1 long way: i = i - 1; abbreviated: --i; i--; Error Types: Syntax and Logical Syntax errors: Program won t compile due to errors with spelling, punctuation, etc. Logical errors: Program compiles but doesn t do what you want it to? Which one is harder to debug? Date : 10/12/2017 Aim : String Operations String Operations: Concatenation : Put one string at the end of another String x = hello + there ; Length : returns the # of characters in a string int c = s1.length( ); touppercase : s2 = s1.touppercase(); tolowercase : s3 = s1.tolowercase(); Substring: Extract a subset of a String: beginning at the OFFSET specified String s1 = Good Morning! ; // G o o d M o r n i n g // 0 1 2 3 4 5 6 7 8 9 10 11 String sub1 = s1.substring(3); // sub1 contains d Morning! beginning at the offset (inclusive), ending at the offset (exclusive) String sub2 = s1.substring(3,7); // 3,4,5,6 // sub2 contains d Mo Escape Sequences: Allows inclusion of special characters in a String String str = Say \ Hi\ to him. ; // str will contain: Say Hi to him. Sequence Inserts a \t tab \n new line \" double quote \\ backslash

Date : 10/17/2017 Aim : Math & Numbers (lesson 4) Multiple declarations It s possible to declare and / or initialize multiple variables in one statement: double x = 31.2, m, p = 43.917; int i, j = 2, k; note: declare vs. initialize The assignment operator Equal Sign = Fundamental arithmetic operations Addition + Subtraction - Multiplication * Division / Modulo % PEMDAS ( ) exponent * / + - Increment & Decrement ++i Increment i, then use it i++ Use i, then increment it --i Decrement i, then use it i -- Use i, then decrement it System.out.println(i++); System.out.println(++i); Compound Operators Compound Operator Example Meaning += x += 3; x = x + 3; -= x -= y - 2; x = x - (y - 2); *= z *= 46; z = z * 46; /= p /= x-z; p = p / (x - z); %= j %= 2 j = j % 2; Integer Division Truncation When dividing two integers, the fractional part is truncated (thrown away): int x = 5; int y = 2; int z = x / y; // the answer is 2

Date : 10/19/2017 Aim : Numbers: Mixed Data Types, Casting, and Constants (lesson 5) Mixed data types: Calculations with double and int Casting: Forcing a variable to a new type Constants: A variable s value CANNOT change Mixed data types Calculations with double and int Java does not like to lose data. It will always want to store a result in the most precise data type involved. If it can t it will give an error: double d = 29.78; int i = d; // error, data loss int p = 20 + 5 * 6.0; //error int j = 29; double k = j; // ok, no data loss Casting Forcing one data type into another double d = 29.78; int ii = (int) d; // forcing d into an int The casting only applies to the number, variable, or parenthetical expression that immediately follows the cast. double d = (double)5 / 4; // 1.25 double e = (double)(5 / 4); //1.0 Remember that when a calculation has numbers that are different data types the result will be the more precise: int m = 4 / 2 * 1.0; // error Constants Variables whose values will not change final double PI = 3.1415927; PI = 72.0; // error The word final is used The variable name is all UPPERCASE Can be created for any data type final String NAME = Mercy ; final int SECTIONS = 8;

Date : 10/25/2017 Aim : Boolean Operators (lesson 8) & Keyboard Input (lesson 7) Boolean Operators: == equal > greater than!= not equal >= greater / equal < less than && and <= less / equal or! not -- applied to boolean variables -- ex: if (!a == b) Truth tables How && ( and ) and ( or ) work with combinations of a and b: a b (a && b) a b (a b) false false false false false false false true false false true true true false false true false true true true true true true true Keyboard Input: 1 - Import the Java io and utility libraries import java.io.*; import java.util.*; 2 - Declare an object to associate with the keyboard - a Scanner object - and give it a name Scanner kb = new Scanner(System.in); 3 - Use the Scanner methods String input = kb.nextline(); Create an object: Scanner kb = new Scanner(System.in); Methods in the Scanner class String equality: nextint(); nextdouble(); next(); nextline(); // kb.nextint(); // kb.nextdouble(); // kb.next(); // kb.nextline(); When comparing two String objects you CANNOT use the == comparator You must use String s equals method: String fruit_1 = apple ; String fruit_2 = cantaloupe ; if (fruit_1.equals(fruit_2)) System.out.println( same ); if (!fruit_1.equals(fruit_2)) System.out.println( different );

Date: 10/30/2017 Aim: Switch & While (lessons 10 & 12) The switch statement is an alternative to the if-then-else decision statement. It is easier to read and write. The while and do-while statements are an alternative to the for loop statement. All 3 are loops but each is used for a different purpose. if versus switch String todo; //------- more code -------- if (todo.equals( + )) { answer = a + b; else if (todo.equals( - )) { answer = a - b; else if (todo.equals( x )) { answer = a * b; else { // division answer = a / b; String todo; //---- more code ----- switch (todo) { case + : answer = a + b; break; case - : answer = a - b; break; case x : answer = a * b; break; default: answer = a / b; } Another if versus switch if (num <= 3) { answer = low ; } else if (num <=6 ) { answer = middle ; } else answer = top ; switch (num) { case 1: case 2: case 3: answer = low ; break; case 4: case 5: case 6: answer = middle ; break; default: answer = top ;

for versus while for (int i=1; i <=10; i++) { System.out.println(i); // versus: Scanner kb = new Scanner (System.in); boolean done = false; String answer; // control expression: i <=10; while (!done) { // control expression:!done System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); while versus do-while while (!done) { // control expression before the loop System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); // versus: do { System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); while (!done); // control expression after Compound Control Expressions int loops = 0; while (!done && loops <= 3 ) { System.out.println( Finished? (yes or no) ); answer = kb.nextline(); done = (answer.equals( yes )); loops++;

Math.random( ); More fun stuff Returns a number between 0 (inclusive) and 1 (exclusive) If you want a random number within a range, multiply the result by the high end of the range Math.random( ) * 5; // returns a number between 0 (inclusive) and 5 (exclusive) return; Exits the program String word = Hello ; if (word.equalsignorecase( hello ))... char letter = word.charat(1); // returns e int offset = word.indexof( e ); // returns 1 int offset = word.tolowercase().indexof( h ); // returns 0 (zero) More java string methods: https://www.javatpoint.com/java-string