More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Similar documents
Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

JAVA OPERATORS GENERAL

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Introduction to Computer Programming

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Building Java Programs

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

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

Programming with Java

Building Java Programs

Chapter 3. Selections

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

ECE 122 Engineering Problem Solving with Java

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

Lecture Set 2: Starting Java

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

Computer Programming CS F111

Lecture Set 2: Starting Java

Operators in java Operator operands.

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

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

COMP 202 Java in one week

Lecture 3 Tao Wang 1

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Chapter 3: Operators, Expressions and Type Conversion

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Prof. Navrati Saxena TA: Rochak Sachan

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

What did we talk about last time? Examples switch statements

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

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

AP COMPUTER SCIENCE A

Chapter 2: Data and Expressions

Building Java Programs

Topic 4 Expressions and variables

COMP 202. Java in one week

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

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

Chapter 2: Data and Expressions

First Java Program - Output to the Screen

I. Variables and Data Type week 3

CEN 414 Java Programming

Software Practice 1 Basic Grammar

Introduction to Java Applications

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Program Elements -- Introduction

Chapter 2: Basic Elements of Java

Full file at

Program Control Flow

Program Control Flow

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Chapter 3 Selection Statements

Handout 4 Conditionals. Boolean Expressions.

Chapter 4: Basic C Operators

Lesson 7 Part 2 Flags

CONDITIONAL EXECUTION

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Selenium Class 9 - Java Operators

Conditional Programming

Course Outline. Introduction to java

Computational Expression

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

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Elementary Programming

Basics of Java Programming

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

A Quick and Dirty Overview of Java and. Java Programming

Chapter 2. Elementary Programming

2: Basics of Java Programming

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

Operators and Expressions

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

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

Building Java Programs Chapter 2

CS111: PROGRAMMING LANGUAGE II

H212 Introduction to Software Systems Honors

CS 106 Introduction to Computer Science I

Chapter 2 ELEMENTARY PROGRAMMING

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

CSE 142, Summer 2014

Chapter 2 Primitive Data Types and Operations. Objectives

AP CS Unit 3: Control Structures Notes

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Condensed Java. 12-Oct-15

Getting started with Java

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Chapter 2 Elementary Programming

Expressions and Variables

Section 2: Introduction to Java. Historical note

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Introduction to Computer Science Unit 2. Notes

Transcription:

More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input Assignment Constants Selection 11 October 2007 Ariel Shamir 2 Circle Calculations 2πr r? π = 3.1415927 πr 2 11 October 2007 Ariel Shamir 3 1

Outline of a Program class CircleCalc { public static void main(string[] args) { // my code should come here // as s 11 October 2007 Ariel Shamir 4 CircleCalc First Attempt class CircleCalc {??? public static void main(string[] args) { double r = 3.0; System.out.println(2.0 * 3.1415927 * r); System.out.println(3.1415927 * 3.1415927 * r); Can you see a problem? 11 October 2007 Ariel Shamir 5 Variables Usage One of the most important roles of programs is to deal with data. Data is most often put in variables for example: Numbers in input to be computed. A word written. A word read by the program. The date. 11 October 2007 Ariel Shamir 6 2

Variables A variable is an identifier that represents a storage to hold a particular type of data. Variables are actually a better name for an address in memory. count (integer) radius (real) 3456 3457 3458 3459 3500 3501 25 13.85 11 October 2007 Ariel Shamir 7 Variable Types Variables must have a type. The type is the inner representation of the variable in the computer. The size of the memory allocated depends on the type. Type and size are very close terms in the computer world. 11 October 2007 Ariel Shamir 8 Variable Declaration Variables must be declared before they can be used (declaration ): Syntax: <Type> <variable_name> [,<name>] ; Examples: char c; int x1,x2,x3; double r; 11 October 2007 Ariel Shamir 9 3

Variables Memory Allocation Upon declaration memory of appropriate size is allocated. The address of the beginning of the piece of memory is associated with the variable name. short count; 3456 3457 3458 3459 3500 3501 float radius; 25 13.85 11 October 2007 Ariel Shamir 10 Variable Initialization Variables must be initialized before they can be used. Syntax: <variable_name> = <value>; Examples: x = 3; c = c ; myvalue = 1.00003; 11 October 2007 Ariel Shamir 11 Variable List Initialization A list of any size of variables of the same type can be initialized to the same value: Syntax: <variable1> = <variable2> = <variable3> = <value> ; Examples: x = y = my = account = degrees = 9 ; 11 October 2007 Ariel Shamir 12 4

Initialization During Declaration Both operations (declaration and initialization) can be performed in the same line: <type> Examples: int x=3; char c= c ; <variable_name> = <value>; float myvalue=1.0003f; 11 October 2007 Ariel Shamir 13 Variables Example class VariablesDeclerationExample { public static void main (String[] args) { short weeks = 14; int numberofstudents = 120; double averagefinalgrade = 78.6; System.out.println(weeks); System.out.println(numberOfStudents); System.out.println(averageFinalGrade); 11 October 2007 Ariel Shamir 14 CircleCalc Second Attempt class CircleCalc { public static void main(string[] args) { double r = 3.0; double circum, area; circum = 2 * 3.1415927 * r; area = 3.1415927 * r * r; System.out.println( Circumference: + circum); System.out.println( Area: + area); 11 October 2007 Ariel Shamir 15 5

Operators Java has 37 tokens that are operators. Java operators can be either: Unary operator - takes a single value Binary operator - takes two values Java binary operators are written in the infix notation: <operand1> <operator> <operand2> The operator is written between operands. 11 October 2007 Ariel Shamir 16 Operators Tokens + - * / % ++ -- > < ==!= <= >= =? :! && ^ ~ & << >> >>> += -= *= /= %= &= = ^= <<= >>= >>>= 11 October 2007 Ariel Shamir 17 Expressions An expression can consist of a combination of operators and operands. Operands can be literal values, variables, or expressions by themselves (recursive). Types of expressions: Arithmetic expression: 12.3+3*4 Boolean expression: grade > 100 String expression: abc + d 11 October 2007 Ariel Shamir 18 6

Arithmetic Operators Binary: + addition x+y - subtraction x-y * multiplication x*y / division x/y % modulo remainder x%y Unary: - negation a = -34; 11 October 2007 Ariel Shamir 19 Operators Semantics The result of an arithmetic expression depends on the type of the operands: 3.0 / 2.0 == 1.5 3 / 2.0 == 1.5 3.0 / 2 == 1.5 3 / 2 == 1-3 / 2 == -1 11 October 2007 Ariel Shamir 20 Precedence The order in which operands are evaluated in expressions is determined by a welldefined precedence hierarchy. Operators at the same level of precedence are evaluated according to their associativity (right to left or left to right). Parentheses can be used to change precedence. 11 October 2007 Ariel Shamir 21 7

Precedence Example The usual rules apply: multiplication and division before addition and subtraction etc. and from left to right: 1 2 2 / 3 * ( 4 + 6 ) - 7 / 3 3 5 4 11 October 2007 Ariel Shamir 22 More Examples Expression 2 + 3 * 4 / 2 3 * 13 + 2 (3 * 13) + 2 3 * (13 + 2) 4 * (11-6) * (-8 + 10) (5 * (4-1)) / 2 Result 8 41 41 45 40 7 11 October 2007 Ariel Shamir 23 String Type String is the type of a line of text: I am a String. It is a first example of a reference data type (not a primitive type). It is widely used. 11 October 2007 Ariel Shamir 24 8

String Concatenation The + operator between strings has the meaning of String concatenation. When we apply + upon a String and a value of another type, that value is first converted into a String and the result is the concatenation of the two Strings. 11 October 2007 Ariel Shamir 25 Concatenation Example class AntarticaCode { public static void main(string[] args) { System.out.print( The international + code ); System.out.println( for Antarctica is + 762); Output: The international code for Antarctica is 762 11 October 2007 Ariel Shamir 26 Getting Input You are already acquainted with one way of output: System.out.println(... ) How do we get input? read from keyboard? Just as System.out is an object that represents the standard output (screen), System.in is an object that represents the standard input (keyboard). We can read directly from System.in, however it is a bit complicated. An easier way: use the Scanner class. 11 October 2007 Ariel Shamir 27 9

The Scanner Class System.out.println( Enter number of items: ); Scanner sc = new Scanner(System.in); int numberofitems = sc.nextint(); You may use it to read any primitive data types by calling its methods: bollean b = sc.nextboolean(); float f = sc.nextfloat(); double d = sc.nextdouble(); To use the Scanner class, you must include the line: import java.util.scanner; at the head of your file. 11 October 2007 Ariel Shamir 28 CircleCalc Third Attempt class CircleCalc { public static void main(string[] args) { double r, circum, area; Scanner sc = new Scanner(System.in); System.out.println( Please enter radius: ); r = sc.nextint(); //or maybe nextdouble()? circum = 2 * 3.1415927 * r; area = 3.1415927 * r * r; System.out.println( Circumference: + circum); System.out.println( Area: + area); 11 October 2007 Ariel Shamir 29 Example - Adding Two Numbers // Requests two integers and prints their sum class AdditionExample { public static void main(string[] args) { int a,b; Scanner sc = new Scanner(System.in); System.out.println( Please enter first number: ); a = sc.nextint(); System.out.println( Please enter second number: ); b = sc.nextint(); int sum = a + b; System.out.println( The sum is + sum); 11 October 2007 Ariel Shamir 30 10

The Assignment Statement Stores a new value into a variable. The most common computer instruction. Syntax: <variable_name> = <expression>; Examples: x = 3+(2*7); c = c ; myvalue = 1.00003/5.7+2.0; 11 October 2007 Ariel Shamir 31 Assignment Evaluation The assignment has a left side and a right side : <left_side> = <right_side>; The left side is usually a variable name and the right side some expression. The computer first evaluates the right side and only then assigns the value of the this evaluation to the left side. 11 October 2007 Ariel Shamir 32 Assignment Example class MyIncome { public static void main (String[] args) { Assignment Initialization int year = 2000; float monthincome = 10.4f; float bonus = 8.8f; float income = 12 * monthincome + bonus; System.out.println( in +year+ income was +income); year = 2001; bonus = 0; income = 12 * monthincome + bonus; System.out.println( in +year+ income was +income); 11 October 2007 Ariel Shamir 33 11

Blocks Block is the simplest type of composite. { // s It implements grouping of a sequence of s into a single. Block can be empty without s! 11 October 2007 Ariel Shamir 34 Block Scope { float k; // declaration k = (k+5)/32; // assignment (?) System.out.println(k); // call A variable k declared inside a block is completely inaccessible and invisible from outside that block. Such a variable is called local to the block. 11 October 2007 Ariel Shamir 35 Constants A constant is an identifier that is similar to a variable except that its value cannot be changed. You cannot assign to a constant! The final modifier is used for constant declaration: final <type> <Variable_name> = <value>; Example: final int MAX_GRADE=100; 11 October 2007 Ariel Shamir 36 12

CircleCalc Final Version! // Reads the radius of a circle and prints // its circumference and area class CircleCalc { static final double PI = 3.1415927; public static void main(string[] args) { double r, circum, area; Scanner sc = new Scanner(System.in); system.out.println( Please enter radius: ); r = sc.nextint(); circum = 2 * PI * r; area = PI * r * r; System.out.println( Circumference: + circum); System.out.println( Area: + area); 11 October 2007 Ariel Shamir 37 Relational and Conditional Operators > greater than >= greater than or equal to < less than <= less than or equal to = = equal to! = not equal to 11 October 2007 Ariel Shamir 38 Boolean Expressions Expressions that use conditional operators are called Boolean expressions. Boolean expressions can have only two values: true False Examples: 5 >= 2 3+6 == 1+7 5!= 8+9 11 October 2007 Ariel Shamir 39 13

Boolean Operators Operator && ^! Use exp1 && exp2 exp1 exp2 exp1 ^ exp2!exp Returns true if exp1 and exp2 are both true, conditionally evaluates exp2 either exp1 or exp2 is true, conditionally evaluates exp2 if exp1 or exp2 is true but not both exp is false 11 October 2007 Ariel Shamir 40 Truth Tables or && and ^ xor T F T F T F T T T T T F T F T F T F F F F F T F 11 October 2007 Ariel Shamir 41 Bit-wise Operators Perform the operation on each bit Operator Use Evaluates ~ ~exp1 Flips all the bits of exp1 & exp1 & exp2 Always evaluates exp1 and exp2 exp1 exp2 Always evaluates exp1 and exp2 ~10000101 = 01111010 10000101 10110001 = 10110101 10000101 & 10110001 = 10000001 11 October 2007 Ariel Shamir 42 14

Program Flow (Up Till Now) 11 October 2007 Ariel Shamir 43 Selection Statement selection? 11 October 2007 Ariel Shamir 44 If Statement Doing something under some condition: if (Boolean_condition) ; Boolean_condition is a Boolean expression that can have true or false values. If the value is true than is performed, otherwise (the value is false) is skipped. 11 October 2007 Ariel Shamir 45 15

If Flow Chart If? true false 11 October 2007 Ariel Shamir 46 Boolean Expression Example if ( x<1 x%2!=0 ) { System.out.println( x is not a positive even number! ); return; if ( y+2 < x &&!(y == 17) ) { System.out.println( y is not 17 and is smaller than x by more than 2! ); return; 11 October 2007 Ariel Shamir 47 If Statement Example class FailTest { public static void main(string[] args) { System.out.println( Enter your grade: ); Scanner sc = new Scanner(System.in); int grade = sc.nextint(); System.out.println( Your grade is: + grade); if (grade < 60) { System.out.println( You failed! ); 11 October 2007 Ariel Shamir 48 16

If.. Else Statement A choice between doing two things: if (Boolean_condition) 1; else 2; If the Boolean_condition is true, 1 is executed; if the condition is false, 2 is executed. 11 October 2007 Ariel Shamir 49 If..Else Flow Chart true If..else? false (else clause) 11 October 2007 Ariel Shamir 50 If.. Else Example class FailTest { public static void main(string[] args) { System.out.println( Enter your grade: ); Scanner sc = new Scanner(System.in); int grade = sc.nextint(); System.out.println( Your grade is: + grade); if (grade < 60){ else { System.out.println( You failed!! ); System.out.println( You passed!! ); 11 October 2007 Ariel Shamir 51 17

Nested If s if (a!= b) { if (a > b) { System.out.println(a + is greater ); else { System.out.println(b + is greater ); else { System.out.println( They are equal! ); 11 October 2007 Ariel Shamir 52 Always Use Blocks! if (grade >= 60) sum = sum + grade; avg = sum / NUM_STUDENTS; Problem?... So after thinking the programmer adds: if (grade >= 60) sum = sum + grade; count = count+1; avg = sum / count; 11 October 2007 Ariel Shamir 53 18