More on methods and variables. Fundamentals of Computer Science Keith Vertanen

Similar documents
Static methods. Not actually a valid Java static method. Fundamentals of Computer Science Keith Vertanen

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

Designing data types. Fundamentals of Computer Science I

JAVA OPERATORS GENERAL

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

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

CS 231 Data Structures and Algorithms, Fall 2016

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2012

Prof. Navrati Saxena TA: Rochak Sachan

Java Programming Language. 0 A history

Computational Expression

Programming Basics. Digital Urban Visualization. People as Flows. ia

Java Simple Data Types

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Conditionals, Loops, and Style

Selenium Class 9 - Java Operators

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Fundamentals of Programming Data Types & Methods

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Fall 2017 CISC124 9/16/2017

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Key Java Simple Data Types

Java Simple Data Types

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

CONDITIONAL EXECUTION

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Methods. Eng. Mohammed Abdualal

PROGRAMMING FUNDAMENTALS

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2015

MODULE 02: BASIC COMPUTATION IN JAVA

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

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Array. Prepared By - Rifat Shahriyar

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

DATA TYPES AND EXPRESSIONS

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

Datatypes, Variables, and Operations

Variables and data types

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Chapter 1 Introduction to java

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

Software Practice 1 Basic Grammar

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Getting started with Java

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2013

CS180. Exam 1 Review

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Program Fundamentals

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

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Exercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CS Week 5. Jim Williams, PhD

Lecture 5: Methods CS2301

Expressions & Flow Control

Exam 1. CSC 121 Spring Lecturer: Howard Rosenthal. March 1, 2017

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

CS115 Principles of Computer Science

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

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

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

Introduction to Arrays

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Key Differences Between Python and Java

AP COMPUTER SCIENCE A

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

Lecture Set 4: More About Methods and More About Operators

Darrell Bethea May 25, 2011

4 Programming Fundamentals. Introduction to Programming 1 1

Introduction to Java

Java is an objet-oriented programming language providing features that support

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Introduction to Programming Using Java (98-388)

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

Prelim 1. CS 2110, 13 March 2018, 5:30 PM Total Question Name Short answer

Operators in java Operator operands.

AP Computer Science Unit 1. Programs

Place your name tag here

Chapter 2: Programming Concepts

Topics. Chapter 5. Equality Operators

Getting started with Java

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Write a program which converts all lowercase letter in a sentence to uppercase.

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

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Java generics. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

AP Computer Science A Unit 7. Notes on Arrays

Transcription:

More on methods and variables Fundamentals of Computer Science Keith Vertanen

Terminology of a method Goal: helper method than can draw a random integer between start and end (inclusive) access modifier return type parameters / arguments public static int getrandomnum(int start, int end) return (int) (Math.random() * (end - start + 1)) + start; return statement method name Naming convention: start lowercase, uppercase each new word 2

Array parameters Arrays can be passed as arguments public class AverageArray public static double average(int [] nums) long total = 0; for (int i = 0; i < nums.length; i++) total += nums[i]; return (double) total / (double) nums.length; public static void main(string [] args) int [] vals = new int[1000]; for (int i = 0; i < vals.length; i++) vals[i] = RandomUtil.getRandomNum(1, 10); System.out.println("avg " + average(vals)); % java AverageArray avg 5.508 3

Array as a return value Arrays can be returned from methods Method must create and fill in the array public class ReturnArray public static double [] getrandomarray(int N) double [] result = new double[n]; for (int i = 0; i < N; i++) result[i] = Math.random(); return result; public static void main(string [] args) double [] randnums = getrandomarray(integer.parseint(args[0])); for (int i = 0; i < randnums.length; i++) System.out.println("randNums[" + i + "] = " + randnums[i]); 4

Pass by value Java passes parameters by value (by copy) Changes to primitive type parameters do not persist after method returns Primitive types: int, double, char, long, boolean public static int sum(int a, int b) int result = a + b; a = 0; b = 0; return result; int c = 2; int d = 3; System.out.println("sum = " + sum(c, d)); System.out.println("c = " + c); System.out.println("d = " + d); % java PassByVal sum = 5 c = 2 d = 3 5

Pass by value Java passes parameters by value (by copy) Changes to the immutable String type parameters do not persist after the method public class StringPuzzler public static void printstuff(string word) word = "best"; System.out.print(word); word = "bestest"; % java StringPuzzler It was the best worst of times public static void main(string [] args) String word = "worst"; System.out.print("It was the "); printstuff(word); System.out.print(" " + word + " of times"); 6

Changing an array parameter Methods can change elements of passed array Changes DO persist after the method public class ArrayClearer public static void clear(int [] nums) for (int i = 0; i < nums.length; i++) nums[i] = 0; public static void main(string [] args) int [] scores = 90, 85, 99, 45; for (int i = 0; i < scores.length; i++) System.out.print(scores[i] + " "); System.out.println(); clear(scores); for (int i = 0; i < scores.length; i++) System.out.print(scores[i] + " "); % java ArrayClearer 90 85 99 45 0 0 0 0 7

Java primitive types (plus String) Java type what it stores examples default value byte short int long tiny integer values -128 to 127 small integer values -32,768 to 32,767 integer values -2,147,483,648 to 2,147,483,647 big integer values -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 3-87 -3433 123 42 1234 5454-43984938 double floating-point values 9.95 3.0e8 float less precise floating-point values 9.95f 3.0e8f boolean truth values true false 0 0 0 0 0.0 0.0 false char characters 'a', 'b', '!' '\u0000' String Sequences of characters "Hello world!" null 8

Equality: integer primitives Boolean operator == See if two variables are exactly equal i.e. they have identical bit patterns Boolean operator!= See if two variables are NOT equal i.e. they have different bit patterns int a = 5; if (a == 5) System.out.println("yep it's 5!"); while (a!= 0) a--; This is a safe comparison since we are using an integer type. 9

Equality: floating-point primitives Floating-point primitives i.e. double and float Only an approximation of the number Use == and!= at your own peril double a = 0.1 + 0.1 + 0.1; double b = 0.1 + 0.1; double c = 0.0; if (a == 0.3) System.out.println("a is 0.3!"); if (b == 0.2) System.out.println("b is 0.2!"); if (c == 0.0) System.out.println("c is 0.0!"); 10

Equality: floating-point primitives Floating-point primitives i.e. double and float Only an approximation of the number Floating-point numbers are shoved into a binary number. 32 bits for a float, 64-bits for a double 11

Equality: floating-point primitives Floating-point primitives i.e. double and float Only an approximation of the number Use == and!= at your own peril double a = 0.1 + 0.1 + 0.1; double b = 0.1 + 0.1; double c = 0.0; if (a == 0.3) System.out.println("a is 0.3!"); This works as long as no calculation has been done on 0.0 value and both are typed double. if (b == 0.2) System.out.println("b is 0.2!"); if (c == 0.0) System.out.println("c is 0.0!"); b is 0.2! c is 0.0! 12

Safe floating-point equality check Floating-point primitives Check if sufficiently close to target value double a = 0.1 + 0.1 + 0.1; double b = 0.1 + 0.1; double c = 0.0; final double EPSILON = 1e-10; if (Math.abs(a - 0.3) < EPSILON) System.out.println("a is 0.3!"); if (Math.abs(b - 0.2) < EPSILON) System.out.println("b is 0.2!"); if (c == 0.0) System.out.println("c is 0.0!"); a is 0.3! b is 0.2! c is 0.0! 13

Equality: String variables Comparing String variables Using boolean operators ==,!= will compile and run BUT: Does not actually compare text in the String variables Big cause of bugs for Java beginners! String a = "hello"; String b = "hello"; String c = "hell" + "o"; String d = "hell"; d = d + "o"; if (a == b) System.out.println("a equals b!"); if (b == c) System.out.println("b equals c!"); if (c == d) System.out.println("c equals d!"); a equals b! b equals c! 14

Equality: String variables Check equality with equals() method Each letter must be the same (including case) String a = "hello"; String b = "hello"; String c = "hell" + "o"; String d = "hell"; d = d + "o"; if (a.equals(b)) System.out.println("a equals b!"); if (b.equals(c)) System.out.println("b equals c!"); if (c.equals(d)) System.out.println("c equals d!"); a equals b! b equals c! c equals d! 15

Summary Static methods Can take arrays as parameters Can return an array as a result Method is responsible for creating and filling array Changing parameters in a method Changes to primitive types DO NOT persist Changes to String types DO NOT persist Changes to elements of arrays DO persist Primitive types have default values Watch out for String null default Testing for equality Be careful comparing double variables with ==,!= Don't compare String variables with ==,!= 16