1 Variables b A variable is a name for a location in memory b A variable must be declared, specifying the variable's name and the type of information that.

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
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
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”
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.
Chapter Day 4. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 4 Return Signed Contracts Questions from last Class?? Problem set 1 Posted.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
Expressions, Data Conversion, and Input
Chapter 2: Objects and Primitive Data Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
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.
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCopyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
1 The String Class Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks,
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.
1 Objects and Primitive Data  Now we can explore some more fundamental programming concepts  Chapter 2 focuses on: predefined objects primitive data.
Chapter 2 Data and Expressions. © 2004 Pearson Addison-Wesley. All rights reserved2-2 Data and Expressions Let's explore some other fundamental programming.
_Introduction elsaddik CSI 1102 Introduction to Software Design Prof. Dr. Abdulmotaleb El Saddik Multimedia.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 2: Objects and Primitive Data Presentation slides for Java Software Solutions for AP* Computer.
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
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.
1 Lecture 2 b declaration and use of variables b expressions and operator precedence b introduction to objects b class libraries b flow of control b decision-making.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
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 Introduction to Graphics b The last one or two sections of each chapter of the textbook focus on graphical issues b Most computer programs have graphical.
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.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
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.
Chapter 2: Objects and Primitive Data Lian Yu Department of Computer Science and Engineering Arizona State University Tempe, AZ
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.
© 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)
Objects and Classes A class An object (the concept) (the realization)
Multiple variables can be created in one declaration
Escape Sequences What if we wanted to print the quote character?
Chapter 2 Data and Expressions.
Objects and Primitive Data
Chapter 2 Data and Expressions.
Chapter 2: Objects and Primitive Data
Chapter 2: Objects and Primitive Data
Presentation transcript:

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

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

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

Constants b A constant is an identifier that is similar to a variable except that it holds one value for its entire existence b The compiler will issue an error if you try to change a constant  In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; b Constants: give names to otherwise unclear literal valuesgive names to otherwise unclear literal values facilitate changes to the codefacilitate changes to the code prevent inadvertent errorsprevent inadvertent errors

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

Numeric Primitive Data b The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double 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

7 Characters  A char variable stores a single character from the Unicode character set b A character set is an ordered list of characters, and each character corresponds to a unique number b The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters b It is an international character set, containing symbols and characters from many world languages b Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n'

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

Arithmetic Expressions b An expression is a combination of operators and operands b Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition+ Subtraction- Multiplication* Division/ Remainder% b If either or both operands to an arithmetic operator are floating point, 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) b 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 b Operators can be combined into complex expressions result = total + count / max - offset; b Operators have a well-defined precedence which determines the order in which they are evaluated b Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation b Arithmetic operators with the same precedence are evaluated from left to right b Parentheses can always be used to force the evaluation order

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

Assignment Revisited b 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

Assignment Revisited b 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 Then the result is stored back into count (overwriting the original value) count = count + 1;

Data Conversions b Sometimes it is convenient to convert data from one type to another b For example, we may want to treat an integer as a floating point value during a computation b Conversions must be handled carefully to avoid losing information  Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int )  Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short )

Data Conversions b In Java, data conversions can occur in three ways: assignment conversionassignment conversion arithmetic promotionarithmetic promotion castingcasting b Assignment conversion occurs when a value of one type is assigned to a variable of another b Only widening conversions can happen via assignment b Arithmetic promotion happens automatically when operators in expressions convert their operands

Data Conversions b Casting is the most powerful, and dangerous, technique for conversion b Both widening and narrowing conversions can be accomplished by explicitly casting a value b To cast, the type is put in parentheses in front of the value being converted  For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total : result = (float) total / count;

18 Characters b The ASCII character set is older and smaller than Unicode, but is still quite popular b 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, … &, |, \, … carriage return, tab,...

Creating Objects b A variable either holds a primitive type, or it holds a reference to an object b A class name can be used as a type to declare an object reference variable String title; b No object has been created with this declaration b An object reference variable holds the address of an object b The object itself must be created separately

Creating Objects  We use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object b Creating an object is called instantiation b An object is an instance of a particular class

Creating Objects  Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; b This is special syntax that only works for strings b Once an object has been instantiated, we can use the dot operator to invoke its methods title.length()

String Methods  The String class has several methods that are useful for manipulating strings  Many of the methods return a value, such as an integer or a new String object

23 The String Class  Every character string is an object in Java, defined by the String class  Every string literal, delimited by double quotation marks, represents a String object b The string concatenation operator (+) is used to append one string to the end of another b It can also be used to append a number to a string b A string literal cannot be broken across two lines in a program

24 String Concatenation b The plus operator (+) is also used for arithmetic addition b The function that the + operator performs depends on the type of the information on which it operates b If both operands are strings, or if one is a string and one is a number, it performs string concatenation b If both operands are numeric, it adds them b The + operator is evaluated left to right b Parentheses can be used to force the operation order

25 Escape Sequences b What if we wanted to print a double quote character? b 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."); b An escape sequence is a series of characters that represents a special character  An escape sequence begins with a backslash character ( \ ), which indicates that the character(s) that follow should be treated in a special way System.out.println ("I said \"Hello\" to you.");

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

Class Libraries b A class library is a collection of classes that we can use when developing programs b There is a Java standard class library that is part of any Java development environment b These classes are not part of the Java language per se, but we rely on them heavily  The System class and the String class are part of the Java standard class library b Other class libraries can be obtained through third party vendors, or you can create them yourself

Packages b The classes of the Java standard class library are organized into packages b Some of the packages in the standard class library are: Package java.lang java.applet java.awt javax.swing java.net java.util Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities

The import Declaration b When you want to use a class from a package, you could use its fully qualified name java.util.Random b Or you can import the class, then just use the class name import java.util.Random; b To import all classes in a particular package, you can use the * wildcard character import java.util.*;

The import Declaration  All classes of the java.lang package are automatically imported into all programs  That's why we didn't have to explicitly import the System or String classes in earlier programs

HTML b Here is an example of HTML page: HTML example page My first HTML page HTML is a briliant idea. Don't you think so? Here is a nice picture:

Applets  A Java application is a stand-alone program with a main method (like the ones we've seen so far) b An applet is a Java program that is intended to transported over the web and executed using a web browser b An applet can also be executed using the appletviewer tool of the Java Software Development Kit  An applet doesn't have a main method b Instead, there are several special methods that serve specific purposes  The paint method, for instance, is automatically executed and is used to draw the applets contents

Applets  The paint method accepts a parameter that is an object of the Graphics class  A Graphics object defines a graphics context on which we can draw shapes and text  The Graphics class has several methods for drawing shapes b The class that defines the applet extends the Applet class b This makes use of inheritance, an object-oriented concept explored in more detail later

Applets b An applet is embedded into an HTML file using a tag that references the bytecode file of the applet class b It is actually the bytecode version of the program that is transported across the web b The applet is executed by a Java interpreter that is part of the browser

Drawing Shapes  Let's explore some of the methods of the Graphics class that draw shapes in more detail b A shape can be filled or unfilled, depending on which method is invoked b The method parameters specify coordinates and sizes b Recall that the Java coordinate system has the origin in the upper left corner b Many shapes with curves, like an oval, are drawn by specifying its bounding rectangle b An arc can be thought of as a section of an oval

Drawing a Line X Y page.drawLine (10, 20, 150, 45); page.drawLine (150, 45, 10, 20); or

Drawing a Rectangle X Y page.drawRect (50, 20, 100, 40);

Drawing an Oval X Y page.drawOval (175, 20, 50, 80); boundingrectangle

The Color Class  A color is defined in a Java program using an object created from the Color class  The Color class also contains several static predefined colors b Every graphics context has a current foreground color b Every drawing surface has a background color

Applet example import java.applet.Applet; import java.awt.*; public class Applet1 extends Applet { public void paint(Graphics g) { g.setColor(Color.orange); g.fillOval(50, 50, 100, 100); g.setColor(Color.green); g.drawRect(90, 90, 20, 20); }

Flow of Control b Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written b Some programming statements modify that order, allowing us to: decide whether or not to execute a particular statement, ordecide whether or not to execute a particular statement, or perform a statement over and over repetitivelyperform a statement over and over repetitively b The order of statement execution is called the flow of control

Conditional Statements b A conditional statement lets us choose which statement will be executed next b Therefore they are sometimes called selection statements b Conditional statements give us the power to make basic decisions b Java's conditional statements are the if statement, the if-else statement, and the switch statement

43 The if Statement b The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.

The if Statement b An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); First, the condition is evaluated. The value of sum is either greater than the value of MAX, or it is not. If the condition is true, the assignment statement is executed. If it is not, the assignment statement is skipped. Either way, the call to println is executed next.

Logic of an if statement condition evaluated false statement true

46 Boolean Expressions b A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to  Note the difference between the equality operator ( == ) and the assignment operator ( = )

47 The if-else Statement b An else clause can be added to an if statement to make it an if-else statement: if ( condition ) statement1; else statement2; b If the condition is true, statement1 is executed; if the condition is false, statement2 is executed b One or the other will be executed, but not both

Logic of an if-else statement condition evaluated statement1 true false statement2

49 Block Statements b Several statements can be grouped together into a block statement b A block is delimited by braces ( { … } ) b A block statement can be used wherever a statement is called for in the Java syntax b For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements

50 Nested if Statements b The statement executed as a result of an if statement or else clause could be another if statement b These are called nested if statements b An else clause is matched to the last unmatched if (no matter what the indentation implies)

51 If example b Finding minimum of three numbers: if (num1 < num2) if (num1 < num3) min = num1; else min = num3; else // num1 >= num2 if (num2 < num3) min = num2; else min = num3;

Comparing Characters b We can use the relational operators on character data b The results are based on the Unicode character set b The following condition is true because the character '+' comes before the character 'J' in Unicode: if ('+' < 'J') System.out.println ("+ is less than J"); b The uppercase alphabet (A-Z) and the lowercase alphabet (a-z) both appear in alphabetical order in Unicode

Comparing Strings b Remember that a character string in Java is an object b We cannot use the relational operators to compare strings  The equals method can be called on a string to determine if two strings contain exactly the same characters in the same order  The String class also contains a method called compareTo to determine if one string comes before another alphabetically (as determined by the Unicode character set)

Comparing Floating Point Values  We also have to be careful when comparing two floating point values ( float or double ) for equality  You should rarely use the equality operator ( == ) when comparing two floats b In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal b Therefore, to determine the equality of two floats, you may want to use the following technique: if (Math.abs (f1 - f2) < ) System.out.println ("Essentially equal.");