CEN 414 Java Programming

Similar documents
Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming

Chapter 2. Elementary Programming

Chapter 2 ELEMENTARY PROGRAMMING

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2 Elementary Programming

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

JAVA Programming Concepts

Datatypes, Variables, and Operations

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Elementary Programming

Full file at

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Chapter 2 Primitive Data Types and Operations

CS110: PROGRAMMING LANGUAGE I

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Programming with Java

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Zheng-Liang Lu Java Programming 45 / 79

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Chapter 2 Primitive Data Types and Operations

Computer System and programming in C

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Chapter 2: Data and Expressions

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

3. Java - Language Constructs I

Basic Computation. Chapter 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Chapter 2: Data and Expressions

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Welcome to the Primitives and Expressions Lab!

Basics of Java Programming

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Primitive Data, Variables, and Expressions; Simple Conditional Execution

COMP 202 Java in one week

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

double float char In a method: final typename variablename = expression ;

COMP 202. Java in one week

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Chapter 2. Elementary Programming. Program Listings

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data Types and the while Statement

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

Full file at

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

COMP Primitive and Class Types. Yi Hong May 14, 2015

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Data Conversion & Scanner Class

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Computational Expression

ECE 122 Engineering Problem Solving with Java

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Section 2.2 Your First Program in Java: Printing a Line of Text

Reserved Words and Identifiers

Basic Computation. Chapter 2

Eng. Mohammed S. Abdualal

Chapter 2: Data and Expressions

Objectives. In this chapter, you will:

COMP 202 Java in one week

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

Big Java. Fifth Edition. Chapter 3 Fundamental Data Types. Cay Horstmann

Visual C# Instructor s Manual Table of Contents

BASIC ELEMENTS OF A COMPUTER PROGRAM

Program Fundamentals

More Programming Constructs -- Introduction

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CMPT 125: Lecture 3 Data and Expressions

A variable is a name for a location in memory A variable must be declared

Chapter 2: Review Exercise Solutions R2.1

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

COMP-202: Foundations of Programming

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

I. Variables and Data Type week 3

Transcription:

CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang

WEEK 2 ELEMENTARY PROGRAMMING 2

Computing the Area of a Circle 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); } } allocate memory for radius radius no value allocate memory for area area no value 3

Computing the Area of a Circle public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20; radius area 20 no value assign 20 to radius // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } 4

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

Computing the Area of a Circle public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20; radius area memory 20 1256.636 // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } print a message to the console String concatenation operator 6

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: "); Scanner input = new Scanner(System.in); double d = input.nextdouble(); 7

Compute Area with Console Input import java.util.scanner; // Scanner is in the java.util package public class ComputeAreaWithConsoleInput { } public static void main(string[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Prompt the user to enter a radius System.out.print("Enter a number for radius: "); double radius = input.nextdouble(); // Compute area double area = radius * radius * 3.14159; // Display result System.out.println("The area for the circle of radius " + } radius + " is " + area); Compute Area with Console Input http://www.cs.armstrong.edu/liang/intro10e/html/computeareawithconsoleinput.html 8

Import Statement There are two types of import statements: Specific Import: Specifies a single class in the import statement. e.g. import java.util.scanner; Wildcard Import: Imports all the classes in a package by using the asterisk as the wildcard. e.g. import java.util.*; The information for the classes in an imported package is not read in at compile time or runtime unless the class is used in the program. No performance difference. 9

Identifiers Identifiers are the names that identify the elements such as classes, methods, and variables in a program. An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. An identifier cannot be a reserved word. An identifier cannot be true, false, or null. An identifier can be of any length. $2, ComputeArea, radius are legal identifiers 2A, d+4 are not legal identifiers Give descriptive names to identifiers If identifiers are written wrong than syntax error occurs 10

Variables Variables are used to represent values that may be changed in the program. Variables are for representing data of a certain type. To use a variable, you declare it by telling the compiler its name as well as what type of data it can store. The variable declaration tells the compiler to allocate appropriate memory space for the variable based on its data type. The syntax for declaring a variable is: datatype variablename; 11

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; If variables are of the same type, they can be declared together, as follows: datatype variable1, variable2,..., variablen; int i, j, k; // Declare i, j, and k as int variables 12

Assignment Statements An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java. After declaring a variable you can assign a value to it: Examples: variable = expression; x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; area = radius * radius * 3.14159; // Compute area 13

Assignment Statements You can use a variable in an expression. A variable can also be used in both sides of the = operator. x = x + 1; If a value is assigned to multiple variables, you can use this syntax: i = j = k = 1; You can declare and initialize in one step: int x = 1; double d = 1.4; 14

Named Constants A named constant is an identifier that represents a permanent value. Do not change during the execution of a program final datatype CONSTANTNAME = VALUE; A constant must be declared and initialized in the same statement. The word final is a Java keyword for declaring a constant. final double PI = 3.14159; final int SIZE = 3; 15

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, and the method computearea. 16

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

Numeric Data Types and Operations Java has six numeric types for integers and floating-point numbers with operators +, -, *, /, and %. Java uses four types for integers: byte, short, int, and long. Java uses two types for floating-point numbers: float and double. 18

Numeric Data Types 19

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

Numeric Operators 21

Numeric Operators When both operands of a division are integers, the result of the division is the quotient and the fractional part is truncated. 5 / 2 yields 2, not 2.5 5 / 2 yields -2, not 2.5 To perform a float-point division, one of the operands must be a floating-point number. 5.0 / 2 yields 2.5 22

Numeric Operators The % operator is often used for positive integers The remainder is negative only if the dividend is negative -7 % 3 yields -1-12 % 4 yields 0-26 % -8 yields -2 20 % -13 yields 7 23

Numeric Operators Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is in 10 days? You can find that day is Tuesday using the following expression: 24

Problem: Displaying Time Write a program that obtains hours and minutes from seconds. Display Time http://www.cs.armstrong.edu/liang/intro10e/html/displaytime.html 25

Arithmetic Expressions Java expressions are evaluated in the same way as arithmetic expressions. 3 4x 5 10( y 5)( a x b c) 4 9( x 9 y x ) is translated to (3+4*x)/5 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) 26

Problem: Converting Temperatures Remember the program that converts a Fahrenheit degree to Celsius using the formula: 5 celsius ( 9 )( fahrenheit 32) You have to write this expression as: celsius = (5.0 / 9) * (fahrenheit 32) 27

NOTE Calculations involving floating-point numbers are approximated 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 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. 28

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; 29

Integer Literals An integer literal can be assigned to an integer variable as long as it can fit into the variable. 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. An integer literal is assumed to be of the int type, whose value is between -2 31 (-2147483648) to 2 31 1 (2147483647). 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). 30

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. 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. 31

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 1.23456e-2 is equivalent to 0.0123456 E (or e) represents an exponent and it can be either in lowercase or uppercase. 32

Augmented Assignment Operators The operators +, -, *, /, and % can be combined with the assignment operator to form augmented operators. Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8 33

Augmented Assignment Operators The augmented assignment operator is performed last after all the other operators in the expression are evaluated. For example, x /= 4 + 5.5 * 1.5; is same as x = x / (4 + 5.5 * 1.5); 34

Increment and Decrement Operators The increment operator (++) and decrement operator ( ) are for incrementing and decrementing a variable by 1. 35

Increment and Decrement Operators int i = 10; Same effect as int newnum = 10 * i++; int newnum = 10 * i; i = i + 1; int i = 10; Same effect as int newnum = 10 * (++i); i = i + 1; int newnum = 10 * i; 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 36

Numeric Type Conversion You can always assign a value to a numeric variable whose type supports a larger range of values Consider the following statements: byte i = 100; long k = i * 3 + 4; double d = i * 3.1 + k / 2; range increases byte, short, int, long, float, double 37

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. 38

Type Casting You cannot, however, assign a value to a variable of a type with a smaller range unless you use type casting. Casting is an operation that converts a value of one data type into a value of another data type. Casting a type with a small range to a type with a larger range is known as widening a type. double d = 3; (type widening) Casting a type with a large range to a type with a smaller range is known as narrowing a type. int i = (int)3.9; (Fraction part is truncated) 39

Type Casting Java will automatically widen a type, but you must narrow a type explicitly. What is wrong? int x = 5 / 2.0; A compiler error will occur range increases byte, short, int, long, float, double 40

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 sum += 4.5 is equivalent to sum = (int)(sum + 4.5). 41

Software Development Process Requirement Specification System Analysis System Design Implementation Testing Deployment Maintenance 42

Requirement Specification Requirement Specification System Analysis A formal process that seeks to understand the problem and document in detail what the software system needs to do. System Design Implementation This phase involves close interaction between users and designers. You need to study a problem carefully to identify its requirements. Testing Deployment Maintenance 43

System Analysis Requirement Specification System Analysis System Design Seeks to analyze the business process in terms of data flow, and to identify the system s input and output. Implementation Testing Deployment Maintenance 44

System Design Requirement Specification System Analysis To design a process for obtaining the output from the input. System Design Implementation Testing You can break down the problem into subsystems that performs specific functions of the system. Deployment Maintenance 45

IPO Requirement Specification System Analysis Input, Process, Output System Design Implementation The essence of system analysis and design is input, process, and output. This is called IPO. Testing Deployment Maintenance 46

Implementation Requirement Specification System Analysis System Design The process of translating the system design into programs. Separate programs are written for each component and put to work together. Implementation This phase requires the use of a programming language like Java. The implementation involves coding, testing, and debugging. Testing Deployment Maintenance 47

Testing Requirement Specification System Analysis Ensures that the code meets the requirements specification and weeds out bugs. System Design Implementation An independent team of software engineers not involved in the design and implementation of the project usually conducts such testing. Testing Deployment Maintenance 48

Deployment Requirement Specification System Analysis Deployment makes the project available for use. System Design Implementation For a Java applet, this means installing it on a Web server; for a Java application, installing it on the client's computer. Testing Deployment Maintenance 49

Maintenance Requirement Specification System Analysis Maintenance is concerned with changing and improving the product. System Design Implementation A software product must continue to perform and improve in a changing environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes. Testing Deployment Maintenance 50

Problem: Computing Loan Payments This program lets the user enter the interest rate, number of years, and loan amount, and computes monthly payment and total payment. monthlypayment loanamount monthlyinterestrate 1 (1 monthlyinterestrate) 1 numberofye ars 12 Compute Loan http://www.cs.armstrong.edu/liang/intro10e/html/computeloan.html 51

Problem: Monetary Units This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. Compute Change http://www.cs.armstrong.edu/liang/intro10e/html/computechange.html 52

Common Errors and Pitfalls Common elementary programming errors often involve: undeclared variables uninitialized variables integer overflow unintended integer division round-off errors 53

Undeclared/Uninitialized Variables and Unused Variables double interestrate = 0.05; double interest = interestrate * 45; This code is wrong, because interestrate is assigned a value 0.05; but interestrate has not been declared and initialized. Java is case sensitive, so it considers interestrate and interestrate to be two different variables. double interestrate = 0.05; double taxrate = 0.05; double interest = interestrate * 45; System.out.println("Interest is " + interest); If a variable is declared, but not used in the program, it might be a potential programming error. So, you should remove the unused variable from your program. In this code taxrate is never used. It should be removed from the code 54

Integer Overflow Numbers are stored with a limited numbers of digits. When a variable is assigned a value that is too large (in size) to be stored, it causes overflow. int value = 2147483647 + 1; Executing the statement causes overflow, because the largest value that can be stored in a variable of the int type is 2147483647. 2147483648 will be too large for an int value. 55

Round-off Errors A round-off error, also called a rounding error, is the difference between the calculated approximation of a number and its exact mathematical value. 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. 56

Unintended Integer Division Java uses the same divide operator, namely /, to perform both integer and floating-point division. 57

Redundant Input Objects New programmers often write the code to create multiple input objects for each input. 58

Continue WEEK 3 SELECTIONS 59