Basic Programming Elements

Similar documents
Program Control Flow

Program Control Flow

Full file at

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

More on control structures

Computational Expression

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

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

Basic Computation. Chapter 2

CEN 414 Java Programming

Operators and Expressions

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

3. Java - Language Constructs I

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

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

Chapter 2. Elementary Programming

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

CMPT 125: Lecture 3 Data and Expressions

Elementary Programming

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

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

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

Programming with Java

Program Fundamentals

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

Data Conversion & Scanner Class

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2: Using Data

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

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

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

Chapter 02: Using Data

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

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

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

Basics of Java Programming

Full file at

Chapter 2 Elementary Programming

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

ECE 122 Engineering Problem Solving with Java

Getting started with Java

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

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

Introduction to Java Applications; Input/Output and Operators

Basic Computation. Chapter 2

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

Chapter 2: Data and Expressions

COMP 202 Java in one week

CS 302: Introduction to Programming

COMP 110 Introduction to Programming. What did we discuss?

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Peer Instruction 1. Elementary Programming

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

COMP6700/2140 Operators, Expressions, Statements

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

COMP 202 Java in one week

Chapter 2 Primitive Data Types and Operations. Objectives

Basic Operations jgrasp debugger Writing Programs & Checkstyle

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

Introduction to Java Applications

Welcome to the Primitives and Expressions Lab!

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Section 2: Introduction to Java. Historical note

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

CS110: PROGRAMMING LANGUAGE I

Visual C# Instructor s Manual Table of Contents

Input. Scanner keyboard = new Scanner(System.in); String name;

Simple Java Reference

Arithmetic and IO. 25 August 2017

AP Computer Science Unit 1. Programs

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

STUDENT LESSON A7 Simple I/O

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Building Java Programs

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 2: Using Data

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

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

Primitive Data Types: Intro

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

I. Variables and Data Type week 3

Chapter 2: Using Data

2.5 Another Application: Adding Integers

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

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

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

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

CIS 110: Introduction to Computer Programming

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

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

Chapter. Let's explore some other fundamental programming concepts

CS111: PROGRAMMING LANGUAGE II

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

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

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

Lecture Set 2: Starting Java

Transcription:

Chapter 2 Basic Programming Elements Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2 http://www.ii.uib.no/~khalid/jac/ Permission is hereby granted to use these lecture slides in conjunction with the book. Modified: 14/11/08 JACT 2: Basic Programming Elements 2-1/30

Overview Printing to the terminal window Local variables Numerical data types Arithmetic expressions and operators Formatted output Reading numbers from the keyboard JACT 2: Basic Programming Elements 2-2/30

Printing to the terminal window Java programs can calculate values and print them directly to the terminal window literals System.out.println(9+7); standard out expression print and terminate the line Key concepts: Standard out - the System.out object, connected to terminal window by default println() prints values followed by newline print() prints values and allows printing to continue on the same line Literal - value written directly in the source code, e.g. an integer or a string Expression - a combination of values and operators, e.g. addition of two integers JACT 2: Basic Programming Elements 2-3/30

Printing to the terminal window Program 2.1 illustrates use of the print() and println() methods... System.out.print("The value of 9 + 7 is "); // (4) System.out.println(9+7); // (5)... Compile and run with > javac SimplePrint.java > java -ea SimplePrint Exercise: Compile and run Program 2.1. Check that you get the same output as in the book. JACT 2: Basic Programming Elements 2-4/30

Printing to the terminal window Printing several strings on the same line // Alt.1: using the print() method to continue on the same line System.out.print("This text continues "); System.out.print("on the same line "); System.out.println("until terminated by a newline."); // Alt.2: using the + operator to print all text in one call System.out.println("This text continues " + "on the same line " + "until terminated by a newline."); Both code snippets above produce the same output: This text continues on the same line until terminated by a newline. Exercise: Enter the code lines above into a Java source code file. Compile and run the program. Check that your output matches with the above output. JACT 2: Basic Programming Elements 2-5/30

Printing to the terminal window Potential pitfall: Printing strings and numerical values in the same call System.out.println("The value of 9 + 7 is " + (9+7)); Best practice: Ensure your numeric expressions are placed within parentheses when printing strings and numerical values together. JACT 2: Basic Programming Elements 2-6/30

Local variables Variables allow locations in memory to be named and accessed in a program A variable declared inside a method is called a local variable. Declaring a variable: declaration comment int numberofcourses; // number of courses this semester type variable name Key concepts: Variable name - unique name of the memory location Data type (or type) - defines what kind of values the variable can hold Comment - describes its purpose, helps in understanding the program Best practice: Choose names that makes the purpose of the variable easy to understand. Write a short comment for each variable unless the purpose is obvious from its name. JACT 2: Basic Programming Elements 2-7/30

Declaring and initialising a variable: declaration assignment int numberofcourses = 2; Local variables type variable name initial value Key concepts: Assignment - placing a value in the memory location referred to by the variable Initialisation - the first assignment to a variable Size of an int value 10 0x010349 (address) Name: sum Type: int value ("content") int sum = 10; is equivalent to int sum; sum = 10; JACT 2: Basic Programming Elements 2-8/30

Local variables Best practice: Declare a local variable where it is first assigned a value. This ensures each variable is properly initialised, and reduces the risk of incorrect use or modification. Choosing variable names: Remember what Java accepts as valid names Names can contain letters and digits, but cannot start with a digit. Underscore (_) is allowed, also as the first character of a name. Java distinguishes between upper and lower case letters in names. Keywords like int cannot be used as variable names. Keep in mind conventions for variable names Use lower case letters for single-word names, and upper case letters for the first character of each consecutive word. Use all upper case letters for constants, and separate words with underscore. Exercise: Determine which of the following names are valid and follow conventions. Propose valid/better names if needed. int teamid, Team_Leader, 24x7, bestguess!, MAX_COUNT; JACT 2: Basic Programming Elements 2-9/30

Identifiers A name in a program is called an identifier. An identifier contains a sequence of characters that are either a letter, digit, underscore (_) or dollar-character ($), and cannot start with a digit. Local variables Literals denote a constant value Identifiers containing lower and upper case letters are different (case-sensitive). Defined: Number, number, sum_$, max_sum, bingo_, counter, $$_100 declared in the program. Keywords: float, if, true, while, for reserved words with specific meaning. Example of invalid identifiers: what?, 7UP Integers: 59 0 1993-46 Floating-point: -3.1.5 0.5 5E-1(=5x10-1 =0.5) Characters: 'a' '0' '+' '5' '\n' '\u000a' Boolean: true false String: "a piece of cake" "if" "\n" "0" "3.14" In addition there are special characters, like ( ) { } [ ] ;. and operators, such as + * - % = ==!= >= JACT 2: Basic Programming Elements 2-10/30

Local variables Identifiers, literals, operators and special character comprise what is called basic programming elements (tokens) in Java. A program in a source code file is a long sequence of characters. The compiler must divide the source code into basic programming elements to translate the program to byte code. In some cases basic programming elements must be separated in the source code by white spaces: sequences of space, tabulator, newline and formfeed characters. return 0; // must write a space between return and 0 return0; // invalid statement consisting of a single // identifier named return0. sum=sum+1; // not necessary to separate these basic elements However, use of white spaces can improve readability! JACT 2: Basic Programming Elements 2-11/30

Assignment operator identifier = expression Identifier gets the value of the expression. sum = 59; Identifier must be declared. 2 Identifier and expression must be of the same type. 1 3 59 Name: sum Type: int 2 cent = sum + 6; 65 3 59+6 1 59 Name: count Type: int Name: sum Type: int JACT 2: Basic Programming Elements 2-12/30

Numerical data types Variables are used to store values. A variable has a name, type, size, value, and address. Primitive data type Integer: with sign and 2 scompliment Floating-point: IEEE 754-1985 standard Keyword in Java Value-size Example of literal Example of variable declaration byte 8-bits 29 byte b; short 16-bits 29 300-1 short m,n; int 32-bits 29 035 0x1D -12345 int i,j,k; long 64-bits 29L 1L 123456L long l; float 32-bits 1.5F 3.2e2F float r; double 64-bits 1.5 3.2e-2.1e2 3.14D 0.0-0.0 double s,t; Character: char 16-bits 'a' '\t' '\u0009' char c; UNICODE Boolean/logical: boolean true false boolean v; JACT 2: Basic Programming Elements 2-13/30

Numerical data types Overview of primitive data types in Java: Primitive data types Boolean type Numerical data types Integral types Floating-point types Character type Integer types boolean char byte short int long float double JACT 2: Basic Programming Elements 2-14/30

Numerical data types A write operation overwrites the old value in memory with a new value, e.g. an assignment. A read operation does not change the value stored in memory, e.g. in a variable (operand) used in an expression. int i = 10, j = 20; i = 2 * j; // read: retrieving the value of j // write: i is assigned a new value (40) JACT 2: Basic Programming Elements 2-15/30

Arithmetic expressions and operators Common operators for numerical values Multiplication (*) Division (/) Addition (+) Subtraction (-) are all supported in Java. Operators and operands in arithmetic expressions: unary operator binary operator binary operator -273.15 9 + 7 price + price * 0.23 operand operands operand operand operands binary operator A unary operator requires one operand. A binary operator requires two operands. JACT 2: Basic Programming Elements 2-16/30

Arithmetic expressions Arithmetic expressions can contain: Example: a number literal, 3.14 a variable, count a method call, Math.sin(90) an operator between two expressions (binary operator), phase + Math.sin(90) an operator applied to one expression (unary operator), -discount expressions in parentheses. (3.14-amplitude) Integer arithmetic yields results of type int unless at least on of the operands is of type long. Floating-point arithmetic yields results of type double if one of the operands is of type double. JACT 2: Basic Programming Elements 2-17/30

Arithmetic expressions and operators (Value) type Expression (has a value) of type T variable, literal method call type specific expression int count, 2, 97 Math.power(2,10), db.numberofcars() 8+count, (2*4)/3, 13%2 double price, vat, 3.14D, -0.5e5,.035, 2.667 Math.cos(0.0), Math.sqrt(3.14+1.0) 8*price+vat, (2.0*4)/3 JACT 2: Basic Programming Elements 2-18/30

Arithmetic expressions and operators T (Value) type variable, constant or literal method call Expression (has a value) of type type specific expression boolean finished, OK, true, false Character.isDigit(c), Character.isLetter(c), Character.isLowercase(c) Comparison operators: count == 3, i < 100 Boolean or logical operators: finished && OK, (i<100) (count == 1) char character, 'z', '\n', '\u000a' Character.toLowercase(c) String str, "a string\n", "\"aha\"", "" str.substring(start, stop+1) Concatenation: "Hi!" + " What s " + "up?.\n" JACT 2: Basic Programming Elements 2-19/30

Conversion between primitive data types Evaluation of an arithmetic expression can results in implicit conversion of values in the expression. See examples below. Conversion of a "narrower" data type to a "broader" data type is (usually) done without loss of information, while conversion the other way round may cause loss of information. The compiler will issue a error message if such a conversion is illegal. int i = 10; double d = 3.14; d = i; // OK! i = d; // Not accepted without explicit conversion (cast) i = (int) d; // Accepted by the compiler JACT 2: Basic Programming Elements 2-20/30

Precedence and associativity rules Used to unambiguously evaluate expressions. The rules can be overruled by means of parentheses, (). Problem: Does 2 + 3 * 4 evaluate to 20 or 14? Precedence rules are used to decide which operator will be evaluated first, if there are two operators with different precedence following each other in the expression. The operator with highest precedence is evaluated first. 2 + 3 * 4 is interpreted as 2 + (3 * 4) (resulting in value 14) since * has higher precedence than +. Associativity rules are used to decide which operator will be evaluated first, if there two operators with same precedence following each other in the expression. Left associativity yields grouping from left to right. 1 + 2-3 is interpreted as ((1 + 2) - 3) since binary operators + and - are leftassociative. Right-associativity yields grouping from right to left. - - 4 is interpreted as (- (- 4)) (resulting in value 4) since unary operator - is rightassociative. JACT 2: Basic Programming Elements 2-21/30

Evaluation of arithmetic expressions Arithmetic operators Expression Evaluation: Determine operands. Evaluate left to right. Grouping () 3 + 2-1 ((3 + 2) - 1) 4 Unary + 2 + 6 * 7 (2 + (6 * 7)) 44 - -5+7- -6 (((-5)+7)-(-6)) 8 Binary (modulo) * 2+4/5 (2+(4/5)) 2 / 13 % 5 (13 % 5) 3 % 10 / 0 ArithmeticException Unary operators associate from right to left. Binary operators associate from left to right. Precedence decreases downwards in the table. Operands are evaluated from left to right before the operator is applied. Value + 2+4.0/5 (2.0+(4.0/5.0)) 2.8-4.0 / 0.0 Inf JACT 2: Basic Programming Elements 2-22/30

Evaluation of arithmetic expressions Integer expressions: 3 + 2-1: 4 2 + 6 * 7: 44-5+7- -6: 8 2+4/5: 2 (integer division: truncation) 13 % 5: 3 (remainder) Floating-point expressions: 2+4.0/5: 2.8 (floating-point division) 2.0+4/5: 2.0 (integer division) 4.0 / 0.0: INF (Infinity) 0.0 / 0.0: NAN(004) (Not-a-Number) Number limits: Integer.MAX_VALUE: 2147483647 Integer.MIN_VALUE: -2147483648 Long.MAX_VALUE: 9223372036854775807 Long.MIN_VALUE: -9223372036854775808 Float.MAX_VALUE: 3.40282e+38 Float.MIN_VALUE: 1.4013e-45 (Also applies to negative floating-point values.) Double.MAX_VALUE: 1.79769e+308 Double.MIN_VALUE: 2.22507e-308 Float.POSITIVE_INFINITY: INF Float.NEGATIVE_INFINITY: -INF Number over/underflow is not signaled! (NB! "Wrap-around" for integers.) Integer.MAX_VALUE +1: -2147483648 Integer.MIN_VALUE -1: 2147483647 Long.MAX_VALUE +1: -9223372036854775808 Long.MIN_VALUE -1: 9223372036854775807 Float.MAX_VALUE +1: 3.40282e+38 Float.MIN_VALUE +1: 1.0 Double.MAX_VALUE +1: 1.79769e+308 Double.MIN_VALUE +1: 1.0 Float.POSITIVE_INFINITY +1: INF Float.NEGATIVE_INFINITY -1: -INF JACT 2: Basic Programming Elements 2-23/30

Formatted output We can call the method printf() in the System.out object to print a formatted string to the terminal window, using a format string and an argument-list: printf(string formatstring, Object... argumentlist) A format string can contain both fixed text and format specifications. When calling the printf()-method, all arguments in the argument list will be sent to the method and formatted according to the format specifications in the format string. JACT 2: Basic Programming Elements 2-24/30

Example: Formatted output System.out.printf("Formatted output %6d %8.3f kr. %.2f %6s%n", 2004, Math.PI, 1234.0354, "hi!"); Output (with Norwegian locale as default): Formatted output 2004 3,142 kr. 1234,04 hi! The format string is the first parameter in the method call. The argument list consists of all parameters after the format string. In this case, there are 4 parameters: 2007, Math.PI, 1234.0354, "hi!". The format string contains 5 format specifications: %6d, %8.3f, %.2f, %6s and %n. The format specification specifies how the arguments will be processed, and the sequence says where the result of each argument will be placed in the format string. Type Format specification Argument Result Integer Integer Floating-point String %6d %8.3f %.2f %5s 2007 Math.PI 1234.0354 "hi!" " 2007" " 3,142" "1234,04" " hi!" The format specification %n yields a newline where it occurs in the format string. JACT 2: Basic Programming Elements 2-25/30

It's now or never Flam ing Sta r S u spious M A n gel inds Reading numbers from the keyboard Any input the user writes on the keyboard is shown in the terminal window. How can a program read the input that the user types on the keyboard? This is called reading from the keyboard. System.in identifies the object that reads bytes from the keyboard. The class java.util.scanner offers methods for converting bytes to primitive data values. main() IntegerReader new Scanner(System.in) keyboard:scanner nextint() Screen 1 2 Keyboard 3 123 Enter-key pressed JACT 2: Basic Programming Elements 2-26/30

Reading numbers from the keyboard How to read values from the keyboard: import java.util.scanner; // Imports Scanner-class.... Scanner keyboard = new Scanner(System.in); // Coupling a Scanner // to standard-in. // We can now call methods of the Scanner-class to read values from // the keyboard. int i = keyboard.nextint(); // Read an integer. double d = keyboard.nextdouble();// Read a floating-point value. String str = keyboard.nextline();// Read (rest of) the line as string.... JACT 2: Basic Programming Elements 2-27/30

Reading numbers from the keyboard Exercise: Extend Program 2.7 to read the sides of a cube, and calculate its volume. The user dialogue may look like the following, where user input is shown in bold: Enter the cube length [integer]: 12 Enter the cube breadth [integer]: 4 Enter the cube height [integer]: 7 A cube of length 12 cm, breadth 4 cm and height 7 cm has volume 336 cubic cm. JACT 2: Basic Programming Elements 2-28/30

Example: Reading numbers from the keyboard import java.util.scanner; /* Celsius to Fahrenheit: * 9 x celsius * ----------- + 32 * 5 */ public class Temperature { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Input temperature in degrees Celsius:"); double celsius = keyboard.nextdouble(); double fahr = (9.0 * celsius)/5.0 + 32.0; System.out.println(celsius + " degrees Celsius corresponds to " + fahr + " degrees Fahrenheit."); } } JACT 2: Basic Programming Elements 2-29/30

Reading numbers from the keyboard Running the program: Input temperature in Celsius: 23,5 23.5 degrees Celsius corresponds to 74.3 degrees Fahrenheit. Note: The user inputs floating-point values using comma for decimal point because the program is using the Norwegian locale as default. The methods print() and println() print floating-point values using dotnotation. Exercise: Write a program that calculates the corresponding temperature in degrees Celsius when a temperature in degrees Fahrenheit is input by the user. The following formula converts a Fahrenheit temperature to Celsius: celsius = (fahr - 32.0) * 5.0 / 9.0; Check that the program behaves as expected by using a few Fahrenheit temperatures calculated by the Temperature class as input. JACT 2: Basic Programming Elements 2-30/30