CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.

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.
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
String Escape Sequences
Expressions, Data Conversion, and Input
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
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.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
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.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
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.
Mathematical Calculations in Java Mrs. G. Chapman.
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,
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
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.
Mathematical Calculations in Java Mrs. C. Furman.
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Doing math In java.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
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.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
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.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
© 2006 Pearson Education Chapter 2: Objects and Primitive Data Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by.
© 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 02 Data and Expressions.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Type Conversion, Constants, and the String Object
Escape Sequences What if we wanted to print the quote character?
Increment and Decrement
Lecture 3 Expressions Richard Gesick.
Objects and Primitive Data
Arithmetic Expressions & Data Conversions
Chapter 2 Variables.
Expressions and Assignment
Data Types and Expressions
Instructor: Alexander Stoytchev
Data Types and Expressions
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

CSci 142 Data and Expressions

2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data conversions

3 Character Strings  A String consists of zero or more characters  Represent a String literal with double quotes "This is a string literal." "123 Main Street" "X" ""  this is called an empty String  Every string is an object in Java, defined by the String class

Printing Strings  The ConsoleProgram class has two methods for printing:  print  println  Both accept String arguments  println inserts a line break, while print does not 4

5 Printing Strings println ("Whatever you are, be a good one."); method name information provided to the method (argument) print ("Whatever you are, "); print ("be a good one.");

String Concatenation  Concatenation is appending one string to the end of another  "Peanut butter " + "and jelly"  A string literal cannot be broken across two lines in a program 6

7 The + Operator  The + operator can be used for concatenating Strings or adding numbers  If either or both operands are Strings, String concatenation is performed  println(“Good ” “U”);  If both operands are numeric, it adds them  println(3+6);  The + operator is evaluated left to right, but parentheses can be used to force the order  println(“Hi ” );  println(“Hi ” + (2 + 3));

8 Escape Sequences  How would we print the quote ( " ) character?  The following line would confuse the compiler println ("I said "Hi" to you.");  An escape sequence is a series of characters that represents a special character  Begins with a backslash ( \ ) println ("I said \"Hi\" to you.");

9 Escape Sequences Escape Sequence Character \nNewline \”Double quote \’Single quote \\Backslash \tTab

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

Variable names  May contain letters or numbers, but may not start with a number  you2 - valid  2you - not valid  May not contain a space or any special characters, except the underscore (_)  why_not - valid  why not? - not valid  Should use camel case  gpa, numCredits, totalClassCount 11

12 Variable Initialization  A variable must be initialized before it can be used  A variable can be initialized in the declaration  A variable can be initialized after it is declared double sum = 0.0; int base = 32, max = 149; double sum; sum = 0.0; int base, max; base = 32; max = 149;

Variable Assignment  An assignment statement changes the value of a variable  Read “=” as gets  total gets 55  The value that was in total is overwritten  Values assigned to a variable must be consistent with the variable's declared type  Most current value of a variable is used 13 total = 55; int base = 32; println(base); base = 45; println(base);

14 Constants  A constant is similar to a variable except that its value cannot change during program execution  As the name implies, it is constant, not variable  The compiler will issue an error if you try to change the value of a constant  In Java, use the keyword final to declare a constant final int MIN_HEIGHT = 69;

15 Why Constants are Cool  Give meaning to otherwise unclear literal values  MAX_LOAD means more than the literal 250  They facilitate program maintenance  If a constant is used in multiple places, its value need only be updated once  They formally establish that a value should not change, avoiding inadvertent errors

16 Primitive Data TypesUsed for byte, short, int, long Integers (whole numbers) float, double Decimal (floating point) numbers char A single character boolean Boolean (true or false) values

17 Numeric Primitive Data  The difference between the various numeric primitive types is their size Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value ,768 -2,147,483,648 < -9 x /- 3.4 x with 7 significant digits +/- 1.7 x with 15 significant digits Max Value ,767 2,147,483,647 > 9 x 10 18

18 char  A char variable stores a single character  Characters are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n'  Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; Note that a character variable can hold only one character, while a String can hold zero or more characters.

19 boolean  A boolean value represents true or false  The reserved words true and false are the only valid values for a boolean type boolean done = false;

20 Expressions  Arithmetic expressions use arithmetic operators: Addition+ Subtraction- Multiplication* Division/ Remainder%  If either or both operands used by an arithmetic operator are floating point (decimal), then the result is a floating point

21 Division and Remainder  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 into the first 14 / 3 equals 8 / 12 equals 14 % 3 equals 8 % 12 equals

22 Operator Precedence  Operators can be combined into complex expressions result = total + count / max - offset;  Operations have a well-defined precedence 1.Parentheses 2.Multiplication, division, and remainder 3.Addition, subtraction, and string concatenation 4.Assignment  Arithmetic operators with the same precedence are evaluated from left to right

23 Example The expression is evaluated and the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest; 1432

Practice int a=3, b=5, c=2; int answer; answer = a * b - c; answer = b + a * c; answer = b / a; answer = a / b; answer = b % a; answer = a % b; answer = b - a * b - c; answer = b - a / c; answer = (b - a) / c; answer = a * (b + c); 24

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

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

27 Assignment Operators  Often we perform an operation on a variable, and then store the result back into that variable  Example:  num = num + count;  This can be written using an assignment operator:  num += count;

28 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

29 Data Conversion  Sometimes it is convenient to convert data from one type to another  These conversions do not change the type of a variable or the value that's stored in it  They only convert a value as part of a computation  Conversions must be handled carefully to avoid losing information

30 Data Conversion  widening conversions  Go from a small data type to a larger one  Example: short to an int  Safe  narrowing conversions  Go from a large data type to a smaller one  Example: int to a short  Can lose information  Types of conversion  Assignment conversion  Data conversion  Casting byte short int long float double widening conversions narrowing conversions

31 Assignment Conversion  Assignment conversion occurs when a value of one type is assigned to a variable of another double money; int dollars = 5; money = dollars;  Only widening conversions can happen via assignment  The value and type of dollars did not change converts the value in dollars to a float

32 Data Conversion  Promotion happens automatically in certain expressions  Example double sum = 5.0; int count = 3; double result = sum / count; count is Temporarily converted to a double

33 Casting  Casting is the most powerful, and dangerous, technique for conversion  May be used for both widening and narrowing conversions  To cast, the type is put in parentheses in front of the value being converted  Example: int total=3, count=2; result = (double)total / count;

34 Practice 1.iResult = num1 / num4; 2.dResult = num1 / num4; 3.iResult = num3 / num4; 4.dResult = num3 / num4; 5.dResult = val1 / num4;  Given the following declarations, what result is stored in each of the statements? int iResult, num1=25, num2=40, num3=17, num4=5; double dResult, val1=17.0, val2=12.78; 6.dResult = (double)num1 / num2; 7.dResult = num1 / (double)num2; 8.iResult = (int)(val1 / num4); 9.dResult = (int)((double)num1/num2); 10.iResult = num3%num4;