COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Similar documents
COMP 202 Java in one week

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

COMP 202 Java in one week

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

COMP 202. Java in one week

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

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

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

Chapter. Let's explore some other fundamental programming concepts

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

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

Full file at

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

ECE 122 Engineering Problem Solving with Java

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Chapter 2. Elementary Programming

Program Fundamentals

Chapter 2: Data and Expressions

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

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

CMPT 125: Lecture 3 Data and Expressions

Elementary Programming

2 rd class Department of Programming. OOP with Java Programming

2: Basics of Java Programming

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

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

Computer Science is...

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

Basics of Java Programming

Computer Components. Software{ User Programs. Operating System. Hardware

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

Computer Components. Software{ User Programs. Operating System. Hardware

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

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

COMP-202 Unit 5: Basics of Using Objects

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

Data Conversion & Scanner Class

Chapter 2 Elementary Programming

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

Basic Computation. Chapter 2

Programming Lecture 3

Chapter 2 ELEMENTARY PROGRAMMING

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

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

Lecture Set 2: Starting Java

Section 2: Introduction to Java. Historical note

Lecture Set 2: Starting Java

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Programming with Java

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

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

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

CEN 414 Java Programming

Chapter 3: Operators, Expressions and Type Conversion

Primitive Data Types: Intro

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

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS111: PROGRAMMING LANGUAGE II

CSC 1214: Object-Oriented Programming

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

2 nd Week Lecture Notes

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

Accelerating Information Technology Innovation

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

More Programming Constructs -- Introduction

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

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

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

Basic Computation. Chapter 2

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

B.V. Patel Institute of BMC & IT, UTU 2014

First Java Program - Output to the Screen

Lecture 3: Variables and assignment

What did we talk about last time? Examples switch statements

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Introduction to Java Applications; Input/Output and Operators

UNIT- 3 Introduction to C++

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

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

Introduction to C# Applications

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Programming. C++ Basics

AP Computer Science A

Course Outline. Introduction to java

Introduction to Java Applications

Chapter 2: Programming Concepts

An overview of Java, Data types and variables

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Declaration and Memory

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

CS102: Variables and Expressions

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Transcription:

COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Part 1: The Java Programming Language

The Java Programming Language Java was created by Sun Microsystems, Inc. It was introduced in 1995 and has become quite popular It is an object-oriented language It represents the program as a series of objects, each of which belongs to one of many categories called classes The Java programming language combines both compilation and interpretation 3

Java Translation and Execution (1) The Java compiler translates Java source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU Another software tool, an interpreter called the Java virtual machine (JVM) translates bytecode into machine language and executes it Therefore the Java compiler is not tied to any particular machine Java bytecode will run on any CPU for which there exists a JVM Java is considered to be architecture-neutral 4

Java Translation and Execution (2) This is the standard approach to Java translation and execution Java source code.java Java compiler Java bytecode JVM (CPU 1) JVM (CPU 2).class CPU 1 CPU 2 5

Java Translation and Execution (3) Java source code Java compiler.java This approach to Java translation and execution is very uncommon, and probably unnecessary Bytecode compiler (to CPU 1) binary code (CPU 1) Java bytecode Bytecode compiler (to CPU 2) binary code (CPU 2) CPU 1 CPU 2.class 6

Java Program Structure (1) In the Java programming language: A program consists of one or more classes; each class is defined in a different file A class contains one or more methods A method contains program statements Statements are the actual commands you issue, the instructions that are executed when the program runs A Java program always has at least one class which contains a method called main() This is where the program starts executing 7

Java Program Structure (2) For now, all programs we develop will involve writing only one class, and this class will contain exactly one method: main() 8

Java Program Structure: Classes public class MyProgram { } class body class header: the name of the class The class header states that you are defining a new class whose name will be the name you specify. This class will consist of what you write in the class body. Important note: the name of the file which contains this class MUST be the name of the class, followed by extension.java Here: MyProgram.java 9

Java Classes There are three possible roles for a class in Java A class can be the starting point of a program; any class that defines a main() method has this role A class can be a collection of related methods; this is called a library A class can define a category of objects, and specify what objects that belong to this category look like and how they behave Many classes only have one of these roles, but some have two and even all three For now, all the classes we write will have only one role: they will be the starting point of a program 10

Java Program Structure: Methods public class MyProgram { } public static void main(string[] args) { } method body method header The method header states that you are defining a new method; this method consists of the statements in the method body. The method header also specifies the new method's name. 11

Java Methods A Java method is a list of statements that has been given a name The statements that the method consists of perform a task when they are executed together Writing a method means specifying a list of statements and giving a name to this list of statements Once a method is written, its name can be used as a single statement inside another method When that single statement is executed, all statements in the method are executed This is referred to as calling or invoking a method We will cover methods in detail later 12

Part 2: Java Basics

Our First Java Program (1) Here is our first Java program: public class HelloWorld { public static void main(string[] args) { System.out.println("Hello world!"); } } Some highlights: It involved writing a single class called HelloWorld This class contains a single method called main(), which is where the program starts The main() method contains a single statement, which requests that the sentence "Hello world!" (without the quotation marks) be displayed on the screen 14

Our First Java Program (2) By looking at the program and knowing what it does, can you deduce a way to modify it so that it does the following: Display "Programming is fun!" instead of "Hello world!"? Display two different sentences? 15

EchoNumber.java import java.util.scanner; /* This program asks the user to enter an integer, reads this integer from the keyboard, and displays it to the screen. */ public class EchoNumber { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int number; } } // Prompt the user for a number, read it, and display it. System.out.print("Enter a whole number: "); number = keyboard.nextint(); System.out.println("You entered the following number " + number); 16

Dissecting EchoNumber.java Although very simple, the program in EchoNumber.java illustrates a number of basic concepts of Java programming: Comments White space and formatting Identifiers Variables Data types Assignment statements Reading information from the keyboard Displaying information to the screen We will now cover each of these concepts in detail one by one 17

Comments (1) Comments are notes in a program They are meant for humans, and are completely ignored by the compiler You can write anything in a comment In most cases, they describe aspects of the program such as its purpose or the way it works Syntax Comments that start with // end when the current line ends; the compiler ignores everything between // and the end of the current line Comments that start with /* end with */ ; the compiler ignores everything between /* and the matching */ 18

Comments (2) Comment examples: // This is a one line comment. /* This is a multi-line comment. */ Even though they do not change how the program works, comments are important! They provide valuable information to humans who read the program about its purpose and the way it works, including to the one who wrote it in the first place! "You know you're brilliant, but maybe you'd like to understand what you did 2 weeks from now." - Linus Torvalds, Linux 1.3.53 CodingStyle documentation 19

Formatting Rules Spaces, blank lines, and tabs are collectively called white space It is used to separate words and symbols in a program Extra white spaces are completely ignored A valid Java program can be formatted many different ways Programs should be formatted for readability by humans Use proper indentation Use space and new lines Use comments The program in EchoNumber.java is formatted very nicely 20

Bad Formatting (1) The following is an example of a (very) badly formatted program: import java.util.scanner; public class EchoNumberBad { public static void main(string[] args){ Scanner keyboard = new Scanner(System.in); int number; System.out.print("Enter a whole number: "); number = keyboard.nextint(); System.out.println( "You entered the following number " + number); }} 21

Bad Formatting (2) As long as a program is syntactically correct, the compiler will understand it, no matter how badly formatted it is However, humans who have to read your program (including TAs) may have trouble understanding it if it is badly formatted Make sure to format your programs so that they are readable by humans 22

Identifiers (1) Identifiers are the words a programmer uses in a program They are used to give names to things Examples of things that can be named with identifiers: Classes Methods Variables Constants An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign ($) Identifiers cannot begin with a digit 23

Identifiers (2) Java is case sensitive, therefore Result and result are different identifiers Sometimes we choose identifiers ourselves when writing a program (such as number, keyboard, or EchoNumber) We should choose identifiers that are meaningful so that the program is more readable for humans Sometimes we are using another programmer's code, so we use the identifiers that they 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; it cannot be used to give names to things like other identifiers 24

Identifiers (3) Examples of reserved words: class, public, static, void There are many others 25

Java Reserved Words Here is the complete list of Java reserved words: abstract double int super assert else interface switch boolean enum long synchronized break extends native this byte final new throw case finally package throws catch float private transient char for protected try class goto public void const if return volatile continue implements short while default import static do instanceof strictfp 26

Identifiers: Exercise Which of the following identifiers are invalid according to the Java rules for identifiers? Why are they invalid? myidentifier _my_other_identifier yet-another-identifier $can 2for1 twofor1 class my_class 27

Identifier Conventions There exist Java style conventions for identifiers Do not put characters between words The first letter of a word should be in upper-case The first letter of the first word should be in lower-case unless the identifier is for a class The first word of the identifier for a method should be a verb Identifiers should be descriptive and avoid abbreviations The compiler will not complain if you do not follow the conventions, but not following conventions considered bad practice See the General Instructions and Regulations for Assignments for further information regarding conventions for identifiers 28

Conventions: Exercise Which identifiers follow style conventions for Java? myidentifier _my_other_identifier totalvalue totval thesumofallthevaluesenteredbytheuser MyClass my_class getvalue GetValue 29

Variables (1) A variable is a placeholder for values We can store a value in a variable We can use the value stored in a variable to compute other values (which may be stored in other variables), to make decisions, to display it, or for other things Before we use the value that a variable contains, we must store a value in this variable, otherwise the compiler will report an error Each variable has a name The compiler allocates one or more consecutive memory cells The (combined) contents of these cells forms the value of the variable The compiler assigns the name chosen for the variable to these cells 30

Variables (2) We can then refer to the value stored in these memory cells using the variable name Much easier, more practical, and more flexible than using the addresses of the memory cells (and less error-prone) Each variable also has a type The type of a variable specifies the kind of values it can contain 31

Variable Declarations Before we can store a value in a variable or use the value it contains, we have to declare it A variable declaration is a statement that announces that want to create and use a new variable They can occur anywhere in a method, but they are typically at the beginning They must indicate the name and the type of the new variable Once a variable has been declared, we can store a value in it or use the value it contains If you try to store a value in a variable before it is declared, or use the value stored in a variable before the variable is declared, the compiler will generate an error 32

Syntax for Declaring Variables modifiers type identifier = value; Where: modifiers final,... (optional) type int, double, char (mandatory) identifier as defined previously (mandatory) = value an expression matching the type (optional) ; (mandatory) This is a partial definition 33

More on Variable Declarations Note that you can declare more than one variable with one variable declaration statement The variable names are separated using commas For example, the following statement declares three different variables, called var1, var2, and var3, each of type int: int var1, var2, var3; 34

Types A type is a category of values that a variable belongs to and determines: How to interpret the value it contains What are the possible values it can contain For example, it makes no sense to assign the name of a month as a value to a variable whose purpose is to hold the name of a day of the week In Java, all variables and all values have a type 35

The Purpose of Types The type of a variable provides an answer to the following question: should the value of the variable be considered as an integer, a real number, a character, or maybe even something else? For a computer, everything is stored as a series of ones and zeros We need a way to tell what the ones and zeros represent and how they should be interpreted by the program 36

Types in Java There are two broad kinds of types in Java: primitive types and reference types We will see reference types later in the course Primitive types represent very basic kinds of values They are defined by the Java language and directly supported by the compiler 37

Primitive Types There are exactly 8 primitive types in Java Four of them represent integers (positive and negative whole numbers): byte, short, int, long Two of them represent floating point numbers (positive and negative numbers with decimal parts): float, double One of them represents characters: char And one of them represents boolean values (true or false): boolean 38

Numeric Primitive Types The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double Space 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Literal 5 5 5 5L 5.2f 5.2 Minimum -128-32768 -2147483648 ~ -9 X 10 18 Maximum +/- 3.4 X 10 38 (with 7 significant digits) 127 32767 2147483647 ~ 9 X 10 18 +/- 1.7 X 10 308 (with 15 significant digits) 39

Real vs. Floating Point A real number is number that can be given by an infinite decimal representation For example, π = 3.14159265... However, we would need infinite memory to store a number with infinite decimal representation The solution: floating point numbers A floating point number is an approximation of a real number; it can only have a finite number of decimal places Floating point numbers need only finite space (they fit in a memory cell or a finite set of memory cells) 40

Characters A char variable stores a single character from the Unicode character set char gender; gender = 'M'; A character set is an ordered list of characters, and each character corresponds to a unique number The Unicode character set uses 16 bits (2 bytes) per character, allowing for 65536 unique characters It is an international character set, containing symbols and characters from many world languages Character values, also called character literals, are delimited by apostrophes: 'a' 'X' '7' '$' ',' '\n' 41

More on Characters The ASCII character set is older and smaller than Unicode, but is still quite popular The ASCII characters are a subset of the Unicode character set, including: upper-case letters lower-case letters punctuation digits special symbols control characters A, B, C,... a, b, c,... period (.), semicolon (;),... 0, 1, 2,... &,, \,... carriage return, line feed, tab,... 42

Escape Sequences (1) What if we wanted a store an apostrophe (') in a variable of type char? The following line would confuse the compiler because it would interpret the second apostrophe as the end of the char literal: char c = '''; // Error! An escape sequence is a series of characters that represents one special character An escape sequence begins with a backslash character (\), which indicates that the character(s) that follows should be treated in a special way: char c = '\''; // OK! 43

Escape Sequences (2) For example, assigning the char literal '\'' to the a char variable will result in the apostrophe being stored in the variable The backslash in the char literal tells the compiler that the apostrophe that follows does not mark the end of the char literal, but instead is part of the char literal 44

Java Escape Sequences Some escape sequences in Java: Escape sequence Meaning \b \t \n \r \" \' \\ Backspace Tab New line (line feed) Carriage return Double quotation mark (String) Single quotation mark (char) Backslash 45

Boolean Values An expression that evaluates either to true or to false Named after George Boole, the inventor of Boolean algebra Similar concept in natural (human) languages: "the traffic light is red" This expression is either true or false 46

Boolean Type You can declare variables which are of type boolean A boolean variable represents a true or false condition A boolean can also be used to represent any two states, such as a light bulb being on or off The literals true and false are the only valid values for a boolean type While not technically reserved words, you cannot use them for any other purpose than as a literal boolean value Example: boolean done = false; // Some code here done = true; 47

The Assignment Statement (1) To store a value in a variable, we use the assignment statement The assignment operator in Java is the = sign The syntax for the assignment statement is the following: variable = expression; The expression on the right of the = sign is evaluated An expression can consist of a single value, a single variable, or a more complex combination involving many operators and operands The result of evaluating the expression is stored in the variable on the left of the = sign; the previous value stored in that variable (if any) is overwritten The values stored in the variables on the right side of the assignment statement do not change (except when special operators are used) 48

The Assignment Statement (2) The left-hand side of the = MUST be a SINGLE variable; it CANNOT be an expression with multiple operators and operands The = operator does NOT define an equation 49

Reading from the Keyboard (1) To read values from the keyboard, we use Scanner First, we must declare a variable of type Scanner, and initialize it Scanner variable = new Scanner(System.in); variable can be replaced by any identifier; keyboard is a good choice, but there is nothing special about it Everything else, however, must be exactly as above This only needs to be done once in your program, but it needs to be done before you attempt to read any values To read a value of type int from the keyboard, we use the following expression: variable.nextint() 50

Reading from the Keyboard (2) variable must be replaced by the identifier you used when you declared the Scanner variable Thus, if you called your Scanner variable foo, you must write foo.nextint() if you want to read an int value from the keyboard The expression variable.nextint() (where variable is a variable of type Scanner) can be used as the right side of an assignment statement: int input; input = keyboard.nextint(); The right side of the assignment statement is evaluated; this results in a value of type int being read from the keyboard 51

Reading from the Keyboard (3) The value read from the keyboard is then stored in the variable on the left side of the assignment statement, overwriting any previous values stored in that variable To read a value of type double instead of type int, simply replace nextint() by nextdouble() 52

Displaying to the Monitor You can use one of two built-in commands to display something to the monitor: System.out.println(stuffToDisplay); Displays stufftodisplay followed by a line break System.out.print(stuffToDisplay); Only stufftodisplay is displayed 53

More on print() / println() println() and print() each take one input (also called parameter or argument) a character string: println("hello world!"); the value of a variable: println(output); the combination of both: println("the sum is " + output); a combination can have more than two parts: println("the sum is " + sum + " and the " + " difference is " + difference); 54

Examples of Displaying Text System.out.println("Hello world!"); The character string Hello world! is displayed int value = 5; System.out.println(value); The value 5 is displayed double price = 44.99; System.out.println("This book costs " + price + " dollars"); The character string This book costs 44.99 dollars is displayed 55

Countdown.java public class Countdown { public static void main(string[] args) { System.out.print("Three... "); System.out.print("Two... "); System.out.print("One... "); System.out.print("Zero... "); } } System.out.println("Liftoff!"); System.out.println("Houston, we have a problem!"); What does this display? 56

Countdown Result The following is displayed when the Countdown program is executed Three... Two... One... Zero... Liftoff! Houston, we have a problem! _ Cursor ends up here 57

Aside: Calling Methods (1) When you read a value from the keyboard, what you are really doing is calling a method The method is called nextint() or nextdouble(), depending on what you are reading The method is invoked on an object which belongs to class Scanner The name of this object is the name you gave to your Scanner variable Likewise, when you display something to the monitor, you are also calling a method The method is called println() or print() The method is invoked on an object which belongs to class PrintStream 58

Aside: Calling Methods (2) The name of this object is System.out We will revisit this aspect of reading and displaying when we cover classes and objects 59

Reading and Displaying: Exercise Write a Java program which consists of one class called ReverseDisplay. This class must define a method called main() which does the following: Displays a message asking the user to enter an integer Reads this integer from the keyboard Displays a message asking the user to enter another integer Reads this second integer from the keyboard Displays the second integer entered by the user along with a message describing the meaning of this value Displays the first integer entered by the user along with a message describing the meaning of this value 60

Program Template To make it easier to write programs, you can use the following template as a starting point: import java.util.scanner; public class Template { // Change "Template" to the desired name // for your class public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); // Write your program statements here } } 61

Part 3: Expressions

Arithmetic Expressions An expression is a combination of operators and operands Operators are optional but operands are mandatory An operand can be a literal value (for example, 5 or 3.14), a variable, or the value returned by a method call (like nextint()) Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition: Subtraction: Multiplication: Division: Remainder: x + y x y x * y x / y x % y Negation: -x 63

Division With Integers If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) The remainder operator (%) returns the remainder after dividing the second operand by the first Example: int numhours = 52; int fulldays = numhours / 24; // fulldays contains 2 int remaininghours = numhours % 24; // remaininghours contains 4 Division by 0 with integers Produces run-time error The program has to avoid it, or it will crash 64

DivisionInt.java import java.util.scanner; public class DivisionInt { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int numerator, denominator, quotient, remainder; } } // Read the values System.out.print("Enter the numerator: "); numerator = keyboard.nextint(); System.out.print("Enter the denominator: "); denominator = keyboard.nextint(); quotient = numerator / denominator; remainder = numerator % denominator; System.out.println("The result is: " + quotient); System.out.println("The remainder is: " + remainder); What does this display? 65

Operator Precedence Operators can be combined into complex expressions: result = total + count / max offset; Operators have a well-defined precedence which determines the order in which they are evaluated Multiplication (*), division (/), and remainder (%) are evaluated prior to addition (+) and subtraction (-) Arithmetic operators with the same precedence are evaluated from left to right Parentheses can always be used to force the evaluation order 66

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

Assignment Operator Precedence The assignment operator has a lower precedence than the arithmetic operators answer = sum / 4 + MAX * lowest; Then the result is stored in the variable on the left-hand side 4 1 3 2 First, the expression on the right side of the = operator is evaluated 68

Assignment Operator Sides The left-hand and right-hand sides of an assignment statement can contain the same variable: count = count + 1; Then, the overall result is stored into count, overwriting the original value First, 1 is added to the original value of count; the result is stored in a temporary memory location The fact that the assignment operator has lower precedence than arithmetic operators allows us to do this 69

Arithmetic Expressions: Exercise 1 Write a Java program which consists of one class called AddTwoIntegers. This class must define a method called main() which does the following: Displays a message asking the user to enter an integer Reads an integer from the keyboard Displays a message asking the user to enter another integer Reads another integer from the keyboard Adds the two integers read from the keyboard together Displays the result with an appropriate message How would you modify this program to add two real numbers instead? 70

Arithmetic Expressions: Exercise 2 Write a Java program which consists of one class called TemperatureConverter. This class must define a method called main() which does the following: Displays a message asking the user to enter a temperature in Celcius degrees Converts the temperature in Celcius degrees to Fahrenheit degrees; the formula for this calculation is f = (9c / 5) + 32, where f is the temperature in Fahrenheit, and c is the temperature in Celcius Displays the equivalent temperature in Fahrenheit with an appropriate message 71

Increment / Decrement Operators The increment and decrement operators are arithmetic and operate on one operand This operand must be a single variable The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The increment and decrement operators can be applied in prefix form (before the variable) or postfix form (after the variable) 72

Increment / Decrement Semantics When used alone in a statement, the prefix and postfix forms are basically equivalent That is, when used alone in a statement, ++count; is equivalent to count++; which is equivalent to count = count + 1; However, they are not equivalent when they are used in expressions! Using these operators in expressions requires you to really know what you are doing 73

Increment / Decrement Advice Using increment and decrement operators is fine if this operator is the only operation in a statement i++; // OK ++j; // OK too Do not use increment and decrement operators in more complex statements total = count++ - --count; // Avoid! index = ++i * --j / k++; // Avoid too! 74

Assignment Operators (1) Often we perform an operation using a variable, then store the result back into that variable Java provides additional assignment operators to simplify that process They combine the assignment operator with an arithmetic operator Example 1: The statement total += 5; is equivalent to total = total + 5; Example 2: The statement result *= count1 + count2; is equivalent to result = result * (count1 + count2); 75

Assignment Operators (2) In general, assignment operators have the form variable op= expression; which is equivalent to variable = variable op (expression); The entire expression on the right side of the assignment operator is evaluated It can be a complex expression involving many levels of parentheses Then, the result of evaluating that expression is used on the right hand side of the operator in the assignment operator The left operand is the variable on the left of the assignment operator The final result is stored back in the variable on the left-hand side of the assignment operator 76

Assignment Operators (3) There are many assignment operators, including the following: Operator Example Equivalent to += x += y; x = x + y; -= *= /= %= x -= y; x *= y; x /= y; x %= y; x = x - y; x = x * y; x = x / y; x = x % y; 77

Boolean Expressions Instead of evaluating to a numeric value, boolean expressions evaluate to either true or false mynumber > 0 // can be either true or false You can assign the result of a boolean expression to a variable of type boolean: boolean positive; positive = (mynumber > 0); Boolean expressions are often used to control the flow of execution of a program We will see control flow in detail later in the course; we will cover boolean expressions in more detail then 78

Constants (1) A constant is an identifier that is similar to a variable except that it holds one value for its entire existence In Java, we use the final modifier to declare a constant final double PI = 3.14; The compiler will issue an error if you try to assign a value to a constant more than once in the program final double PI = 3.14; // Some more statements... PI = 2.718; // Error: cannot assign a value to a // final variable more than once 79

Constants (2) Java style conventions for constants: identifiers for constants should contain only upper-case letters, and each word in the identifier should be separated by an underscore (_) 80

Advantages of Constants Constants give names to otherwise unclear literal values The meaning of 0.05 may not be clear to the person reading your code, but the meaning of GST or TAX is Constants facilitate changes to the code More precision required? Change PI from 3.14 to 3.14159265 in only one place No need to search the whole program for occurrences of the value Constants prevent inadvertent errors The programmer cannot type the wrong value by mistake If you type Pi instead of PI, the compiler will report an error; if you type 31.4 instead of 3.14, the compiler will not report an error but your calculations will probably be all wrong 81

Constants: Exercise Write a Java program which consists of one class called Circle. This class should define a method called main() which does the following: Displays a message asking the user to enter the radius of a circle, and reads the value of the radius from the keyboard Computes the circumference of the circle; the formula for this calculation is c = 2πr, where r is the radius of the circle and c is its circumference Computes the area of the circle; the formula for this calculation is a = πr 2, where r is the radius of the circle and a is its area Displays both values with an appropriate message You must declare π as a constant called PI, with 4 digits after the decimal, and use this constant in your calculations 82

Part 4: String Basics

The String Type (1) As we saw earlier, a variable of type char can only store a single character value char c1 = 'a'; char c2 = '%'; What could we do if we wanted to store an ordered sequence of characters, like: a word? a complete sentence, including spaces and punctuation? One possible answer: use a variable of type String 84

The String Type (2) The String type is a reference type, not a primitive type However, because Strings are so common, the Java programming language allows us to use the String type almost in the same way we use primitive types The differences will be explained in detail when we cover reference types 85

String Variables and Values Variables of type String are declared just like variables of other types But remember that Java is case-sensitive For example, if you wanted to declare a variable of type String called message, you could do it like this String message; Actual String values, often called String literals, are delimited by double quotation marks (") This is unlike char values, which are delimited by apostrophes In Java, every (legal) character sequence delimited by double quotation marks is a String literal Examples of String literals: "Hello", "world", "See ya!" 86

String Assignment The assignment operator works almost the same way with Strings as it does with primitive types The syntax is the same The semantics are mostly the same; the differences will be explained in detail when we cover reference types String message; message = "Hello world!"; // Variable message now contains the // String value "Hello world!" System.out.println(message); // Displays "Hello world!" 87

String Concatenation String concatenation occurs when a String is added to the end of another String, thus forming a new String The concatenation of "a" and "b" is "ab"; likewise, the concatenation of "ab" and "cd" is "abcd" In Java, the String concatenation operator is the + operator "hello " + "world" results in a new String This new String will be "hello world" The + operator is the only arithmetic operator which can be used with Strings 88

Reading and Displaying Strings We can read Strings from the keyboard just like we read int or double values Simply replace nextint() or nextdouble() by nextline() The variable on the left side of the assignment statement must be of type String nextline() reads an entire line of text We can also display Strings to the screen just like we display anything else: by using System.out.print() or System.out.println() 89

Facts.java public class Facts { public static void main(string[] args) { String firstname = "Cuthbert"; String lastname = "Calculus"; String fullname; } } fullname = firstname + " " + lastname; System.out.println("His name is: " + fullname); What is the output? 90

String Caveats (1) One must be able to distinguish String literals from String variables String variables are regular identifiers String literals are always surrounded by double quotation marks Therefore, assuming that variables text and message of type String, and that the value of variable message is the String "Hello!" The line text = "message"; assigns the String value "message" to String variable text 91

String Caveats (2) Thus, if the line System.out.println(text); is executed next, the following will be displayed to the screen: message On the other hand, the line text = message; assigns the String value stored in String variable message (that is, the String "Hello!") to String variable text Thus, if the line System.out.println(text); is executed next, the following will be displayed to the screen: Hello! 92

String Caveats (3) A String literal cannot be broken across two lines of source code by inserting an end-of-line sequence in it If you really need to split a String literal across two lines in your program, break the original literal into two smaller String literals and combine them with the concatenation operator The following code fragment causes an error: "This is a very long literal that spans two lines" // Incorrect! However, the following code fragment is legal: "These are two shorter literals " + "that are on separate lines" // OK 93

String Escape Sequences (1) What if we wanted to include a double quotation mark in a String literal? The following line would confuse the compiler because it would interpret the second double quotation mark as the end of the String literal: System.out.println("I said "Hello" to you."); If we want to include a double quotation mark in a String literal, the double quotation mark has to be escaped by putting a backslash (\) in front of it System.out.println("I said \"Hello\" to " + "you."); 94

String Escape Sequences (2) In general, escape characters work the same with Strings as they do with chars However: Double quotation marks MUST be escaped in String literals, but not in char literals Apostrophes MUST be escaped in char literals, but not in String literals Escaping a double quotation mark in a char literal or an apostrophe in a String literal has no effect 95

Poem.java public class Poem { public static void main(string[] args) { System.out.println("Roses are red,"); System.out.println("\t Violets are blue"); System.out.println("\t This poem " + "sucks\n\t I wish it were a haiku"); } } What does this display? 96

Haiku.java public class Haiku { public static void main(string[] args) { System.out.print("\t Windows Vista crashed."); System.out.print("\n\t I am the Blue Screen " + "of Death.\n"); System.out.println("\t No one hears your screams."); } } What does this display? 97

Strings: Exercise Write a Java program which consists of one class called Greeting. This class should define a method called main() which does the following: Displays a message asking the user to enter his/her first name, and reads the first name from the keyboard Displays a message asking the user to enter his/her last name, and reads the last name from the keyboard Displays a greeting to the user in the following format: the String "Hello, ", followed by the user's first name, followed by a single space, followed by the user's last name, followed by an exclamation mark (!) 98

Part 5: Data Conversion

Data Conversion Sometimes it is convenient to convert data from one type to another For example, we may want to treat an integer as a floating point value during a computation Conversions must be handled carefully to avoid losing information There are two types of conversions: Widening conversions Narrowing conversions But first, a word on precision 100

Precision The precision of a type is the range of all possible values you can express with a variable of that type Variables of type int have higher precision than variables of type short; you can express more values with a variable of type int than with a variable of type short Variables of type double have higher precision that variables of type int; again, you can express more values with a variable of type double than with a variable of type int There is a correlation between the number of bytes used to store a value of a given type, and the precision of that type byte uses only 8 bits and has the lowest precision; double uses 64 bits and has the highest precision 101

Conversion Types Widening conversions occur when a value whose type has lower precision is converted to a type that has higher precision (such as a short to an int or an int to a double) They are usually safe, as there is usually no information lost Narrowing conversions occur when a value whose type has higher precision is converted to a type that has lower precision (such as an int to a short or double to int) Information can be lost when conversions of this type occur 102

Assignment Conversion (1) In Java, data conversions can occur in three ways: Assignment conversion Arithmetic promotion Casting Assignment conversion occurs when a value of one type is assigned to a variable of another type Only widening conversions can occur via assignment (such as assigning a value of type int to a variable of type double) If we attempt a narrowing conversion via assignment (such as assigning a value of type double to a variable of type int), the compiler will issue an error 103

Assignment Conversion (2) Assignment conversions occur automatically For example, if we attempt to assign the value of an expression of type int to a variable of type double, the value of the expression will be automatically converted to have type double The second assignment statement below is perfectly legal: int i = 7; double d = 3 + i; The expression on the right-hand side has type int, which has lower precision than type double, the type of the variable on the left-hand side The value of 3 + i gets converted to have type double and gets assigned to d; note that the type of i does not change 104

Assignment Conversion (3) The assignment second assignment statement below is illegal: double d = 7.0; int i = 3.0 + d; The expression on the right-hand side has type double, which has higher precision than type int, the type of the variable on the left-hand side The compiler will therefore report an error 105

Arithmetic Promotion Arithmetic promotion happens automatically when operators in expressions convert their operands double kmperlitre; int km = 1000; float litres = 85.0f; kmperlitre = km / litres; (2) Division (1) Arithmetic promotion to float (3) Assignment conversion to double (4) Assign result to kmperlitre 106

Casting (1) Casting (also called typecasting) is the most powerful, general, and dangerous, technique for conversion It trusts that you know what you are doing Both widening and narrowing conversions can be accomplished by explicitly casting a value It is the only way to perform a narrowing conversion To cast, the type you want to convert a value to is put in parentheses in front of the value being converted. The general syntax is thus: (desiredtype) expression 107

Casting (2) The cast does not change the type of the value in a variable for the rest of the program, only for the operation in which the value is cast When casting from floating point to integer, the fractional part of the floating point is discarded double money = 25.80; int dollars; dollars = (int)money; // dollars contains the value 25 // money still contains the value 25.80 108

Casting (3) Casting has higher precedence than the arithmetic operators double a; int b, c, d; a = 3.5; b = 3; c = (int)a * b; d = (int)(a * b); Only the value of a is cast; the value of b is not cast Thus, c now contains the value 9 The product of a and b is cast Thus, d now contains the value 10 109

Conversion Traps (1) Consider the following variable declarations: int total = 10; int count = 4; double result; What will the value of result be after the following statement is executed? result = total / count; The value of result is now 2.0 (?!?) The two operands of the division operator have type int; thus, integer division is performed, truncating the fractional part The result of total / count is therefore 2 and has type int 110

Conversion Traps (2) It's only when the quotient is assigned to result that it is converted to type double via assignment conversion Casting one of the integer operands to double (or float) will result in floating point division being performed instead result = (float)total / count; The value of result is now 2.5 First, total is cast to type float Arithmetic promotion occurs to promote count to have type float; floating point division is performed and the result of the division therefore has type float The quotient is converted to type double before being assigned to result 111

Conversion Examples Code Fragment double x = 5.9; int y = (int) x; int a = 5; float b = 7.3f; double c = 10.03; c = b + a; int a = 2, b = 5; double c = 22; c = a / b; Result y contains value 5 c contains value 12.3 c contains value 0.0 112

Type Conversions and Strings For the most part, primitive types and Strings do not mix Assignment conversion between Strings and primitive types is forbidden If you try to assign a value whose type is a primitive type to a String variable, the compiler will report an error If you try to assign a String to a variable whose type is a primitive type, the compiler will also report an error Casting a String to a primitive type and casting a value whose type is a primitive type to a String are both forbidden The compiler will report an error in those cases as well 113

Mixed-Type Concatenation (1) On the other hand, we can convert a value whose type is a primitive type to a String by using something similar to arithmetic promotion Remember: the plus operator (+) is used for both arithmetic addition and for string concatenation The function that the + operator performs depends on the type of the values on which it operates Strings are considered to have higher precision than numeric types If both operands are of type String, or if one is of type String and the other is numeric, the + operator performs string concatenation (after "promoting" the numeric operand, if any, to type String by generating its textual representation) 114

Mixed-Type Concatenation (2) If both operands are numeric, it adds them The + operator is evaluated left to right, regardless of whether it performs addition or string concatenation However, parentheses can always be used to force the operation order This suggests a useful trick to convert a value whose type is a primitive type to a String: concatenate the empty String "" with the value int i = 42; String s = "" + i; // s contains the String "42" 115

Addition.java public class Addition { public static void main(string[] args) { int x = 5; int y = 2; int sum = 0; String message = "The sum is "; } } sum = x + y; message = message + sum; System.out.println(message); What is the output? 116

Trick Question (1) What will be the output of the following code fragment? System.out.println("The sum of 5 and 3 is " + 5 + 3); The answer is: The sum of 5 and 3 is 53 (?!?) Explanation: The + operator is evaluated from left to right Thus, it is first applied to "The sum of 5 and 3 is " and the int literal 5 to form the String "The sum of 5 and 3 is 5" Then, we apply the + operator to the result from the previous concatenation operation and the int literal 3 to get "The sum of 5 and 3 is 53" 117

Trick Question (2) What will be the output of the following code fragment? System.out.println(5 + 3 + " is the sum of " + "5 and 3"); The answer is: 8 is the sum of 5 and 3 (?!?) Explanation: Again, the + operator is evaluated from left to right Thus, it is first applied to the int literals 5 and 3; both of these have numeric type, so addition is performed and the sum is 8 Then, the + operator is applied to the result of the addition and the String literal " is the sum of "; the sum is converted from int to String and concatenated with the String literal 118

Trick Question (3) Finally, the String literal "5 and 3" is concatenated to the String "8 is the sum of " to form the String "8 is the sum of 5 and 3" Lesson: When in doubt, use parentheses 119

Part 6: Problem Solving

Problem Solving The purpose of writing a program is to solve a problem (or rather, have the computer solve a problem for us) The general steps in problem solving are: Understand the problem Dissect the problem into manageable pieces Design a solution for each of the pieces Consider alternatives to the solutions and refine them Implement the solutions Test the solutions and fix any problems that exist Combine the solutions for each of the piece to obtain the solution to the original problem 121

Part 7: Exercises

Exercises (1) 1. Write a program which consists of a single class called BMICalculator. This class must define a method called main() which does the following: Asks the user to enter his/her weight (in kilograms) and his/her height (in meters) Calculates the user's Body Mass Index (BMI); a person's BMI can be computed by dividing his /her weight in kilograms by the square of his / her height in meters. Displays the user's BMI it to the screen 123

Exercises (2) 2. Write a program which consists of a single class called EnergyCalculator. This class defines a method called main() which does the following: Asks the user to enter a quantity of water (in kilograms), an initial temperature (in Celcius degrees), and a final temperature (also in Celcius degrees) Calculates how much energy (in joules) is needed to raise that quantity of water from the initial temperature to the final temperature; the formula for this calculation is q = 4184 m (f i), where q is the energy, m is the quantity of water, f is the final temperature, and i is the initial temperature. You may assume that there are no state transitions (from ice to water or water to steam, for example) in the temperature interval Displays the required energy quantity to the screen 124

Exercises (3) 3. Write a program which consists of a single class called GoalieStatsCalculator. This class defines a method called main() which does the following: Asks the user to enter the number of minutes an ice hockey goalie has played, the number of goals he / she allowed, and the total number of shots he / she faced Calculates the goalie's goals against average (GAA) and save percentage; the GAA is the number of goals allowed per 60 minutes of play, while the save percentage is the number of saves (the total number of shots minus the number of goals allowed) divided by the number of shots faced Displays the goalie's GAA and save percentage to the screen 125