1 Program Elements -- Introduction zWe can now examine the core elements of programming zLecture focuses on: ydata types yvariable declaration and use.

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.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
ECE122 L2: Program Development February 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 2 Program Development.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
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.
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.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
Introduction to C Programming
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
Program Elements -- Introduction
Objectives You should be able to describe: Data Types
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
1 Course Lectures Available on line:
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.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Week 1 Algorithmization and Programming Languages.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Introduction to Java Java Translation Program Structure
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
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)
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.
White Space Spaces, blank lines, and tabs are collectively called white space and are used to separate words and symbols in a program Extra white space.
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.
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
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.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
Primitive Data Types 1 In PowerPoint, point at the speaker icon, then click the "Play" button.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
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.
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.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Escape Sequences What if we wanted to print the quote character?
IDENTIFIERS CSC 111.
Introduction to C++ Programming
Escape Sequences Some Java escape sequences: See Roses.java (page 68)
Objects and Primitive Data
Fundamentals 2.
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

1 Program Elements -- Introduction zWe can now examine the core elements of programming zLecture focuses on: ydata types yvariable declaration and use yoperators and expressions ydecisions and loops yinput and output

2 Primitive Data Types zA data type is defined by a set of values and the operators you can perform on them zEach value stored in memory is associated with a particular data type zThe Java language has several predefined types, called primitive data types zThe following reserved words represent eight different primitive types:  byte, short, int, long, float, double, boolean, char

3 Integers zThere are four separate integer primitive data types zThey differ by the amount of memory used to store them Type byte short int long Storage 8 bits 16 bits 32 bits 64 bits Min Value ,768 -2,147,483,648 < -9 x Max Value ,767 2,147,483,647 > 9 x 10 18

4 Floating Point zThere are two floating point types:  The float type stores 7 significant digits  The double type stores 15 significant digits Type float double Storage 32 bits 64 bits Approximate Min Value -3.4 x x Approximate Max Value 3.4 x x

5 Characters  A char value stores a single character from the Unicode character set zA character set is an ordered list of characters zThe Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters zIt is an international character set, containing symbols and characters from many world languages

6 Characters zThe ASCII character set is still the basis for many other programming languages zASCII is a subset of Unicode, 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,...

7 Boolean  A boolean value represents a true or false condition zThey 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

8 Wrappers zFor each primitive data type there is a corresponding wrapper class. For example: zWrapper classes are useful in situations where you need an object instead of a primitive type zThey also contain some useful methods Primitive Type int double char boolean Wrapper Class Integer Double Character Boolean

9 Variables zA variable is an identifier that represents a location in memory that holds a particular type of data zVariables must be declared before they can be used zThe syntax of a variable declaration is: data-type variable-name; zFor example: int total;

10 Variables zMultiple variables can be declared on the same line: int total, count, sum; zVariables can be initialized (given an initial value) in the declaration: int total = 0, count = 20; float unit_price = 57.25;  See Piano_Keys.java Piano_Keys.java

11 Assignment Statements zAn assignment statement takes the following form: variable-name = expression; zThe expression is evaluated and the result is stored in the variable, overwriting the value currently stored in the variable  See United_States.java United_States.java zThe expression can be a single value or a more complicated calculation

12 Constants zA constant is similar to a variable except that they keep the same value throughout their existence  They are specified using the reserved word final in the declaration zFor example: final double PI = ; final int STUDENTS = 25;

13 Constants zWhen appropriate, constants are better than variables because: ythey prevent inadvertent errors because their value cannot change zThey are better than literal values because: ythey make code more readable by giving meaning to a value ythey facilitate change because the value is only specified in one place

14 Input and Output zJava I/O is based on input streams and output streams zThere are three predefined standard streams:  The print and println methods write to standard output Stream System.in System.out System.err Purpose reading input writing output writing errors Default Device keyboard monitor

15 Input and Output zThe Java API allows you to create many kinds of streams to perform various kinds of I/O  To read character strings, we will convert the System.in stream to another kind of stream using: BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));  This declaration creates a new stream called stdin zObject creation in more detail later

16 Escape Sequences  See Echo.javaEcho.java zAn escape sequence is a special sequence of characters preceded by a backslash (\) zThey indicate some special purpose, such as: Escape Sequence \t \n \" \' \\ Meaning tab new line double quote single quote backslash

17 Buffers zAs you type, the characters are stored in an input buffer zWhen you press enter, the program begins processing the data zSimilarly, output information is temporarily stored in an output buffer  The output buffer can be explicitly flushed (sent to the screen) using the flush method  See Python.javaPython.java

18 Numeric Input  Converting a string that holds an integer into the integer value can be done with a method in the Integer wrapper class: value = Integer.parseInt (my_string); zA value can be read and converted in one line: num = Integer.parseInt (stdin.readLine());  See Addition.java and Addition2.javaAddition.java Addition2.java

19 Expressions zAn expression is a combination of operators and operands  The arithmetic operators include addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ) zOperands can be literal values, variables, or other sources of data zThe programmer determines what is done with the result of an expression (stored, printed, etc.)

20 Division  If the operands of the / operator are both integers, the result is an integer (the fractional part is truncated)  If one or more operands to the / operator are floating point values, the result is a floating point value  The remainder operator ( % ) returns the integer remainder after dividing the first operand by the second  The operands to the % operator must be integers  See Division.javaDivision.java zThe remainder result takes the sign of the numerator

21 Division Expression 17 / / 5 17 / / / % 2 14 % % 5 Result

22 Operator Precedence zThe order in which operands are evaluated in an expression is determined by a well-defined precedence hierarchy zOperators at the same level of precedence are evaluated according to their associativity (right to left or left to right) zParentheses can be used to force precedence zAppendix D contains a complete operator precedence chart for all Java operators

23 Operator Precedence zMultiplication, division, and remainder have a higher precedence than addition and subtraction zBoth groups associate left to right Expression: Order of evaluation: Result: / %

24 Operator Precedence Expression * 4 / 2 3 * (3 * 13) * (13 + 2) 4 * (11 - 6) * ( ) (5 * (4 - 1)) / 2 Result

25 The if Statement zThe Java if statement has the following syntax: if (condition) statement; zIf the boolean condition is true, the statement is executed; if it is false, the statement is skipped zThis provides basic decision making capabilities

26 The if Statement statement condition false true

27 Boolean Expressions  The condition of an if statement must evaluate to a true or false result zJava has several equality and relational operators:  See Temperature.javaTemperature.java Operator == != < <= > <= Meaning equal to not equal to less than less than or equal to greater than greater than or equal to

28 Block Statements zSeveral statements can be grouped together into a block statement zBlocks are delimited by braces zA block statement can be used wherever a statement is called for in the Java syntax  See Temperature2.java Temperature2.java

29 The if-else Statement  An else clause can be added to an if statement to make it an if-else statement: if (condition) statement1; else statement2; zIf the condition is true, statement1 is executed; if the condition is false, statement2 is executed  See Temperature3.java and Right_Triangle.java Temperature3.java Right_Triangle.java

30 The if-else Statement statement1 condition false true statement2

31 Nested if Statements  The body of an if statement or else clause can be another if statement zThese are called nested if statements  See Football_Choice.java Football_Choice.java  Note: an else clause is matched to the last unmatched if (no matter what the indentation implies)

32 The while Statement zA while statement has the following syntax: while (condition) statement; zIf the condition is true, the statement is executed; then the condition is evaluated again zThe statement is executed over and over until the condition becomes false

33 The while Statement statement condition false true

34 The while Statement  If the condition of a while statement is false initially, the statement is never executed  Therefore, we say that a while statement executes zero or more times  See Counter.java, Factors.java, and Powers_of_Two.javaCounter.javaFactors.java Powers_of_Two.java

35 Infinite Loops  The body of a while loop must eventually make the condition false zIf not, it is an infinite loop, which will execute until the user interrupts the program zThis is a common type of logical error -- always double check that your loops will terminate normally  See Forever.javaForever.java