Review: Python Transi,on Warning

Similar documents
9/16/15. Review: Assign 0. Objec,ves. Review. Review: Python Transi,on Warning. What is the output? INTRO TO JAVA LIBRARIES

CISC 370: Introduction to Java

Objec+ves. Review. Basics of Java Syntax Java fundamentals. What are quali+es of good sooware? What is Java? How do you compile a Java program?

"Hello" " This " + "is String " + "concatenation"

Objec&ves. Packages Collec&ons Generics. Sept 28, 2016 Sprenkle - CSCI209 1

Why OO programming? want but aren t. Ø What are its components?

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Objec,ves. Review: Object-Oriented Programming. Object-oriented programming in Java. What is OO programming? Benefits?

Imports. Lexicon. Java/Lespérance 1. PROF. Y. LESPÉRANCE Dept. of Electrical Engineering & Computer Science

Programming with Java

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

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

Index COPYRIGHTED MATERIAL

CSI33 Data Structures

Object-oriented programming in Java. Sept 19, 2016 Sprenkle - CSCI Object References. weight = height = Chicken. weight = height = name =

Brief Summary of Java

EL2310 Scientific Programming

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

CS 231 Data Structures and Algorithms, Fall 2016

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Ø Interface methods are public by default

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

Programming with Java

Java+- Language Reference Manual

Creating Strings. String Length

Pace University. Fundamental Concepts of CS121 1

Chapter 2: Functions and Control Structures

Strings, Arrays, A1. COMP 401, Spring 2015 Lecture 4 1/20/2015

Full file at

C Programming Primer 8/31/15 1

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

STUDENT LESSON A10 The String Class

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

AP Computer Science A

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Java Bytecode (binary file)

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

CSC Web Programming. Introduction to JavaScript

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

8/25/17. Demo: Create application. CS2110, Recita.on 1. Arguments to method main, Packages, Wrapper Classes, Characters, Strings.

appreciate the difference between a char and a string understand and use the String class methods

5/23/2015. Core Java Syllabus. VikRam ShaRma

AP Programming - Chapter 6 Lecture

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Wrap up indefinite loops Text processing, manipula7on. Broader Issue: Self-driving cars. How do write indefinite loops in Python?

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Introduction to Programming Using Java (98-388)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Values and Variables 1 / 30

Introduction. C provides two styles of flow control:

More non-primitive types Lesson 06

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

Java Fall 2018 Margaret Reid-Miller

Ex: If you use a program to record sales, you will want to remember data:

USING LIBRARY CLASSES

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

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

Program Fundamentals

Eng. Mohammed S. Abdualal

9/23/15. Objec-ves. Assignment 2 Review. Review STATIC METHODS AND FIELDS. Sta-c Methods/Fields. Sta-c Methods

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Computer Programming : C++

9/19/12. Objectives. Assignment 2 Review. Code Review. Review. Testing. Code Review: Good Use of switch Statement

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Computer Programming I - Unit 5 Lecture page 1 of 14

egrapher Language Reference Manual

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

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

Using Java Classes Fall 2018 Margaret Reid-Miller

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

INTRODUCTION TO COMPUTER SCIENCE - LAB

Array Basics: Outline

Language Reference Manual

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Class Library java.lang Package. Bok, Jong Soon

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

In Java there are three types of data values:

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

10/7/15. MediaItem tostring Method. Objec,ves. Using booleans in if statements. Review. Javadoc Guidelines

Visual C# Instructor s Manual Table of Contents

Sept 26, 2016 Sprenkle - CSCI Documentation is a love letter that you write to your future self. Damian Conway

Learning objec<ves. Classes, Objects, and Methods. Problem Decomposi<on. Problem Decomposi<on (cont d)

BASIC ELEMENTS OF A COMPUTER PROGRAM

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

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

Programming Languages and Techniques (CIS120)

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

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

CSC 222: Object-Oriented Programming. Spring 2017

Transcription:

Objec,ves More Java fundamentals Ø java.lang classes: Math and String class Ø Control Structures Ø Arrays Sept 14, 2016 Sprenkle - CSCI209 1 Review: Python Transi,on Warning OK: You cannot redeclare a variable name in the same scope int x = 3; x = -3; Not OK: int x = 3; int x = -3; boolean x = true; Compiler errors Sept 14, 2016 Sprenkle - CSCI209 2 1

INTRO TO JAVA LIBRARIES Sept 14, 2016 Sprenkle - CSCI209 3 Java Libraries Organized into a hierarchy of packages java javax org lang net Object String util Arrays Fully qualified name: java.lang.string java.lang.* classes included by default in all Java programs Many, many more classes and packages Sept 14, 2016 Sprenkle - CSCI209 4 2

Java API Documenta,on API: Applica,on Programming Interface Ø What the class can do for YOU! Complete documenta,on of every class included with the JDK Ø Every method and variable contained in class http://docs.oracle.com/javase/8/docs/api Bookmark it! Ø Too many classes, methods to remember them all Ø Refer to it o\en Sept 14, 2016 Sprenkle - CSCI209 5 java.lang.math class Similar to Python s math module Included by default in every Java program Contains useful mathema,cal func,ons (methods) and constants (fields): Look at java.lang.math API online Ø http://docs.oracle.com/javase/8/docs/api/ Ø Note how API is specified Sept 14, 2016 Sprenkle - CSCI209 6 3

java.lang.math class Example Uses: method constant double y = Math.pow(x, a); double z = Math.sin(y); double d = Math.exp(4.59) * Math.PI; Use Classname.methodname() to call Math s methods because they re static static: for the class MathExample.java Sept 14, 2016 Sprenkle - CSCI209 7 java.lang.string class Similar func,onality to Python but different ways to use Strings are represented by double quotes: "" Ø Single quotes represent chars only Examples: String emptystring = ""; String nicegreeting = "Hello there."; String badgreeting = "What do you want?"; Sept 14, 2016 Sprenkle - CSCI209 8 4

Strings A char at each posi,on of String stringvar = "The Beatles"; chars End at stringvar.length()-1 'T' 'h' 'e' ' ' 'B' 'e' 'a' 't' 'l' 'e' 's' 0 1 2 3 4 5 6 7 8 9 10 Start at 0 index or position of characters Use charat method to access chars Length of the string: 11 stringvar.length() method Sept 14, 2016 Sprenkle - CSCI209 9 String method: charat A String is a collec,on of chars String teststring1 = "Demonstrate Strings"; char character1; char character2 = teststring1.charat(3); character1 = teststring1.charat(2); Sept 14, 2016 Sprenkle - CSCI209 10 5

String methods: substring Like slicing in Python String substring(int beginindex) Ø Returns a new String that is a substring of this string, from beginindex to end of this string String substring(int beginindex, int endindex) Ø Returns a new String that is a substring of this string, from beginindex to endindex-1 String language = "Java!"; String substr = language.substring(1); String substr2 = language.substring(2, 4); Python Sept 14, 2016 Gotcha: Can t use negative Sprenkle - CSCI209 numbers for indices as in Python 11 String Concatena,on Use + operator to concatenate Strings String nicegreeting = "Hello"; String firstname = "Clark"; String lastname = "Kent"; String blankspace = " "; String greeting = nicegreeting + "," + blankspace + firstname + blankspace + lastname; System.out.println(greeting); Prints Hello, Clark Kent Sept 14, 2016 Sprenkle - CSCI209 12 6

String Concatena,on If a String is concatenated with something that is not a String, the other variable is converted to a String automa,cally. int totalpoints = 110; int earnedpoints = 87; float testscore = (float) earnedpoints/totalpoints; System.out.println("Your score is " + testscore); Converted to a String Sept 14, 2016 Sprenkle - CSCI209 13 StringBuilders vs Strings Strings are read-only or immutable Ø Same as Python Use StringBuilder to manipulate a String Instead of crea,ng a new String using Ø String str = prevstr + " more!"; Use new keyword: allocate memory to a new object StringBuilder str = new StringBuilder( prevstr ); str.append(" more!"); Many StringBuilder methods Ø tostring() to get the resultant string back Sept 14, 2016 Sprenkle - CSCI209 14 7

Effec0ve Java: Code Inefficiency Avoid crea,ng unnecessary objects: String s = new String("text"); // DON T DO THIS Do this instead: String s = "text"; Why? Sept 14, 2016 Sprenkle - CSCI209 15 String Comparison: equals boolean equals(object anobject) Ø Compares this string to the specified object String string1 = "Hello"; String string2 = "hello"; boolean test; test = string1.equals(string2); test is false because the Strings contain different values Sept 14, 2016 Sprenkle - CSCI209 16 8

Python Gotcha: String Comparisons string1 == string4 will not yield the same result as string1.equals(string4) Ø == tests if the objects are the same not if the contents of the objects are the same Ø Similar to is operator in Python string1 string2 string4 Memory "same" "same" string1!= string4 BUT string1.equals(string4) Equals.java Sept 14, 2016 Sprenkle - CSCI209 17 String method: equalsignorecase Does what it s named! String string1 = "Hello"; String string2 = "hello"; boolean test; test = string1.equalsignorecase(string2); test is true! Sept 14, 2016 Sprenkle - CSCI209 18 9

String methods: and many more! boolean endswith(string suffix) boolean startswith(string prefix) int length() String tolowercase() String trim() : remove trailing and leading white space See java.lang.string API for all Sept 14, 2016 Sprenkle - CSCI209 19 CONTROL STRUCTURES Sept 14, 2016 Sprenkle - CSCI209 20 10

Review What is the syntax of a condi0onal statement in Python? Sept 14, 2016 Sprenkle - CSCI209 21 Control Flow: Condi,onal Statements if statement Ø CondiGon must be surrounded by () Ø Condi,on must evaluate to a boolean Ø Body is enclosed by { if mul,ple statements if (purchaseamount < availcredit) { System.out.println("Approved"); availablecredit -= purchaseamount; else System.out.println("Denied"); Don t need { if only one statement in the body Best practice: use { Sept 14, 2016 Sprenkle - CSCI209 22 11

Control Flow: Condi,onal Statements if statement if (purchaseamount < availcredit) { System.out.println("Approved"); else availablecredit -= purchaseamount; System.out.println("Denied"); Everything between { is a block of code Ø Has an associated scope Condition Block of code Sept 14, 2016 Sprenkle - CSCI209 23 Scoping Issues: Python Gotcha Everything between { is a block of code Ø Has an associated scope if (purchaseamount < availablecredit) { availablecredit -= purchaseamount; boolean approved = true; Out of scope Will get a compiler error if(! approved ) (cannot find symbol) System.out.println("Denied"); How do we fix this code? Sept 14, 2016 Sprenkle - CSCI209 24 12

Fixed Move approved outside of the if statement boolean approved = false; if (purchaseamount < availablecredit) { availablecredit -= purchaseamount; approved = true; if(! approved ) System.out.println("Denied"); Sept 14, 2016 Sprenkle - CSCI209 25 Logical Operators OperaGon Python Java AND && OR NOT! In Python, these are? Sept 14, 2016 Sprenkle - CSCI209 26 13

Logical Operators OperaGon Python Java AND and && OR or NOT not! Sept 14, 2016 Sprenkle - CSCI209 27 Control Flow: else if In Python, was elif if( x%2 == 0 ) { System.out.println("Value is even."); else if ( x%3 == 0 ) { System.out.println("Value is divisible by 3."); else { System.out.println("Value isn t divisible by 2 or 3."); What output do we get if x is 9, 13, and 6? Sept 14, 2016 Sprenkle - CSCI209 28 14

Control Flow: switch statement Like a big if/else if statement Works with variables with datatypes byte, short, char, int, and String int x = 3; switch(x) { case 1: System.out.println("It's a 1."); break; case 2: System.out.println("It's a 2."); break; default: System.out.println("Not a 1 or 2."); Sept 14, 2016 Sprenkle - CSCI209 29 Control Flow: switch statement switch(grade) { case a : case A : System.out.println("Congrats!"); break; case b : case B : System.out.println("Not too shabby!"); break; // Handle c, d, and f default: System.out.println("Error: not a grade"); Grades.java Sept 14, 2016 Sprenkle - CSCI209 30 15

Control Flow: while Loops while loop Ø Condi,on must be enclosed in parentheses Ø Body of loop must be enclosed in { if mul,ple statements int counter = 0; while (counter < 5) { System.out.println(counter); counter++; shortcut System.out.println("Done: " + counter); Sept 14, 2016 Sprenkle - CSCI209 31 Changing control flow: break Exits the current loop while ( <readingdata> ) { if( <somethingbad> ) { // shouldn t happen break; Sept 14, 2016 Sprenkle - CSCI209 32 16

Review How do you write a for loop in Python for coun,ng? Sept 14, 2016 Sprenkle - CSCI209 33 Control Flow: for Loop Very different syntax from Python Syntax: for (<init>; <condition>; <execution_expr>) Loop s counter variable, Usually used in condition Executed at end of each iteration. Typically increments or decrements counter Sept 14, 2016 Sprenkle - CSCI209 34 17

Control Flow: for Loop Example System.out.println("Counting down "); for (int count=5; count >= 1; count--) { System.out.println(count); shortcut System.out.println("Blastoff!"); What is the counter variable? What is the condi,on? What is the output? How wriqen in Python? Can t print out count with Blastoff. Why? Sept 14, 2016 Sprenkle - CSCI209 35 ARRAYS Sept 14, 2016 Sprenkle - CSCI209 36 18

Python Lists à Java Arrays A Java array is like a fixed-length list To declare an array of integers: int[] arrayofints; Ø Declara,on only makes a variable named arrayofints Ø Does not ini,alize array or allocate memory for the elements To declare and ini3alize array of integers: int[] arrayofints = new int[100]; new keyword: allocate memory to a new object Sept 14, 2016 Sprenkle - CSCI209 37 Array Ini,aliza,on Ini,alize an array at its declara,on: Ø int[] fibnums = {1, 1, 2, 3, 5, 8, 13; Value Position/index 1 1 2 3 5 8 13 0 1 2 3 4 5 6 Ø Note that we do not use the new keyword when alloca,ng and ini,alizing an array in this manner Ø fibnums has length 7 Sept 14, 2016 Sprenkle - CSCI209 38 19

Array Access Access a value in an array as in Python: Ø fibnums[0] Ø fibnums[x] = fibnums[x-1] + fibnums[x-2] Unlike in Python, cannot use nega,ve numbers to index items Sept 14, 2016 Sprenkle - CSCI209 39 Array Length All array variables have a field called length Ø Note: no parentheses because not a method int[] array = new int[10]; for (int i = 0; i < array.length; i++) { array[i] = i * 2; for (int i = array.length-1; i >= 0; i--) { System.out.println(array[i]); ArrayLength.java Sept 14, 2016 Sprenkle - CSCI209 40 20

Overstepping Array Length Java safeguards against overstepping length of array Ø Run,me Excep,on: Array index out of bounds Ø More on excep,ons later Example int[] array = new int[100]; Ø Aqempts to access or write to index < 0 or index >= array.length (100) will generate excep,on Sept 14, 2016 Sprenkle - CSCI209 41 Arrays Assigning one array variable to another èboth variables refer to the same array Ø Similar to Python Draw picture of below code: int [] fibnums = {1, 1, 2, 3, 5, 8, 13; int [] otherfibnums; otherfibnums = fibnums; otherfibnums[2] = 99; fibnums[2] and otherfibnums[2] are both equal to 99 System.out.println(otherFibNums[2]); System.out.println(fibNums[2]); Sept 14, 2016 Sprenkle - CSCI209 42 21

Array Copying Copy an array (element-by-element) using the arraycopy method in the System class System.arraycopy(from, fromindex, to, toindex, count); For example: int [] fibnums = {1, 1, 2, 3, 5, 8, 13; int [] othernums = new int[fibnums.length]; System.arraycopy(fibNums,0,otherNums,0,fibNums.length); othernums[2] = 99; System.out.println(otherNums[2]); System.out.println(fibNums[2]); fibnums[2] = 2, othernums[2]= 99 Sept 14, 2016 Sprenkle - CSCI209 43 Control Flow: foreach Loop Introduced in Java 5 Ø Sun calls enhanced for loop Iterate over all elements in an array (or Collec,on) Ø Similar to Python s for loop int[] a; int result = 0;... in for (int i : a) { result += i; http://docs.oracle.com/javase/ 1.5.0/docs/guide/language/ foreach.html for each int element i in the array a, the loop body is visited once for each element of a. Sept 14, 2016 Sprenkle - CSCI209 44 22

java.util.arrays Arrays is a class in java.util Methods for sor,ng, searching, deepequals, fill arrays To use class, need import statement Ø Goes at top of program, before class defini,on import java.util.arrays; ArraysExample.java Sept 14, 2016 Sprenkle - CSCI209 45 Summary: Python to Java Gotchas Every variable needs to be declared before it is used Every variable needs a sta,cally-declared data type Scope of variables Syntax Ø Semicolons at the end of statements Ø Braces around blocks of code Ø Keywords Sept 14, 2016 Sprenkle - CSCI209 46 23