125
COMP 202 – Introduction to Computing 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

COMP-202Unit 2: Programming Basics

CONTENTS:The Java Programming LanguageVariables and TypesBasic Input / OutputExpressionsConversions

Page 2: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

Part 1: The Java Programming Language

Page 3: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

3COMP-202 - Programming Basics

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

Page 4: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

4COMP-202 - Programming Basics

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

Page 5: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

5COMP-202 - Programming Basics

Java Translation and Execution (2)

.java

Javacompiler

.classJava sourcecode

Java bytecode

JVM(CPU 1)

CPU 1

JVM(CPU 2)

CPU 2

This is the standard approach to Java translation and execution

Page 6: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

6COMP-202 - Programming Basics

Java Translation and Execution (3)

Javacompiler

Java sourcecode

Java bytecode

.javaBytecodecompiler

(to CPU 2)

Bytecodecompiler

(to CPU 1)

binary code(CPU 1)

binary code(CPU 2)

CPU 1 CPU 2

.class

This approach to Java translation and execution is very uncommon, and probably unnecessary

Page 7: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

7COMP-202 - Programming Basics

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

Page 8: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

8COMP-202 - Programming Basics

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()

Page 9: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

9COMP-202 - Programming Basics

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 .javaHere: MyProgram.java

Page 10: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

10COMP-202 - Programming Basics

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

Page 11: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

11COMP-202 - Programming Basics

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.

Page 12: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

12COMP-202 - Programming Basics

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

Page 13: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

Part 2: Java Basics

Page 14: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

14COMP-202 - Programming 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

Page 15: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

15COMP-202 - Programming Basics

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?

Page 16: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

16COMP-202 - Programming Basics

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); }}

Page 17: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

17COMP-202 - Programming Basics

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

Page 18: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

18COMP-202 - Programming Basics

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 */

Page 19: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

19COMP-202 - Programming Basics

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

Page 20: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

20COMP-202 - Programming Basics

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

Page 21: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

21COMP-202 - Programming Basics

Bad Formatting (1)

• The following is an example of a (very) badly formatted program:

import java.util.Scanner;public classEchoNumberBad { public static voidmain(String[] args){ Scannerkeyboard = 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); }}

Page 22: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

22COMP-202 - Programming Basics

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

Page 23: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

23COMP-202 - Programming Basics

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

Page 24: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

24COMP-202 - Programming Basics

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

Page 25: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

25COMP-202 - Programming Basics

Identifiers (3)

– Examples of reserved words: class, public, static, void

– There are many others

Page 26: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

26COMP-202 - Programming Basics

Java Reserved Words

• Here is the complete list of Java reserved words:

abstract double int superassert else interface switchboolean enum long synchronizedbreak extends native thisbyte final new throwcase finally package throwscatch float private transientchar for protected tryclass goto public voidconst if return volatilecontinue implements short whiledefault import staticdo instanceof strictfp

Page 27: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

27COMP-202 - Programming Basics

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

Page 28: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

28COMP-202 - Programming Basics

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

Page 29: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

29COMP-202 - Programming Basics

Conventions: Exercise

• Which identifiers follow style conventions for Java?– myIdentifier

– _my_other_identifier

– totalValue

– totVal

– theSumOfAllTheValuesEnteredByTheUser

– MyClass

– my_class

– getValue

– GetValue

Page 30: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

30COMP-202 - Programming Basics

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

Page 31: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

31COMP-202 - Programming Basics

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

Page 32: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

32COMP-202 - Programming Basics

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

Page 33: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

33COMP-202 - Programming Basics

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

Page 34: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

34COMP-202 - Programming Basics

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;

Page 35: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

35COMP-202 - Programming Basics

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

Page 36: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

36COMP-202 - Programming Basics

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

Page 37: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

37COMP-202 - Programming Basics

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

Page 38: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

38COMP-202 - Programming Basics

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

Page 39: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

39COMP-202 - Programming Basics

Numeric Primitive Types

• The difference between the various numeric primitive types is their size, and therefore the values they can store:

double

float

long

int

short

byte

Type

64 bits

32 bits

64 bits

32 bits

16 bits

8 bits

Space

5.2

5.2f

5L

5

5

5

Literal

+/- 1.7 X 10308 (with 15 significant digits)

+/- 3.4 X 1038 (with 7 significant digits)

~ -9 X 1018

-2147483648

-32768

-128

Minimum

~ 9 X 1018

2147483647

32767

127

Maximum

Page 40: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

40COMP-202 - Programming Basics

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)

Page 41: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

41COMP-202 - Programming Basics

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'

Page 42: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

42COMP-202 - Programming Basics

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, ...

Page 43: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

43COMP-202 - Programming Basics

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!

Page 44: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

44COMP-202 - Programming Basics

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

Page 45: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

45COMP-202 - Programming Basics

Java Escape Sequences

• Some escape sequences in Java:

\b

\t

\n

\r

\"

\'

\\

Double quotation mark (String)

Carriage return

New line (line feed)

Tab

Backspace

Backslash

Single quotation mark (char)

Escape sequence Meaning

Page 46: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

46COMP-202 - Programming Basics

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

Page 47: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

47COMP-202 - Programming Basics

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 heredone = true;

Page 48: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

48COMP-202 - Programming Basics

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)

Page 49: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

49COMP-202 - Programming Basics

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

Page 50: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

50COMP-202 - Programming Basics

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()

Page 51: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

51COMP-202 - Programming Basics

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

Page 52: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

52COMP-202 - Programming Basics

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()

Page 53: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

53COMP-202 - Programming Basics

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

Page 54: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

54COMP-202 - Programming Basics

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);

Page 55: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

55COMP-202 - Programming Basics

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

Page 56: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

56COMP-202 - Programming Basics

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?

Page 57: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

57COMP-202 - Programming Basics

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

Page 58: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

58COMP-202 - Programming Basics

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

Page 59: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

59COMP-202 - Programming Basics

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

Page 60: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

60COMP-202 - Programming Basics

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

Page 61: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

61COMP-202 - Programming Basics

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 classpublic static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

// Write your program statements here

}}

Page 62: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

Part 3: Expressions

Page 63: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

63COMP-202 - Programming Basics

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: x + y

Subtraction: x – y

Multiplication: x * y

Division: x / y

Remainder: x % y

Negation: -x

Page 64: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

64COMP-202 - Programming Basics

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

Page 65: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

65COMP-202 - Programming Basics

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?

Page 66: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

66COMP-202 - Programming Basics

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

Page 67: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

67COMP-202 - Programming Basics

Operator Precedence Examples

• 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

Page 68: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

68COMP-202 - Programming Basics

Assignment Operator Precedence

• The assignment operator has a lower precedence than the arithmetic operators

answer = sum / 4 + MAX * lowest;

4

1 3 2

First, the expression on the right side of the = operator is evaluated

Then the result is stored in the variable on the left-hand side

Page 69: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

69COMP-202 - Programming Basics

Assignment Operator Sides

• The left-hand and right-hand sides of an assignment statement can contain the same variable:

count = count + 1; First, 1 is added to the original value of count; the result is stored in a temporary memory location

Then, the overall result is stored into count, overwriting the original value

• The fact that the assignment operator has lower precedence than arithmetic operators allows us to do this

Page 70: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

70COMP-202 - Programming Basics

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?

Page 71: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

71COMP-202 - Programming Basics

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

Page 72: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

72COMP-202 - Programming Basics

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)

Page 73: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

73COMP-202 - Programming Basics

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 tocount++;

which is equivalent tocount = 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

Page 74: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

74COMP-202 - Programming Basics

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!

Page 75: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

75COMP-202 - Programming Basics

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 statementtotal += 5;

is equivalent tototal = total + 5;

• Example 2: The statementresult *= count1 + count2;

is equivalent toresult = result * (count1 + count2);

Page 76: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

76COMP-202 - Programming Basics

Assignment Operators (2)

• In general, assignment operators have the formvariable op= expression;

which is equivalent tovariable = 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

Page 77: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

77COMP-202 - Programming Basics

Assignment Operators (3)

• There are many assignment operators, including the following:

Operator

*=

-=

/=

%=

Example

x *= y;

x -= y;

x /= y;

x %= y;

Equivalent to

x = x * y;

x = x - y;

x = x / y;

x = x % y;

+= x += y; x = x + y;

Page 78: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

78COMP-202 - Programming Basics

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

Page 79: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

79COMP-202 - Programming Basics

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 constantfinal 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

Page 80: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

80COMP-202 - Programming Basics

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 (_)

Page 81: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

81COMP-202 - Programming Basics

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

Page 82: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

82COMP-202 - Programming Basics

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 = πr2, 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

Page 83: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

Part 4: String Basics

Page 84: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

84COMP-202 - Programming 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

Page 85: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

85COMP-202 - Programming Basics

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

Page 86: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

86COMP-202 - Programming Basics

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!"

Page 87: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

87COMP-202 - Programming Basics

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!"

Page 88: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

88COMP-202 - Programming Basics

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

Page 89: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

89COMP-202 - Programming Basics

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()

Page 90: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

90COMP-202 - Programming Basics

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?

Page 91: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

91COMP-202 - Programming Basics

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 linetext = "message";

assigns the String value "message" to String variable text

Page 92: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

92COMP-202 - Programming Basics

String Caveats (2)

– Thus, if the lineSystem.out.println(text);

is executed next, the following will be displayed to the screen:message

– On the other hand, the linetext = message;

assigns the String value stored in String variable message (that is, the String "Hello!") to String variable text

– Thus, if the lineSystem.out.println(text);

is executed next, the following will be displayed to the screen:Hello!

Page 93: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

93COMP-202 - Programming Basics

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

Page 94: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

94COMP-202 - Programming Basics

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.");

Page 95: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

95COMP-202 - Programming Basics

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

Page 96: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

96COMP-202 - Programming Basics

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?

Page 97: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

97COMP-202 - Programming Basics

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?

Page 98: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

98COMP-202 - Programming Basics

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 (!)

Page 99: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

Part 5: Data Conversion

Page 100: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

100COMP-202 - Programming Basics

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

Page 101: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

101COMP-202 - Programming Basics

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

Page 102: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

102COMP-202 - Programming Basics

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

Page 103: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

103COMP-202 - Programming Basics

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

Page 104: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

104COMP-202 - Programming Basics

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

Page 105: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

105COMP-202 - Programming Basics

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

Page 106: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

106COMP-202 - Programming Basics

Arithmetic Promotion

• Arithmetic promotion happens automatically when operators in expressions convert their operands

(1) Arithmetic promotion to float

(2) Division

(3) Assignment conversion to double

(4) Assign result to kmPerLitre

double kmPerLitre;int km = 1000;float litres = 85.0f;kmPerLitre = km / litres;

Page 107: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

107COMP-202 - Programming Basics

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

Page 108: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

108COMP-202 - Programming Basics

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

Page 109: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

109COMP-202 - Programming Basics

Casting (3)

• Casting has higher precedence than the arithmetic operators

Only the value of a is cast; the value of b is not castThus, c now contains the value 9

The product of a and b is castThus, d now contains the value 10

double a;int b, c, d;

a = 3.5;b = 3;

c = (int)a * b;

d = (int)(a * b);

Page 110: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

110COMP-202 - Programming Basics

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

Page 111: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

111COMP-202 - Programming Basics

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

Page 112: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

112COMP-202 - Programming Basics

Conversion Examples

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;

y contains value 5

c contains value 12.3

c contains value 0.0

Code Fragment Result

Page 113: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

113COMP-202 - Programming Basics

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

Page 114: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

114COMP-202 - Programming Basics

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)

Page 115: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

115COMP-202 - Programming Basics

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"

Page 116: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

116COMP-202 - Programming Basics

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?

Page 117: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

117COMP-202 - Programming Basics

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"

Page 118: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

118COMP-202 - Programming Basics

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

Page 119: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

119COMP-202 - Programming Basics

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

Page 120: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

Part 6: Problem Solving

Page 121: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

121COMP-202 - Programming Basics

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

Page 122: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

Part 7: Exercises

Page 123: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

123COMP-202 - Programming Basics

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

Page 124: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

124COMP-202 - Programming Basics

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

Page 125: Unit 2: Programming Basics€¦ · C O M P 2 0 2 – I n t r o d u c t i o n t o C o m p u t i n g 1 COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables

CO

MP

202 – Introd

uction to C

omp

utin

g 1

125COMP-202 - Programming Basics

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