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

Similar documents
COMP 250: Java Reference Types & Object Oriented Programming

Introduction to Programming Using Java (98-388)

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.

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

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

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

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

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

Lecture 4: Introduction to Java and your Development Environment

Zheng-Liang Lu Java Programming 45 / 79

Chapter 2. Elementary Programming

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

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

Chapter 2 Elementary Programming

Chapter 1: Introduction to Computers, Programs, and Java

COMP 202 Java in one week

PROGRAMMING FUNDAMENTALS

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

CS171:Introduction to Computer Science II

Java Classes: Math, Integer A C S L E C T U R E 8

Chapter 2: Using Data

Pace University. Fundamental Concepts of CS121 1

VARIABLES AND TYPES CITS1001

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

Computer Science is...

Important Java terminology

Lecture 5: Methods CS2301

Example: Computing prime numbers

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

MODULE 02: BASIC COMPUTATION IN JAVA

CS 231 Data Structures and Algorithms, Fall 2016

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

CS 211: Methods, Memory, Equality

Last Class. While loops Infinite loops Loop counters Iterations

CEN 414 Java Programming

COMP 202. Java in one week

COMP-202: Foundations of Programming

Fundamentals of Programming Data Types & Methods

Chapter 02: Using Data

COMP 202 Java in one week

CS171:Introduction to Computer Science II

Programming with Java

Lecture Set 4: More About Methods and More About Operators

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Chapter 2: Basic Elements of Java

Lecture Set 4: More About Methods and More About Operators

Chapter 2 ELEMENTARY PROGRAMMING

Java Identifiers, Data Types & Variables

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

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

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

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

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

CS111: PROGRAMMING LANGUAGE II

Program Fundamentals

CS 106 Introduction to Computer Science I

Full file at

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Building Java Programs

( &% class MyClass { }

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

Java Classes & Primitive Types

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

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

Loops. CSE 114, Computer Science 1 Stony Brook University

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Software Practice 1 Basic Grammar

Getting started with Java

New Concepts. Lab 7 Using Arrays, an Introduction

Research Group. 2: More types, Methods, Conditionals

Getting started with Java

Building Java Programs

Java Classes & Primitive Types

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

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

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

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

JAVA Programming Fundamentals

EXERCISES SOFTWARE DEVELOPMENT I. 04 Arrays & Methods 2018W

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

BM214E Object Oriented Programming Lecture 4

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Software and Programming 1

Fall 2017 CISC124 9/16/2017

CS111: PROGRAMMING LANGUAGE II

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Chapter 2 Primitive Data Types and Operations. Objectives

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

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

egrapher Language Reference Manual

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

CHAPTER 7 OBJECTS AND CLASSES

Following is the general form of a typical decision making structure found in most of the programming languages:

Computational Expression

Chapter 1. Introduction to Computers and Programming. M hiwa ahmad aziz

DATA TYPES AND EXPRESSIONS

Transcription:

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

Variables and types [Downey Ch 2] Variable: temporary storage location in memory. It has a name (to refer to it) a type (to describe what kind of information it can store). a value (content stored in memory) Two kinds of types: Primitive types (seen today) Classes (next lecture) public class VariablesExample { public static void main(string args[]) { int age; // age can store an integer float pi; age = 29; pi = 3.14; Memory (RAM) // float can store a decimal number 2

[Downey Ch 2] Primitive types Type Size Description Range byte 8-bit signed integer [-128,127] char 16-bit integer [0, 65536] (encodes a, b ) short 16-bit signed integer [-32768,32767] int 32-bit signed integer [-2147483648, 2147383647] long 64-bit signed integer [-9223372036854775807, 9223372036854775806] float 32-bit decimal number 1.40239e-45 to 3.402823e+38 double 64-bit decimal number 4.9406e-324 to 1.79769e+308 boolean 8-bit boolean true or false 3

[Downey Ch 2] Expressions and Assignments Expression: Piece of code that has a value of a certain type Assignment: Storing the value of an expression into a variable Syntax: <variable> = <expression> Examples: Memory (RAM) public class Expressions { public static void main(string args[]) { int i, j, k; float f, g; i = 5; j = i + 1; k = k * 2; // Compiling error: Why? j = j / 2; j + 10; // Legal, but useless. Why? g = j + 3.14; // Note the implicit conversion of j into a float f = 15 / 2; // f now has value 7.0. Why? f = ((float) i) / 2 // Explicit type conversion (casting) of i into a float. f is now 7.5 4

[Downey Ch 6.5-6.6] Boolean expressions Boolean expressions have value true or false. Operations on booleans: boolean a,b; int i = 5; int j = 2; a = ( i * j < 10 ); // a is NOT :! AND : && OR : b =!a; // b is a = (i+j < 10) && (i+j > 0); // a is b = ( i<0 ) ( j>1 ) ; // b is a =! ( b && ( i>0 j<i ) ); // a is 5

Exercise public class Exercise { i j f a b c public static void main(string args[]) { int i,j; - - float f; - - - boolean a, b; - - - - - char c = f ; - - - - - f f = i; // compilation error: i is not initialized i = 9; 9 - - - - f a = (f > 100); // compilation error: f is not initialized f = i; 9-9.0 - - f b = true; 9-9.0 - T f a = ( b (12345.67*i - f/0.02345 == 0.003464) ); 9-9.0 T T f j = i; 9 9 9.0 T T f j = j + 1; // value of j: 10, value of i is still 9 9 10 9.0 T T f i = f + 3.3; // error: a float value cannot be stored in an int i = (int) (f + 3.3); // the float value 12.3 is cast into an int. 12 10 9.0 T T f // It becomes 12, so i becomes 12 b = b && ( (i == j) (!b f > 10) ); 12 10 9.0 T F f 6

[Downey Ch 4.1-4.4] Conditionals Syntax: if (<boolean expression>) <statementblock1> [else <statementblock2>] Executes <statementblock1> only if <boolean expression> is true. Otherwise <statementblock2> is executed. /* Determines if a point (x,y) is inside a circle of radius r centered at (a,b) */ if ( (a-x)*(a-x) + (b-y)*(b-y) <= r*r ) { System.out.println( The point is inside the circle"); if ( (x==a) && (y==b) ) System.out.println( It is the center ); else { System.out.println( The point is outside the circle ); // other statements could be here Note: If the statement block contains a single statement, then the { 7 can be omitted.

[Downey Ch 7.1-7.3] while loops Syntax: while (<boolean expression>) <statementblock> Keeps executing <statementblock> repeatedly as long as <boolean expression> is true. If <boolean expression> is false from the beginning, then <statement> is never executed. int n = 32; int i = 0; int exp = 1; while (exp < n) { i++; // equivalent to i = i +1; exp = exp * 2; // we could also write exp *= 2; // What is the value of exp and i at the end? 8

[Downey Ch 7.1-7.3] do-while loops do <statementblock> while (<boolean expression>) Same as while-loop but <boolean condition> is checked after executing <statementblock>, so <statement> is always executed at least once. // Keep asking for a price as long as the number entered is not positive double price = 0; String line; // String is a special type of variable. More about strings next week do { System.out.println("Enter price of item:"); line = stndin.readline(); // Read a line from keyboard price = Double.parseDouble(line) ; // Parse the line to get a double while (price<=0); 9

For loops [Downey Ch 12.4] for (<statement1>; <boolean expression>; <statement2>) <statementblock3> Equivalent to: <statement1> while (<boolean expression>) { <statementblock3> <statement2> int n=5; int s=0; int i; for (i = 0; i < n; i++ ) { What does this print? s = s + i; System.out.println( Value of s: + s); 10

What does this print? int n=5; for(int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print( i ); System.out.println(""); // print the end of line Memory (RAM) Output 11

Arrays [Downey Ch 12] Arrays are used to store and manipulate several variables of the same type Array X: To access the i-th element: i = 5; X[i] = 2; int a = X[i] + 1; Note: first element is at index 0. 0 1 2 3 4 5 6 7 8 9 10 11 12 X.length is the number of elements in X (here, it s 13) Java makes sure you don't write outside arrays: ArrayIndexOutOfBoundsException gets thrown if you try 12

Arrays in Java [Downey Ch 12] Declaration: Memory (stack) a x y double[] a; // a will be array of double. null null null int[] x,y; // x and y will both be arrays of ints // IMPORTANT: At this point, a, x, and y are references to null arrays a[ 3 ] = 2; // would cause error because a is null Allocation a = new double[10]; x = new int[5]; Memory (stack) a x y null Memory (heap) Array a Array x 13

Arrays in Java Memory (stack) a x y Accessing elements a[ 3 ] = 3.1; x[ 0 ] = 1; a[ x[ 0 ] ] = 1.5; Memory (heap) y[ 3 ] = 2; // compiling error. Why? x[ a[ 1 ] ] = 3; // compiling error. Why? a[ 10 ] = 3; // run-time error. ArrayIndexOutOfBoundsException gets thrown Assignments with arrays y=x; y[ 3 ]=9; // the value of x[3] is now x[ 2 ]=4; // the value of y[2] is now a = x; // compil. error: a and x have different types x = new int[ y[2] ]; x[3] = 5; // the value of y[3] is now y = new int[3]; Memory (stack) a x y null Memory (heap) 14

[Downey Ch 12] Multi-dimensional arrays Arrays can have more than one dimension: double matrix [ ] [ ] = new double[ 10 ] [ 10 ]; // initialize the matrix to zero for ( int i=0; i<10; i++ ) { for ( int j=0; j<10; j++ ) { matrix[ i ][ j ] = 0; // make it an identity matrix for ( int i=0; i<10; i++ ) matrix[ i ][ i ]=1; (Image Source: https://i.stack.imgur.com/yfgwe.png) 15

My first Java program Methods [Downey Ch 2] /* This programs prints a welcoming statement */ public class Welcome { // Every executable class have to contain a method called main like below Method (a.k.a. function, procedure, or routine): // When the class is executed, main is the first method to be called public static void main(string args[]) { Piece of code that carries a specific computation Can be called (executed) from anywhere in the code (if they are public) Can take one or more parameters (arguments) as input Can return a value (or an array, or any object) System.out.println( Welcome to Java! ); System.out.println( This is easy! ); public static float square( float x ) { float s = x*x; return s; 1) Compile Welcome.java 2) Run the program Local variables: File: Welcome.java Output: Variables Welcome declared to inside Java! a method (e.g. s). They 16 This are is discarded easy! after the method finishes being executed.

public class Course{ // prints welcoming statement. Takes no arguments. Returns nothing public static void printwelcome() { System.out.println("Welcome to COMP 250"); // prints welcoming statement for the given courseid. Returns nothing public static void printwelcome(int courseid) { System.out.println("Welcome to COMP + courseid); // returns the letter grade for the given percent grade public static char getgradefrompercent( double percent) { char grade; if ( percent >= 0.8 ) grade = 'A'; if ( percent >= 0.7 && percent < 0.8 ) grade = 'B'; if (percent < 0.7) grade = C ; return grade; public static void main (String args[]) { printwelcome(); printwelcome( 203 ); char g = getgradefrompercent(0.67); System.out.println("The grade is " + g); grade = A ; // compilation error: grade was only defined inside // getgadefrompercent method

Why are methods useful? Code re-use: a method can be called (executed) as often as we want, from anywhere in the program. No need to duplicate code. Encapsulation: Allows to think of a piece of code as a black box with a well-defined function. Users don t need to know how the method works, only what the method does: what are its arguments, what does it return. Makes program much easier to design, understand and debug

Parameter passing // Returns area a circle of radius r static double circlearea(double r) { double a = 3.1416 * r * r ; r = -1 ; // just to see what happens return a ; public static void main(string args[]) { double radius = 2; double area = circlearea(radius); System.out.println("Radius: + radius + " Area: + area ); Memory (stack) Output: Radius: 2 Area:12.5664

The truth about parameter passing What happens when a method is called? 1. The flow of execution of the code calling the method is interrupted. 2. If the methods takes some arguments, these arguments are allocated in memory (stack). They are initialized with the value of the arguments provided by the caller. 3. If variables are declared within the method, they are also put on the stack. 4. The code of the method is executed. This may include calling other methods. 5. When the code of the method has been executed, it may return a value to the caller. All local variables and arguments created on the stack are discarded. Summary: Parameters are passed by value The method called receives a copy of the parameters passed Since it is working a copy, the method can't change the original But watch out with arrays and non-primitive types...

static void stupidincrement( int a ) { int i = a; i = i + 1; System.out.println( In stupidincrement, i = + i); static void fakeassign( int a, int b) { a = b; System.out.println( In fakeassign, a = + a + and b = + b ); static int add(int a, int b) { int sum = a + b; a = 0; return sum; static public void main(string args[]) { int a = 1, b = 2, i = 9; fakeassign( a, b ); System.out.println( After fakeassign a: + a + b: + b + i: + i); stupidincrement(b); System.out.println( After stupid a: + a + b: + b + i: + i); stupidincrement(i); System.out.println( Again after stupid a: + a + b: + b + i: + i); a = add(i, a); System.out.println( After add a: + a + b: + b + i: + i); System.out.println( sum = + sum); // this causes an compilation error // because sum is only defined inside add

Output: In assign, a =2 and b = 2 AfterfakeAssign a:1 b:2 c:9 // because in fakeassign, we were working // only on copies of the original a and b In stupidincrement, i = 3 After stupidincrement, a: 1 b: 2 i: 9 // the variable i used in // fakeassign has nothing to do // with the variable i defined in main In stupidincrement, i = 10 Again after stupidincrement a: 1 b: 2 i: 9 After add a: 10 b: 2 i: 9

Parameter passing with arrays static void changearray( int a[] ) { System.out.println( First, a[0] is + a[0]); a[0]=2; System.out.println( Then, a[0] is " + a[0]); a = new int[2]; a[0]=3; System.out.println("Then, a[0] is " + a[0]); public static void main(string args[]) { int[] array; array = new int[3]; array[0] = 1; changearray(array); System.out.println("Finally, array[0] is " + array[0] );

Parameter passing with arrays Be careful with arrays and other reference types! When you pass a reference to a variable to a method, the method can use that reference to modify the value stored in memory.