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

Similar documents
Introduction to Programming Using Java (98-388)

Full file at

Lecture Set 2: Starting Java

Java Primer 1: Types, Classes and Operators

Lecture Set 2: Starting Java

Program Fundamentals

Program Elements -- Introduction

CS313D: ADVANCED PROGRAMMING LANGUAGE

Basics of Java Programming

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Introduction to Java Applications

CS110: PROGRAMMING LANGUAGE I

Full file at

Chapter 2: Data and Expressions

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Chapter 2 Elementary Programming

Information Science 1

CS 302: Introduction to Programming

Chapter 2: Data and Expressions

Computer Components. Software{ User Programs. Operating System. Hardware

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

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


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

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

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

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Computational Expression

Chapter 2: Data and Expressions

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Unit 3. Operators. School of Science and Technology INTRODUCTION

Lesson 2: First Java Programs

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

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

Getting Started with Python

Basic Computation. Chapter 2

Fundamentals of Programming (Python) Getting Started with Programming

CEN 414 Java Programming

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

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

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Lecture 3 Tao Wang 1

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Datatypes, Variables, and Operations

The C++ Language. Arizona State University 1

4. Inputting data or messages to a function is called passing data to the function.

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

COMP 202 Java in one week

Chapter 2: Using Data

Objectives. In this chapter, you will:

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Chapter 2 Working with Data Types and Operators

Chapter 2: Introduction to C++

AP Computer Science A

Programming with Java

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Ex: If you use a program to record sales, you will want to remember data:

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Chapter 3: Operators, Expressions and Type Conversion

Information Science 1

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Chapter 2: Using Data

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Algorithms and Programming I. Lecture#12 Spring 2015

Chapter 02: Using Data

Visual C# Instructor s Manual Table of Contents

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

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

Fundamental of Programming (C)

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

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

Chapter 2 First Java Programs

Creating a C++ Program

Full file at C How to Program, 6/e Multiple Choice Test Bank

Chapter 2 ELEMENTARY PROGRAMMING

BITG 1233: Introduction to C++

EXPRESSIONS AND ASSIGNMENT CITS1001

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

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

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

Unit E Step-by-Step: Programming with Python

Chapter 2. Elementary Programming

JAVA Programming Fundamentals

Computer Components. Software{ User Programs. Operating System. Hardware

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Chapter 2: Using Data

Basic Computation. Chapter 2

Transcription:

Chapter 3 Syntax, Errors, and Debugging

Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different arithmetic operators. Concatenate two strings or a number and a string. 2

Objectives (cont.) Know how and when to use comments in a program. Tell the difference between syntax errors, run-time errors, and logic errors. Insert output statements to debug a program. 3

Objectives (cont.) Understand the difference between Cartesian coordinates and screen coordinates. Work with color and text properties. 4

Vocabulary Arithmetic expression Comments Coordinate system Exception Graphics context Literal 5

Vocabulary (cont.) Logic error Origin Package Pseudocode Reserved words Run-time error 6

Vocabulary (cont.) Screen coordinate system Semantics Syntax Virus 7

Language Elements Every language, including Java has: Vocabulary: Set of all of the words and symbols in the language Syntax: Rules for combining words into sentences (statements) Semantics: Rules for interpreting the meaning of statements 8

Language Elements (cont.) Table 3-1: Some Java vocabulary 9

Language Elements (cont.) Programming vs. natural languages Programming languages have small vocabularies and simple syntax and semantics. Programming language syntax must be absolutely correct. Programming language statements are interpreted literally. Every detail must be present. 10

Basic Java Syntax and Semantics 11 Two categories of data types: 1. Primitive data types: Numbers, characters, and Booleans 2. Objects ex; Strings Syntax for manipulating primitive data types differs than for objects Primitive data types are combined in expressions with operators. Objects are sent messages.

Basic Java Syntax and Semantics (cont.) 12 Objects must be instantiated before use. Unlike primitives String objects are a little different; are objects & are sent messages, but don t need to be instantiated before use. Six numeric data types int and double are most commonly used Also short, long, byte, and float Each uses a different number of bytes for storage. Each represents a different range of values. Learn more later.

Basic Java Syntax and Semantics (cont.) Table 3-2: Some Java numeric data types 13

Basic Java Syntax and Semantics (cont.) Literals: Items whose values do not change. Examples the number 5.0 or the string Java Restricted to primitive data & strings. Variable is a named location in memory. Changing a variable s value is equivalent to replacing the value at the memory location. A variable s data type cannot change. 14

Basic Java Syntax and Semantics (cont.) Figure 3-1: Changing the value of a variable 15

Basic Java Syntax and Semantics (cont.) 16 Variable declaration statement: Declares the identifier and data type for a variable int age; (declares one int variable) int a, b, c; (declares three int variables) int x, y, z = 7; double p, q = 1.41, pi = 3.14, t; String name = Bill Jones ; Scanner reader = new Scanner(System.in); double d = 2.45; (declares and initializes a variable) You can declare several variables in a single declaration & simultaneously assign them initial values Declares the object variable reader, instantiates or creates a Scanner object that is attached to the keyboard input stream, System.in, and finally assigns the object to the object variable, reader.

Basic Java Syntax and Semantics (cont.) Constants are variables whose value cannot change. final double PI = 3.14; Customary to write the names of constants in uppercase. 17

Basic Java Syntax and Semantics (cont.) 18 Assignment statements: <variable> = <expression>; Value of expression assigned to variable Arithmetic expressions: EXAMPLE: double celsius, fahrenheit; String name; Scanner reader; fahrenheit = reader.nextdouble(); celsius = (fahrenheit 32.0) * 5.0/9.0; Multiplication and division have higher precedence than addition name = Bill and Smith ; subtraction. reader = new Scanner(System.in); Operators of same precedence evaluated from left to right. Parentheses are used to change evaluation order.

Basic Java Syntax and Semantics (cont.) 19 Table 3-5: Common operators and their precedence

Basic Java Syntax and Semantics (cont.) The semantics of division (/) differ for integers and floating-point operators. int / int yields an int. double / double yields EXAMPLES: a double. The modulus operator (%) yields 5.0/2.0 yields a remainder. 2.5 11 % 3 yields 2. Division: 5/2 yields 2 Modulus: 9 % 5 yields 4 9.3 % 5.1 yields 4.2 20

Basic Java Syntax and Semantics (cont.) 21 Table 3-6: Examples of expressions and their values

Basic Java Syntax and Semantics (cont.) Arithmetic overflow: Assigning a value to a variable that is outside of the ranges of values that the data type can represent Mixed-mode arithmetic: Expressions involving integer and floating-point values Lower-precision data types (int) temporarily converted to high-precision data types (double) 22

Basic Java Syntax and Semantics (cont.) Type casting: Temporarily converting one data type to another Can type cast a single variable or an entire expression int i; double d; Place the desired i = (int)3.14; data type i equals within 3, truncation parentheses toward 0 d = (double)5/4; d equals 1.25 before the variable or expression that will be cast to another data type. int x = (int)(d + 1.6); 23

Basic Java Syntax and Semantics (cont.) 24 String concatenation: Append a String or value to another String Use the + operator String s = string1 + string2 ; String s2 = String1 + intvariable1; Escape character (\): Used in codes to represent characters that cannot be directly typed into a program \t is a tab character

Basic Java Syntax and Semantics (cont.) The String class s length method gives the number of characters in a String. Classes implement methods, and objects are instances of classes. Objects can respond to a message only if their class implements the method. Must implement a method with a matching signature 25

Basic Java Syntax and Semantics (cont.) Method signature: Method name Number and data types of method parameters Method and variable names are user defined symbols. Cannot use Java keywords (reserved words) Packages: Used to organize related classes into a single unit for distribution 26

Basic Java Syntax and Semantics (cont.) 27 Table 3-7: Java s reserved words

Terminal I/O for Different Data Types Table 3-8: Methods in class Scanner 28

Terminal I/O for Different Data Types (cont.) 29 Example 3-1: Tests three types of input data

Comments Explanatory sentences inserted in a program Compiler ignores them Purpose is to make program more readable Two varieties: End of line comments: All text following a double slash (//) on a single line Multiline comments: All text occurring between a /* and a */ 30

Comments (cont.) Typical uses of comments: Begin a program with a statement of its purpose Explain the purpose of a variable declaration Explain the purpose of a major segment of code Explain the workings of complex or tricky sections of code 31

Programming Errors Three types of programming errors: Syntax errors: When a syntax rule is violated Detected during compilation Compiler helps identify error Run-time errors: Occurs during execution Dividing by 0 Detected when program runs JVM indicates type of error and location 32

Programming Errors (cont.) Three types of programming errors (cont.): Logic errors (design errors or bugs): Incorrect logic implemented in the program Code may be correct in every other way, but does not do what it is supposed to do. Must thoroughly test and debug the program when an error is found. Desk checking: Examine code immediately after it is written 33

Debugging One debugging method is to add extra lines of code to print values of selected variables at strategic points in the program. 34

Graphics and GUIs: Drawing Shapes and Text Defining a specialized graphics panel: Define a new class that extends the JPanel class Inherits all of the properties and methods of a JPanel, but can add additional instance variables and methods 35

Graphics and GUIs: Drawing Shapes and Text (cont.) Example 3.5: Empty color panel 36

Graphics and GUIs: Drawing Shapes and Text (cont.) Every graphics application uses a coordinate system. Positions of items on a window specified in terms of two-dimensional points Java uses the screen coordinate system: The origin (point with coordinates (0,0)) located at upper-left corner of a panel or frame Every window, frame, or other type of window has own coordinate system 37

Graphics and GUIs: Drawing Shapes and Text (cont.) Figure 3-7: Orientation of Java s coordinate system 38

Graphics and GUIs: Drawing Shapes and Text (cont.) Graphics class: Used to draw on a panel Every panel maintains an instance of this class. The graphics context Shapes drawn on a panel by the Graphics class have a foreground color. Change color via the setcolor() method. 39

Graphics and GUIs: Drawing Shapes and Text (cont.) 40 Table 3-9: Common method in the Graphics class

Graphics and GUIs: Drawing Shapes and Text (cont.) 41 Table 3-9: Common method in the Graphics class (cont.)

Graphics and GUIs: Drawing Shapes and Text (cont.) 42 Table 3-9: Common method in the Graphics class (cont.)

Graphics and GUIs: Drawing Shapes and Text (cont.) Every panel instance has a paintcomponent() method Called by the JVM when the panel needs to be drawn on the screen Contains instructions for how to draw the panel For custom panels, can write own paintcomponent() method, but must also call the superclass s paintcomponent() method 43

Graphics and GUIs: Drawing Shapes and Text (cont.) 44 Example 3.6: Colored panel containing a red text message in a blue rectangle

Graphics and GUIs: Drawing Shapes and Text (cont.) Figure 3-8: Displaying a shape and text in a panel 45

Graphics and GUIs: Drawing Shapes and Text (cont.) The width and height of a panel can be found using the getwidth() and getheight() methods, respectively. Font class: Information about a specific font Font name, size, and style Font font = new Font( Arial, Font.BOLD, 10); 46

Summary Use the int data type for whole numbers and double for floating-point numbers. Variable and method names consist of a letter followed by additional letters or digits. Keywords cannot be used as names. Final variables behave as constants; their values cannot change after they are declared. 47

Summary (cont.) Arithmetic expressions are evaluated according to precedence. Some expressions yield different results for integer and floating-point operands. Strings may be concatenated. The compiler catches syntax errors. The JVM catches run-time errors. 48

Summary (cont.) Logic errors, if caught, are detected by the programmer or user at run-time. Can find and remove logic errors by inserting debugging output statements to view the values of variables. The programmer can modify the color with which images are drawn and the properties of text fonts for a given graphics object. 49

Summary (cont.) Java uses a screen coordinate system to locate the positions of pixels in a window or panel. Origin is the upper-left corner of the drawing area. x and y axes increase to the right and downward. 50