Chapter 2: Beginning to Program

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Chapter 2 Elementary Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
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 Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte,
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
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.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
VARIABLES Introduction to Computer Science 1- COMP 1005, 1405 Instructor : Behnam Hajian
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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
1 Chapter 2 Elementary Programming. 2 Objectives  To write Java programs to perform simple calculations  To obtain input from the console using the.
Chapter 2 Elementary Programming
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
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.
Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
CS 201 Lecture 2: Elementary Programming Tarik Booker CS 201 California State University, Los Angeles.
Primitive Data Types and Operations F Introduce Programming with an Example F Identifiers, Variables, and Constants F Primitive Data Types –byte, short,
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.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
Chapter 2 Elementary Programming
Topic 2 Elementary Programming
Unit 2 Elementary Programming
Elementary Programming
Chapter 2 Elementary Programming
Lecture 3: Operators, Expressions and Type Conversion
Chapter 2 Elementary Programming
Tokens in C Keywords Identifiers Constants
Multiple variables can be created in one declaration
Chapter 2 Elementary Programming
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Elementary Programming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Numerical Data Types.
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
Fundamentals 2.
Chapter 2: Java Fundamentals
Lectures on Numerical Methods
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming
Chapter 2 Elementary Programming
Expressions and Assignment
CS2011 Introduction to Programming I Elementary Programming
Primitive Types and Expressions
Chapter 2 Primitive Data Types and Operations
Chapter 2 Elementary Programming
Presentation transcript:

Chapter 2: Beginning to Program CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified by Kris Brown, Ben Say, Wim Bohm 1

Motivations Solve practical problems programmatically Java primitive data types Strings Input/Output Constants 2

Variables A named container that holds a specific piece of data. Variables have a type (set of values). Some Java types are: int, double, char, String (more later)

Declaring Variables int x; // Declare x to be an // integer variable; double radius; // Declare radius to // be a double variable; char a; // Declare a to be a // character variable; String s; // Declare s to be a // String variable; 4

Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; s = ”Java”; // Assign “Java” to s 5

Declaring and Initializing in One Step int x = 1; double d = 1.4; String s = ”Java”; 6

Variable names A variable name is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). A variable name must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. A variable name cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words). A variable name cannot be true, false, or null. A variable name can be of any length. Which are valid variable names: _special Message message 1message class true 7

Numerical Data Types 8

Printing get the computer to print something to the console System.out.println(“Hello World”); get the computer to print something to the console println prints a line and adds a new line at the end print prints the line and continues on the same line use for DEBUGGING!!

Simple String Operations Concatenation: Use the “+” (plus sign) to concatenate strings System.out.println(mm + “ “ + yy);

Simple String Operations The length() method String theName = ”Donald Duck”; int len = theName.length(); What is returned by length() ? 11 (count the chars in theName)

Reading Input from the Console 1. Create a Scanner object Scanner input = new Scanner(System.in); 2. Use the method nextDouble() to obtain to a double value. For example, System.out.print("Enter a double value: "); double d = input.nextDouble(); Let’s play with IO in Eclipse 12

Reading Numbers from the Keyboard Scanner input = new Scanner(System.in); int value = input.nextInt(); 13

Variables // Compute the first area radius = 1.0; area = radius * radius * 3.14159; System.out.println("The area is ” + area + " for radius "+radius); // Compute the second area radius = 2.0; 14

Trace a Program Execution animation Trace a Program Execution allocate memory for radius public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } radius no value 15

Trace a Program Execution animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } memory radius no value area no value allocate memory for area 16

Trace a Program Execution animation Trace a Program Execution assign 20 to radius public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } radius 20.0 area no value 17

Trace a Program Execution animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } memory radius 20.0 area 1256.636 compute area and assign it to variable area 18

Trace a Program Execution animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } memory radius 20.0 area 1256.636 print a message to the console 19

Your Turn! Write code in which a String variable message contains “The number of rabbits is”. An integer variable num has a value of 129. Concatenate these variables into a String called report. Then print, using report: The number of rabbits is 129!!

Lecture 2 Operators, Expressions

Named Constants final datatype CONSTANTNAME = VALUE; final double PI = 3.14159; final int SIZE = 3; G=]final means “it cannot change" 22

Naming Conventions Choose meaningful and descriptive names. Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area. 23

Naming Conventions, cont. Class names: Capitalize the first letter of each word in the name. For example, the class name ComputeArea. Constants: Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE 24

Numeric Operators 25

PEMDAS What is it? Precedence order in arithmetic expressions: Parentheses Exponentiation Multiplication, Division Addition, Subtraction 2 + 3 * 5 = ? (2 + 3) * 5 = ? Operators at the same level (*, /) and (+,-) go from left to right (left associative (+,-) and left associative (*,/)) 2 - 3 + 5 = ? 12 / 3 * 6 = ?

Integer Division +, -, *, /, and % 5 / 2 yields an integer 2. 5.0 / 2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the (integer) division) 27

Modulo/Remainder Operator Remainder is very useful in programming. An even number % 2 is 0 and an odd number % 2 is 1. Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? Tuesday; use the following expression: Which day is Sunday? 28

Relationship of / and % For all integers p and q : p = (p/q)*q + p%q Terminology: p: dividend q: divisor p/q: quotient p%q: remainder The remainder is negative only if the dividend is negative. Integer division rounds towards 0: 3/2 = 1,  -3/2 = -1

Exponent Operations // these are (Math)library methods System.out.println(Math.pow(2, 3)); // Displays 8.0 System.out.println(Math.pow(4, 0.5)); // Displays 2.0 System.out.println(Math.pow(2.5, 2)); // Displays 6.25 System.out.println(Math.pow(2.5, -2)); // Displays 0.16 30

Number Literals A literal is a constant value that appears directly in the program. For example, 34, 1,000,000, and 5.0 are literals in the following statements:   int i = 34; long x = 1000000; double d = 5.0; 31

Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. byte b1 = 100; byte b2 = 1000; // compiler error, WHY? An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231–1 (2147483647). A compilation error would occur if the literal were too large for the variable to hold. For example, the statement byte b = 1000 would cause a compilation error, because 1000 cannot be stored in a variable of the byte type. To denote an integer literal of the long type, append it with the letter L or l. L is preferred because l (lowercase L) can easily be confused with 1 (the digit one). 32

Floating-Point Literals Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. double d0 = 0.5; double d1 = 100.2d; double d2 = 100.1D; float f1 = 100.2f; float f2 = 100.3F; For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number. 33

double vs. float The double type values are more accurate than the float type values. For example, System.out.println("1.0 / 3.0 is " + 1.0 / 3.0); System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F); 34

Scientific Notation Floating-point literals can also be specified in scientific notation, for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and 1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent and it can be either in lowercase or uppercase. 35

Numeric data types Name Storage byte 8 bit signed integer short long 64 bit signed integer float 32 bit floating point number double 64 bit floating point number Name Storage Size byte short int long float double For value ranges see book. E.g.: byte range: -128 to 127 int range: ~ 2E10 to 2E10

Arithmetic Expressions is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) 37

How to Evaluate an Expression Apply the precedence and associativity rules discussed earlier To determine the order of evaluation. Parentheses ( ) allow changing the order of evaluatioin 38

Full parenthesization In full parenthesization every sub expression is parenthesized. It explicitly defines the evaluation order in an expression: 5 * (3 – 2) - 3 + 4  (((5 * (3-2)) – 3) + 4)

Augmented Assignment Operators 40

Increment and Decrement Operators 41

Increment and Decrement Operators, cont. 42

Increment and Decrement Operators, cont. Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i. 43

Assignment Expressions and Assignment Statements Prior to Java 2, all the expressions can be used as statements. Since Java 2, only the following types of expressions can be statements: variable op= expression; // Where op is +, -, *, /, or % ++variable; variable++; --variable; variable--; (because they are implicit assignment statements) 44

Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (fraction part is truncated) What is wrong? int x = 5 / 2.0; 45

***Conversion Rules*** When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules:   1.    If one of the operands is double, the other is converted into double. 2.    Otherwise, if one of the operands is float, the other is converted into float. 3.    Otherwise, if one of the operands is long, the other is converted into long. 4.    Otherwise, both operands are converted into int. So a byte + byte is equivalent to int + int Java has no byte (or short) + Important Slide!! Everyone forgets this!! Java automatically converts up, not down. Java doesn’t like to lose information. 46

Casting in an Augmented Expression In Java, an augmented expression of the form x1 op= x2 is implemented as x1 = (T)(x1 op x2), where T is the type for x1. Therefore, the following code is correct. int sum = 0; sum += 4.5; // sum becomes 4 after this statement // is equivalent to sum = (int)(sum + 4.5). Don’t go overboard with this!! Use clear and simple typing / casting. 47

Common Errors and Pitfalls Common Error 1: Undeclared/Uninitialized Variables and Unused Variables Common Error 2: Integer Overflow Common Error 3: Unintended Integer Division Common Error 4: Round-off Errors 48

Common Error 1: Undeclared/Uninitialized Variables and Unused Variables double interestRate = 0.05; double interest = interestrate * 45; 49

Common Error 2: Integer Overflow int value = 2147483647 + 1; // value will actually be -2147483648 50

Common Error 3: Unintended Integer Division 51

Your Turn! Write a program that stores the remainder of dividing the integer variable i by integer variable j in an integer variable named k. Use a Scanner object to get those variables from a user at the keyboard. Print k to the console. Enter i: Enter j: Result k:

printf You can format your decimal numbers using, for example, the following: System.out.printf("Total is: $%,.2f%n", dblTotal); You will learn about printf in recitation. THIS IS NOT AT ALL EXPLAINED!! $ not part of the format specifier use of , flag: , separated 3 digit groups meaning of .2 two decimal digit and float/ double type f meaning of %n newline If we do this shouldn’t we also talk about %d, %s, or: I found a useful, short, pdf about printf

NOTE Calculations involving floating-point numbers are approximate because these numbers are not stored with complete accuracy. For example, System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); displays 0.5000000000000001, not 0.5, and System.out.println(1.0 - 0.9); displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result. 54

Common Error 4: Round-off Errors System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); System.out.println(1.0 - 0.9); 55