Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.

Slides:



Advertisements
Similar presentations
CSci 1130 Intro to Programming in Java
Advertisements

Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Constants and Data Types Constants Data Types Reading for this class: L&L,
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
2 Data and Expressions Software Solutions Lewis & Loftus java
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
ECE122 L2: Program Development February 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 2 Program Development.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
1 Character Strings and Variables Character Strings Variables, Initialization, and Assignment Reading for this class: L&L,
String Escape Sequences
Expressions, Data Conversion, and Input
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
CSCI 1100/1202 January 16, Why do we need variables? To store intermediate results in a long computation. To store a value that is used more than.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Program Statements Primitive Data Types and Strings.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCopyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; Copyright © 2012 Pearson Education,
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Chapter 2 Data and Expressions Part One. © 2004 Pearson Addison-Wesley. All rights reserved2-2/29 Data and Expressions Let's explore some other fundamental.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Chapter 2 Data and Expressions Java Software Solutions Foundations of Program Design 1.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: –character strings –primitive data –the declaration.
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
2-1 Character Strings A string of characters can be represented as a string literal by putting double quotes around the text: Examples: "This is a string.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
1 Data and Expressions Chapter 2 In PowerPoint, click on the speaker icon then the “play” button to hear audio narration.
Primitive Data Types 1 In PowerPoint, point at the speaker icon, then click the "Play" button.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Chapter 2 Data and Expressions 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
© 2006 Pearson Education Chapter 2: Objects and Primitive Data Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 2 Data and Expressions
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
CSC 1051 – Data Structures and Algorithms I
Data Conversion & Scanner Class
CSC 1051 – Data Structures and Algorithms I
Multiple variables can be created in one declaration
Chapter 2 Data and Expressions
Escape Sequences What if we wanted to print the quote character?
Data and Expressions Part One
Chapter 2 Data and Expressions.
Objects and Primitive Data
Chapter 2 Create a Chapter 2 Workspace Create a Project called Notes
Chapter 2 Data and Expressions.
CSC 1051 – Data Structures and Algorithms I
Instructor: Alexander Stoytchev
Presentation transcript:

Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs

Character Strings A string of characters can be represented as a string literal by putting double quotes around the text: System.out.println("This is a string literal."); Examples: "123 Main Street" "X"

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 provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // 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!"); System.out.println ("Houston, we have a problem."); }

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

String Concatenation The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation

String Concatenation If both operands are numeric, it adds them The + operator is evaluated left to right, but parentheses can be used to force the order System.out.println ("24 and 45 concatenated: " ); System.out.println ("24 and 45 added: " + ( ));

Exercise What output is produced by the following program statements? A. System.out.println("6" +"7" +8 +9); B. System.out.println(6 +7 +"8" +"9"); C. System.out.println("6" +"7" +(8 +9));

Escape Sequences What if we wanted to print the quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you.");

Escape Sequences 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 \" \' \\ Meaning backspace tab newline double quote single quote backslash

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // 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."); }

Variables

A variable is a name for a location in memory. Variables in a program are used to store data such as numbers and letters. A variable must be declared by specifying the variable's name and the type of information that it will hold int total; data type variable name int count, temp, result; Multiple variables can be created in one declaration

Naming Conventions Style for names of variables –Start with a lower-case letter, then capitalize the first letter of any subsequent word in the name. For example, int radius; int currentSpeed; –The names should be nouns or noun phrases. –One-character variable names should be avoided except for temporary and loop variables.

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

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

Constants A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence Naming convention: upper case for constants In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69;

Constants The compiler will issue an error if you try to change the value of a constant – the only valid place to change their value is in the initial assignment Constants give meaning to otherwise unclear literal values. For example, MAX_NUM_STUDENTS Second, they facilitate program maintenance. If a constant is used in multiple places, its value need only be updated in one place

Primitive Data Types

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 character type: char One boolean type: boolean

Numeric Primitive Data The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long Min Value ,768 -2,147,483,648 < -9 x Max Value ,767 2,147,483,647 > 9 x Common used type

Floating Point Types Type float double Min Value +/- 3.4 x with 7 significant digits +/- 1.7 x with 15 significant digits Max Value For example, double score; score = 78.4; Common used type

Characters A char variable stores a single character Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' ';

Character Sets A character set is an ordered list of characters, with each character corresponding to a unique number A char variable in Java can store any character from the Unicode character set The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters

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: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … backspace, tab,...

Boolean A boolean value represents a true or false condition The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable can also be used to represent any two states, such as a light bulb being on or off

Exercises Declare an integer variable cardsInHand and initialize it to 13. Declare a double variable temperature and initialize it to 98.6.

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%

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

Operator Precedence Operators can be combined into complex expressions result = total + count / max - offset; 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 2341 a / (b * (c + (d - e))) 4123

Exercises Given the declarations below, find the result of each expression (in a Java program). int a = 3, b = 10, c = 7; a / b b / a b% a

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 Then the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest; 1432

Exercises Given two integer variables matricAge and gradAge, write a statement that gives gradAge a value that is 4 more than the value of matricAge.

Assignment Operators Often we perform an operation on a variable, and then store the result back into that variable. Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count;

Assignment Operators There are many assignment operators in Java, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y

Assignment Operators The right hand side of an assignment operator can be a complex expression For example, result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num);

Interactive Programs

Programs generally need input on which to operate - The Scanner class provides convenient methods for reading input values of various types A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard Keyboard input is represented by the System.in object

Reading Input The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in); The new operator creates the Scanner object Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine();

Reading Input The nextLine method reads all of the input until the newline character (\n, end of the line) is found The Scanner class is part of the java.util class library, and must be imported into a program to be used In the beginning of your program, import java.util.Scanner;

Input Tokens Unless specified otherwise, white space is used to separate the elements (called tokens) of the input - White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types

Copyright © 2012 Pearson Education, Inc. //******************************************************************** // GasMileage.java Author: Lewis/Loftus // // Demonstrates the use of the Scanner class to read numeric data. //******************************************************************** import java.util.Scanner; public class GasMileage { // // Calculates fuel efficiency based on values entered by the // user. // public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); continue

Copyright © 2012 Pearson Education, Inc. continue System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); }

Readings and Assignments Reading: Chapter , 2.6 Lab Assignment: Java Lab 2 Self-Assessment Exercises: –Self-Review Questions SR2.4, 2.5, 2.6, 2.25, 2.27, 2.30 –After Chapter Exercises EX2.2, 2.5, 2.8, 2.9, 2.11

Grading Guidelines for Java Labs and Lab Exams 80% - Functionality: Runs correctly, generating correct outputs. A program that does not compile will result in a zero. 10% - Style: Use consistent indentation to emphasize block structure; variables have meaningful names. 10% - Comments: Comment major code segments adequately