Which is better?. Assume s1 and s2 are Strings: A.if (s1 == s2) {... } B.if (s1.equals(s2)) {... }

Slides:



Advertisements
Similar presentations
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
Advertisements

CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
17-Jun-15 Which is better?. 2 Assume s1 and s2 are Strings: A.if (s1 == s2) {... } B.if (s1.equals(s2)) {... } ?
18-Jun-15 Arrays. 2 A problem with simple variables One variable holds one value The value may change over time, but at any given time, a variable holds.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
22-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
Some administrative stuff Class mailing list: –send to with the command “subscribe”
26-Jun-15 Arrays. 2 A problem with simple variables One variable holds one value The value may change over time, but at any given time, a variable holds.
Object References. Objects An array is a collection of values, all of the same type An object is a collection of values, which may be of different types.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
ISBN Chapter 7 Expressions and Assignment Statements.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
General Issues in Using Variables
CSC 142 J 1 CSC 142 Arrays [Reading: chapter 10].
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
ISBN Chapter 7 Expressions and Assignment Statements.
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Chapter 8: Arrays.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Pointers. The structure of memory Computer memory is a linear sequence of addressable locations Addresses are numbered starting at zero In personal computers,
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
A Simple Quiz: Ask User Functions. By Lana Dyck under the direction of Professor Susan Rodger Duke University June 2009, added Part 2 July 2011.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
CSC 142 D 1 CSC 142 Instance methods [Reading: chapter 4]
Programming 101 EPGY Middle School Programming Adam Leeper.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Iterative Statements: while, for, do-while Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
CS 0401 Debugging Hints and Programming Quirks for Java by John C. Ramirez University of Pittsburgh.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
ITM © Port, Kazman1 ITM 352 Simple Arrays. ITM © Port, Kazman2 Arrays r Collections r Array basics m Declaration, allocation, and initialization.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #003 (February 14, 2015)
Introduction to Exceptions in Java CS201, SW Development Methods.
CS 536 © CS 536 Spring Introduction to Programming Languages and Compilers Charles N. Fischer Lecture 15.
27-Jun-16 Arrays. 2 Multiple values An array lets you associate one name with a fixed (but possibly large) number of values Arrays are like Python’s lists,
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Based on slides by Shawn.
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Lesson 2: Building Blocks of Programming
Class Structure 16-Nov-18.
Class Structure 28-Nov-18.
slides created by Ethan Apter
Which is better? 4-Dec-18.
Arrays 6-Dec-18.
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
slides created by Ethan Apter
Class Structure 25-Feb-19.
Which is better? 15-May-19.
Which is better? 28-May-19.
Classes and Methods 15-Aug-19.
Announcements Lab 5 due Wednesday at noon.
Week 7 - Monday CS 121.
Presentation transcript:

Which is better?

Assume s1 and s2 are Strings: A.if (s1 == s2) {... } B.if (s1.equals(s2)) {... }

Answer: B s1 == s2 tests whether s1 and s2 reference the same string; s1.equals(s2) tests whether they reference equal strings String s1 = "ABC"; String s2 = s1; String s3 = "ABC"; String s4 = "AB" + "C" All these strings are equal; but s4 is in a different memory location than the others, so the == test yields false

Which is better? Assume String s1; A.if (s1.equals("OK")) {... } B.if ("OK".equals(s1)) {... }

Answer: B s1.equals("OK") sends a message to s1 asking if it is equal to "OK" "OK".equals(s1) sends a message to "OK" asking if it is equal to s1 –This is legal, because "OK" is a String If s1 is null, then: s1.equals("OK") gives a NullPointerException "OK".equals(s1) gives false

Which is better? Assume int numbers[ ] = new int[100]; A.for (int i = 0; i < 100; i++) numbers[i] = i; B.for (int i = 0; i <= 99; i++) numbers[i] = i;

Answer: A for (int i = 0; i < 100; i++) is better than for (int i = 0; i <= 99; i++) Three reasons: –The first is more traditional –The array size is 100, not 99, so it’s more obvious where the number came from You have to do some arithmetic to get 99 –If you change the array size, a search for 100 won’t find the loop that uses 99

Which is better? Assume int numbers[ ] = new int[100]; A.for (int i = 0; i < 100; i++) numbers[i] = i; B.for (int i = 0; i < numbers.length; i++) numbers[i] = i;

Answer: B for (int i = 0; i < numbers.length; i++) is better than for (int i = 0; i < 100; i++) If you later decide to change the size of the numbers array, you only need to do it in the declaration; the for loop that uses length will automatically adjust

Which is better? Assume finished is a boolean variable: A.if (finished == true) {...} B.if (finished) {...}

Answer: B finished == true is redundant: –If finished is true, then finished==true will be true –If finished is false, then finished==true will be false The extra words don’t gain you anything –finished==true might seem more readable to a beginner, but you quickly learn to read the shorter form –Brevity in programming, as in writing, is a virtue –You can avoid the possible mistake of saying if (finished = true) {... }

Which is better? Assume foo, bar, and larger are integers A.if (foo > bar) larger = foo; else larger = bar; B.larger = foo > bar ? foo : bar;

Answer: neither For each of these, you have to look at the code carefully to make sure it is correct larger = Math.max(foo, bar); is easier to read and more obviously correct

Which is better? A.String s = "Hello"; B.String s = new String("Hello");

Answer: A "Hello" is special syntax to implicitly construct a string String s = new String("Hello"); actually constructs two strings: "Hello" constructs the first string, then it is given as a parameter to an explicit constructor, which constructs the second string

Which is better? Suppose p is a Panel with a BorderLayout and okButton is a Button : A.p.add(okButton, BorderLayout.NORTH); B.p.add(okButton, "North"); Note: BorderLayout.NORTH == "North"

Answer: A p.add(okButton, BorderLayout.NORTH); is strongly recommended over the shorter form p.add(okButton, "North") -- but why? Answer: better error detection –If you type p.add(okButton, "north"), there is no error, but it doesn’t do what you want –If you type p.add(okButton, BorderLayout.North) you will get a syntax error, because BorderLayout has no such variable as North

Which is better? Suppose n is an int and s is a String : A.s = Integer.toString(n); B.s = String.valueOf(n); C.s = new Integer(n).toString(); D.s = n + "";

Answer: D I prefer D ( s = n + ""; ) because: –It’s a common idiom, therefore easily recognized –It’s short –It works for any type

Which is better? Assume n is an integer: A.if (n < 0) n = 0; B.if (n < 0) n = 0; C.if (n < 0) { n = 0; }

Answer: C If, later on, you want to add a statement, it’s easy to make this mistake with B: –if (n < 0) System.out.println("n was " + n); n = 0; You won’t make this mistake with A or C –With C (using braces), you don’t have to change anything that’s already there –However, A (all on one line) is often convenient

Which is better? Assume n is an integer: A.int factorial = 1; for (int i = 2; i < n; i++) { factorial *= n; } B.int factorial = 1; int i = 1; for (i = 2; i < n; i++) { factorial *= n; }

Answer: A In most cases, you don’t care about the index of a for loop outside the loop –You typically give it an initial value in the loop –You typically already have its final value in some variable or by some simple computation If you don’t need a variable, you shouldn’t have that variable –It doesn’t help anything, and it might get in the way

Conclusions There are various ways to do things One way may be better than another because: –It’s easier to read and understand –It’s more familiar—the way things are usually done –It’s less error prone, or provides better error detection –It’s more efficient

The End