Lecture 3: Variables and assignment

Similar documents
2: Basics of Java Programming

Chapter. Let's explore some other fundamental programming concepts

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

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

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

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

Basics of Java Programming variables, assignment, and input

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

objectives chapter Define the difference between primitive data and objects. Declare and use variables. Perform mathematical computations.

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

CSC 1051 Data Structures and Algorithms I

2 rd class Department of Programming. OOP with Java Programming

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

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

Chapter 2: Data and Expressions

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

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

ECE 122 Engineering Problem Solving with Java

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Algorithms and Conditionals

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

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CMPT 125: Lecture 3 Data and Expressions

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Table of Contents Date(s) Title/Topic Page #s. Abstraction

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

Java Basic Introduction, Classes and Objects SEEM

Declaration and Memory

CS 106 Introduction to Computer Science I

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Data Conversion & Scanner Class

Java Basic Introduction, Classes and Objects SEEM

Basics of Java Programming

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

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Getting started with Java

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

CS 112 Introduction to Programming

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

Conditional Statements

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

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Full file at

Building Java Programs

Building Java Programs

CS111: PROGRAMMING LANGUAGE II

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

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

TUGCE KEMEROZ - ASLI OZKAN - AYSE TARTAN. Week 12/02/ /02/2007 Lecture Notes:

Object-Oriented Programming

Visual C# Instructor s Manual Table of Contents

What did we talk about last time? Examples switch statements

Building Java Programs

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Selection Statements and operators

Selection and Repetition Revisited

4 Programming Fundamentals. Introduction to Programming 1 1

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

Introduction to Algorithms and Data Structures

Topic 4 Expressions and variables

Java I/O and Control Structures Algorithms in everyday life

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Java I/O and Control Structures

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Program Fundamentals

Chapter 2. Elementary Programming

CS11 Java. Fall Lecture 1

Chapter 6 Primitive types

Operators in java Operator operands.

Data Representation and Applets

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

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

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Chapter 2: Using Data

Data Representation and Applets

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Data Representation and Applets

Section 2: Introduction to Java. Historical note

CSE 142, Summer 2014

First Java Program - Output to the Screen

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Programming with Java

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

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

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

Selection Statements and operators

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

CSE 142, Summer 2015

Applets and the Graphics class

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

Chapter 2 Elementary Programming

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

Information Science 1

Transcription:

Lecture 3: Variables and assignment CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

Last time Lab 1: Learn about jgrasp - the programming environment that we will be using in this class Compile and run a java program Understand the relationship between a Java class name and the name of the.java file where the class is defined Practice using basic Java output statements and adding documentation (comments) to your source code. Learn about variables, string literals, concatenation. E.g., int x = 42, count = 100; "Many wise words" "Many " + " many wise words" "Many \"wise\" words" Explore Java syntax Experience some errors!

Character Strings A string literal is represented by putting double quotes around the text Examples: "This is a string literal." "123 Main Street" "X" Every character string is an object in Java, defined by the String class

The println Method In the Lincoln program we invoked the println method to print a character string The System.out object represents a destination (the monitor screen) to which we can send output System.out.println ("Whatever you are, be a good one."); object method name information provided to the method (parameters)

The print Method The System.out object has another method: print is similar to the println except that it does not advance to the next line Example: Countdown.java

//******************************************************************** // Countdown.java Author: Lewis/Loftus // // Demonstrates the difference between print and println. //******************************************************************** public class Countdown { //----------------------------------------------------------------- // Prints two lines of output representing a rocket 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!"); // appears on first output line System.out.println ("Houston, we have a problem."); } }

Output //******************************************************************** // Countdown.java Author: Lewis/Loftus // Three... Two... One... Zero... Liftoff! // Demonstrates Houston, the we difference have between a problem. print and println. //******************************************************************** public class Countdown { //----------------------------------------------------------------- // Prints two lines of output representing a rocket 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!"); // appears on first output line System.out.println ("Houston, we have a problem."); } }

String Concatenation The string concatenation operator (+) is used to append one string to the end of another "And one more " + "thing" It can also be used to append a number to a string A string literal cannot be broken across two lines in a program See Facts.java

//******************************************************************** // Facts.java Author: Lewis/Loftus // // Demonstrates the use of the string concatenation operator and the // automatic conversion of an integer to a string. //******************************************************************** public class Facts { //----------------------------------------------------------------- // Prints various facts. //----------------------------------------------------------------- public static void main (String[] args) { // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:"); continue System.out.println (); // A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12");

continue // A numeric value can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515); } } System.out.println ("Speed of ketchup: " + 40 + " km per year");

Output continue We present the following facts for your extracurricular edification: // A numeric value can be concatenated to a string Letters System.out.println the Hawaiian alphabet: ("Dialing 12 code for Antarctica: " + 672); Dialing code for Antarctica: 672 Year System.out.println which Leonardo da ("Year Vinci in invented which Leonardo the parachute: da Vinci 1515 invented " Speed of ketchup: 40 km per + "the year parachute: " + 1515); } } System.out.println ("Speed of ketchup: " + 40 + " km per year");

Escape Sequences What if we wanted to print the quote character? Let s try something like this System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you.");

Escape Sequences Some Java escape sequences: Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash See Roses.java

//******************************************************************** // Roses.java Author: Lewis/Loftus // // Demonstrates the use of escape sequences. //******************************************************************** public class Roses { //----------------------------------------------------------------- // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("Roses are red,\n\tviolets are blue,\n" + "Sugar is sweet,\n\tbut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tat this point in our " + "relationship."); } }

Output //******************************************************************** // Roses.java are Author: red, Lewis/Loftus // // Demonstrates Violets the use of are escape blue, sequences. //******************************************************************** Sugar is sweet, But I have "commitment issues", public class Roses { So I'd rather just be friends //----------------------------------------------------------------- At this point in our relationship. // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("Roses are red,\n\tviolets are blue,\n" + "Sugar is sweet,\n\tbut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tat this point in our " + "relationship."); } }

Quick Check Write a single println statement that produces the following output: "Thank you all for coming to my home tonight," he said mysteriously.

Quick Check Write a single println statement that produces the following output: "Thank you all for coming to my home tonight," he said mysteriously. System.out.println ("\"Thank you all for " + "coming to my home\ntonight,\" he said " + "mysteriously.");

Today: Problem Solving Create a program that will help us calculate a grade point average (GPA) given the number of quality points (QP) and the number of credits. The appropriate formula is GPA = QP / credits We assume A, B, C, D, F grading system.

For Example Course Credits Grade QPs Underwater Basket Weaving 3 A = 4 12 Main Line Boutiques 3 B = 3 9 Winning the Hoops Lottery 3 C = 2 6 Web Surfing 3 B = 3 9 Alg and Data Structures 4 A = 4 16 Totals 16 52 GPA = 52 / 16 = 3.25

Topic Thread 2.1 Character Strings 2.2 Variables, Assignment 2.3 Data Types, in particular int, double 2.4 Expressions (simple) 2.5 Data Conversion 2.6 Interactive Programs 5.1 Boolean Expressions 5.2 The if Statement 5.4 The while Statement

//********************************************** // GPA01.java // // Prints out a QPA //********************************************** public class GPA01 { public static void main (String[ ] args) { System.out.println ("Quality Points: 52"); System.out.println ("Credits: 16"); System.out.println ( \n\tgpa: 3.25"); } } The GPA Problem Solution 1 Not very exciting, is it? Let s add some storage (remember our model of computing)

Variables A variable is a name for a location in memory A variable must be declared by specifying the variable's name and the type of information that it will hold data type variable name int credits; int count, temp, result; Multiple variables can be created in one declaration

Variable Initialization A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; When a variable is referenced in a program, its current value is used.

Assignment Statement Changes the value of a variable The assignment operator is the = sign total = 55 - discount; The expression on the right is evaluated and the result is stored in the variable on the left The old value that was in total is overwritten See Geometry.java (page 68)

Assignment operator Assignment ( = ) copies the value of the right side into the memory location associated with the left side It does not (for primitive types) set up an ongoing equivalence int davesage = 21; int suesage; suesage = davesage; davesage = 22; System.out.println (davesage); // prints 22 System.out.println (suesage); // prints 21 Tracing program code is an important skill!!

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

Numeric Primitive Data Type Storage Min Value Max Value byte short int long 8 bits 16 bits 32 bits 64 bits -128-32,768-2,147,483,648 < -9 x 10 18 127 32,767 2,147,483,647 > 9 x 10 18 float double 32 bits 64 bits +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits

A variable is only declared once! A variable can be given an initial value in the declaration int sum = 0; declaration Later in the program the value of a variable can change: sum = 1; assignment

Strings are not primitive data We can still declare and use String variables: String message = Roses are red ; declaration And use assignment to change their values: message = message + \nviolets are blue ; assignment

//******************************************** // GPA02.java // // Prints out a GPA //******************************************** public class GPA02 { public static void main (String[ ] args) { int qp = 52; int credits = 16; double gpa = 3.25; Solution 2 Still not very exciting, is it? Let s add some processing } } System.out.println ("Quality Points: " + qp); System.out.println ("Credits: " + credits); System.out.println (); System.out.println ( \tgpa: " + gpa);

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

Division and Remainder If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals 8 / 12 equals 4 0 The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals 8 % 12 equals 2 8

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, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order

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

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

Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value)

Increment and Decrement The increment and decrement operators use only one operand The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The statement count++; is functionally equivalent to count = count + 1;

Increment and Decrement The increment and decrement operators can be applied in postfix form: or prefix form: count++ ++count When used as part of a larger expression, the two forms can have different effects Because of their subtleties, the increment and decrement operators should be used with care

//******************************************** // GPA03.java // Solution 3 // Prints out a GPA //******************************************** public class GPA03 { public static void main (String[ ] args) { int qp = 52; int credits = 16; A little more interesting but... What happened to the output? double gpa = qp / credits; System.out.println ("Quality Points: " + qp); System.out.println ("Credits: " + credits); System.out.println (); System.out.println ( \tgpa: " + gpa); } }

Summary Print/println String concatenation Escape sequences Variables Data types Assignment operator Arithmetic operators Operator precedence

Homework Review Sections 2.1-2.4 Always do all self-review exercises when you review material Do Exercises EX 2.6, 2.7, 2.8, 2.11 Read Sections 2.5, 2.6 to prepare for next class Some slides adapted from a presentation by Daniel Joyce and from the slides accompanying Java Software Solutions by Lewis & Loftus Caveman image is from http://www.toonpool.com/cartoons/primitive%20caveman%20words_25547#