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

Similar documents
Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

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:

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

Chapter. Let's explore some other fundamental programming concepts

Conditionals and Loops

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

COMP 202 Java in one week

CMPT 125: Lecture 3 Data and Expressions

ECE 122 Engineering Problem Solving with Java

Chapter 2: Data and Expressions

Full file at

Program Elements -- Introduction

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

Chapter 3. Selections

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Chapter 1. Introduction

COMP 202 Java in one week

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Data Conversion & Scanner Class

BRANCHING if-else statements

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Programming Using Java (98-388)

CSC 1214: Object-Oriented Programming

COMP 202. Java in one week

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

Java Flow of Control

Lecture 3: Variables and assignment

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

2: Basics of Java Programming

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

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

Primitive Data Types: Intro

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

ECE 122 Engineering Problem Solving with Java

2 rd class Department of Programming. OOP with Java Programming

Chapter 4: Conditionals and Loops

Computational Expression

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Chapter 3: Program Statements

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

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

Using Classes and Objects. Chapter

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

Section 2: Introduction to Java. Historical note

More Programming Constructs -- Introduction

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Conditional Programming

Full file at

CS111: PROGRAMMING LANGUAGE II

Chapter 3: Operators, Expressions and Type Conversion

4 Programming Fundamentals. Introduction to Programming 1 1

Lecture Set 2: Starting Java

Java+- Language Reference Manual

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

What did we talk about last time? Examples switch statements

Lecture Set 2: Starting Java

Formatting Output & Enumerated Types & Wrapper Classes

AP Computer Science A

CS 106 Introduction to Computer Science I

Algorithms and Conditionals

Zheng-Liang Lu Java Programming 45 / 79

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 1 Introduction to java

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Program Fundamentals

egrapher Language Reference Manual

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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Java Fall 2018 Margaret Reid-Miller

PROGRAMMING FUNDAMENTALS

Creating a C++ Program

Using Java Classes Fall 2018 Margaret Reid-Miller

CMPT 125: Lecture 4 Conditionals and Loops

Chapter 4: Conditionals and Loops

Chapter 2 Primitive Data Types and Operations. Objectives

JAVA OPERATORS GENERAL

Classes and Objects Part 1

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Topics. Chapter 5. Equality Operators

Basics of Java Programming

CHAPTER 2 Java Fundamentals

Packages & Random and Math Classes

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

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

13 th Windsor Regional Secondary School Computer Programming Competition

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

ARG! Language Reference Manual

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Chapter 2: Using Data

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

CS11 Java. Fall Lecture 1

Transcription:

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

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

The Java Programming Language 3 In the Java programming language: a program is made up of one or more classes a class contains one or more methods a method contains program statements These terms will be explored in detail throughout the course A Java application always contains a method called main Wk04.1 Slide 3

4 A Java Program // comments about the class public class MyProgram { // comments about the method public static void main(string[] args) { } method body method header } Wk04.1 Slide 4

A Very Simple Java Program 5 //****************************************************************** // Lincoln.java Java Foundations Comments about the class // // Demonstrates the basic structure of a Java application. //****************************************************************** class header public class Lincoln { Comments about the method //--------------------------------------------------------------- // Prints a presidential quote. method header //--------------------------------------------------------------- public static void main(string[] args) { System.out.println("A quote by Abraham Lincoln:"); method body class body } } System.out.println("Whatever you are, be a good one."); Output: A quote by Abraham Lincoln: Whatever you are, be a good one. Wk04.1 Slide 5

6 Identifiers Sometimes we choose identifiers ourselves when writing a program (such as Lincoln) Sometimes we are using another programmer's code, so we use the identifiers that he or she chose (such as println) Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way Wk04.1 Slide 6

7 Reserved Words Java reserved words: Wk04.1 Slide 7

8 White Space In Java: Spaces, blank lines, and tabs are called white space White space is used to separate words and symbols in a program A valid Java program can be formatted many ways Extra white space and indenting is ignored by the Java compiler Proper use of White Space is important for people to understand it Programs should be formatted to enhance readability, using consistent indentation Wk04.1 Slide 8

9 Chapter 2 Data & Expressions Sections 2.1 2.5 Wk04.1 Slide 9

10 Character Strings A string of characters can be represented as a string literal by putting double quotes around it Examples: "This is a string literal." "123 Main Street" "X" Every character string is an object in Java, defined by the String class Every string literal represents a String object Wk04.1 Slide 10

11 String Concatenation The string concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly" It can also be used to append a number to a string A string literal cannot be broken across two lines in a program Wk04.1 Slide 11

12 Variables A variable is a name for a location in memory Before it can be used, a variable must be declared by specifying its name and the type of information that it will hold data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration Wk04.1 Slide 12

13 Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; The expression on the right is evaluated and the result is stored in the variable on the left The value that was in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type Wk04.1 Slide 13

14 Primitive Data Types There are eight primitive data types in Java Four of them represent integers byte, short, int, long Two of them represent floating point numbers float, double One of them represents characters char And one of them represents boolean values boolean Wk04.1 Slide 14

15 Expressions An expression is a combination of one or more operators and operands Arithmetic expressions compute numeric results and make use of the arithmetic operators Addition + Subtraction - Multiplication * Division / Remainder % If either or both operands used by an arithmetic operator are floating point, then the result is a floating point Wk04.1 Slide 15

16 Operator Precedence Precedence among some Java operators: Wk04.1 Slide 16

Operator Precedence 17 What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 Wk04.1 Slide 17

18 Key Things to take away: The print and println methods are two services provided by the System.out object In Java, the + operator is used both for addition and for string concatenation An escape character can be used to represent a character that would otherwise cause a compile error A variable is a name for a memory location used to hold a value of a particular data type Accessing data leaves them intact in memory, but an assignment statement overwrites old data One cannot assign a value of one type to a variable of an incompatible type Constants hold a particular value for the duration of their existence Java has two types of numeric values: integer and floating point. There are four integer data types and two floating point data types Java using 16-bit Unicode character set to represent character data Expressions are combinations of operators and operands used to perform a calculation The type of result produced by arithmetic division depends on the types of the operands Java follows a well-defined set of precedence rules that governs the order in which operators will be evaluated in an expression Narrowing conversions should be avoided because they can lose information Wk04.1 Slide 18

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

20 Creating Objects Generally, we use the new operator to create an object: title = new String("James Gosling"); This calls the String constructor, which is a special method that creates the object Creating an object is called instantiation Instantiating an object allocates space in memory for it An object is an instance of a particular class Wk04.1 Slide 20

21 Object References A primitive variable like num1 contains the value itself An object variable link name1 contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically num1 38 name1 "Steve Jobs" Wk04.1 Slide 21

22 Assignment Revisited The act of assignment takes a copy of a value and stores it in a variable For primitive types: Before: num1 38 num2 96 num2 = num1; After: num1 38 num2 38 Wk04.1 Slide 22

23 Assignment Revisited For object references, the address is copied: Before: name1 name2 "Steve Jobs" "Steve Wozniak" name2 = name1; After: name1 name2 "Steve Jobs" Wk04.1 Slide 23

24 Key Things to take away: Object declarations create place holders which point to an object in memory The new operator instantiates a new instance of the class Strings are immutable changing a string creates a new instance A variable holds either a primitive type or a reference to an object Assigning variables of primitive types copies the value Assigning variables of class types copies a reference to the object The String class provides useful methods for working with strings length concat substring touppercase Etc The System.in object represents the standard input stream The Scanner Class provides methods for reading input values Wk04.1 Slide 24

Using Classes and Objects Chapters 3 Section 3.3 Packages Section 3.4 Random Class Section 3.5 Math Class Section 3.7 Enumerated Types Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

26 The Random Class The Random class is part of the java.util package It provides methods that generate pseudorandom numbers A Random object performs complicated calculations based on a seed value to produce a stream of seemingly random values If you specify the same initial seed value, you get the same sequence of random values Very useful for testing with the same sequence of random numbers Wk04.1 Slide 26

27 The Random Class Some methods of the Random class: Wk04.1 Slide 27

28 The Math Class The methods of the Math class are static methods (also called class methods) Static methods can be invoked through the class name only no object of the Math class is needed value = Math.cos(90) + Math.sqrt(delta); We'll discuss static methods in more detail later Wk04.1 Slide 28

29 Key Things to take away: The Java API contains standard set of class definitions Class definitions can be reused by importing packages Packages exist for creating random numbers, math, and formatting You can create your own set of libraries as a package Java provides wrapper classes for primitive data types so they can be used just like any other object Wk04.1 Slide 29

Conditionals and Loops Chapter 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

31 Flow of Control Statement execution is linear unless specified otherwise Public static void main(string[] args) { Flow of Control Statement 1; Statement 2; Statement 3; Statement N; } The order of statement execution is called the flow of control Wk04.1 Slide 31

32 Conditional Statements A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions The Java conditional statements are the if statement if-then-else statement switch statement Wk04.1 Slide 32

33 Equality and Relational Operators Often, conditions are based equality operators or relational operators: Wk04.1 Slide 33

34 Logical Operators Conditions can also use logical operators: They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) Wk04.1 Slide 34

35 Logical Operators Expressions can be evaluated using truth tables For example, let s evaluate the following using a truth table:!done && (count > MAX) Wk04.1 Slide 35

Short-Circuited Operators 36 The processing of logical AND and logical OR is short-circuited If the left operand is sufficient to determine the result, the right operand is not evaluated // This is safe to call even if count equals 0 // thanks to the wonders of short-circuited boolean logic! if (count!= 0 && total/count > MAX) System.out.println("Testing"); This type of processing must be used carefully And can be very useful! Wk04.1 Slide 36

The if-then-else Statement 37 An else clause can be added to an if statement to make an if-then-else statement if ( condition ) statement1; else statement2; If condition evaluates to true, then statement1 is executed otherwise condition must be false, so statement2 is executed One or the other will be executed, but not both Wk04.1 Slide 37

38 Block Statements Several statements can be grouped together into a block statement delimited by braces {} { } if (sum > MAX) delta = sum MAX; System.out.println("The sum is " + sum); A block statement can be used wherever a statement can be used in the Java syntax rules Wk04.1 Slide 38

39 Comparing Data When comparing data using boolean expressions, it's important to understand the nuances of certain data types We will examine some key situations: comparing floating point values for equality comparing characters comparing strings (alphabetical order) comparing object vs. comparing object references Wk04.1 Slide 39

40 The switch Statement An example of a switch statement: switch (option) { case 'A': acount++; break; case 'B': bcount++; break; case 'C': ccount++; break; } Wk04.1 Slide 40

41 The while Loop Example: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute 1 zero or more times 2 How many times does this loop execute? 3 5 times 4 5 What is the output? Wk04.1 Slide 41

The do Loop 42 An example of a do loop: int count = 0; do { count++; System.out.println (count); } while (count < 5); The body of a do loop is executed at least once How many times does count get printed? 5 Wk04.1 Slide 42

43 The for Loop The for loop has the following syntax: The initialization is executed once before the loop begins The statement is executed while the condition remains true for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration Wk04.1 Slide 43

44 Key Things to take away: Flow of Control determines which statements get executed Expressions can form complex conditions using logical operators AND and OR evaluation are short-circuited in Java Selection statements chose different execution paths based on conditions If <condition> then <statement>; If <condition> then <statement1> else <statement2>; Switch <integer value> {Case 1, Case 2, Case N} Java supports two styles of Indefinite Loops: While <condition> <statement>; Do <statement> while <condition>; Java suports two styles of definite Loops: for ( initialization ; condition ; increment ) <statement>; For-each using Iterators Wk04.1 Slide 44