Upload
others
View
12
Download
0
Embed Size (px)
Citation preview
9/12/16
1
Objec,ves• MoreJavafundamentalsØ java.langclasses:MathandStringclassØ ControlStructuresØ Arrays
Sept14,2016 Sprenkle-CSCI209 1
Review:PythonTransi,onWarning
• OK:
• NotOK:
Sept14,2016 Sprenkle-CSCI209 2
int x = 3;x = -3;
int x = 3;int x = -3;…boolean x = true;
Compilererrors
You cannot redeclare a variable name in the same scope
9/12/16
2
INTROTOJAVALIBRARIES
Sept14,2016 Sprenkle-CSCI209 3
JavaLibraries• Organizedintoahierarchyofpackages
Sept14,2016 Sprenkle-CSCI209 4
java
net
lang
util
Object
Arrays
Fully qualified name: java.lang.StringString
java.lang.* classes included �by default in all Java programs
javaxorg Many, many more classes and packages
9/12/16
3
Sept14,2016 Sprenkle-CSCI209 5
JavaAPIDocumenta,on• API:Applica,onProgrammingInterfaceØ WhattheclasscandoforYOU!
• Completedocumenta,onofeveryclassincludedwiththeJDKØ Everymethodandvariablecontainedinclass
http://docs.oracle.com/javase/8/docs/api• Bookmarkit!
Ø Toomanyclasses,methodstorememberthemallØ Refertoito\en
Sept14,2016 Sprenkle-CSCI209 6
java.lang.Mathclass• SimilartoPython’smathmodule• IncludedbydefaultineveryJavaprogram• Containsusefulmathema,calfunc,ons(methods)andconstants(fields):
• Lookatjava.lang.MathAPIonlineØ http://docs.oracle.com/javase/8/docs/api/Ø NotehowAPIisspecified
9/12/16
4
Sept14,2016 Sprenkle-CSCI209 7
java.lang.Mathclass• ExampleUses:
double y = Math.pow(x, a);double z = Math.sin(y);double d = Math.exp(4.59) * Math.PI;
MathExample.java
methodconstant
UseClassname.methodname() tocallMath’smethodsbecausethey’restatic
static: fortheclass
Sept14,2016 Sprenkle-CSCI209 8
java.lang.String class• Similarfunc,onalitytoPythonbutdifferentwaystouse
• Stringsarerepresentedbydoublequotes:""Ø Singlequotesrepresentchars only
• Examples:
String emptyString = "";String niceGreeting = "Hello there.";String badGreeting = "What do you want?";
9/12/16
5
Strings• Acharateachposi,onofStringstringvar = "The Beatles";
Sept14,2016 Sprenkle-CSCI209 9
'T' 'h' 'e' ' ' 'B' 'e' 'a' 't' 'l' 'e' 's'0 1 2 3 4 5 6 7 8 9 10
index or position ofcharacters
chars
Length of the string: 11
stringvar.length() methodStart at 0
End at stringvar.length()-1
Use charAt method to access chars
Sept14,2016 Sprenkle-CSCI209 10
Stringmethod:charAt• AStringisacollec,onofchars
String testString1 = "Demonstrate Strings";
char character1;char character2 = testString1.charAt(3);character1 = testString1.charAt(2);
9/12/16
6
Sept14,2016 Sprenkle-CSCI209 11
Stringmethods:substring• LikeslicinginPython• String substring(int beginIndex)Ø ReturnsanewStringthatisasubstringofthisstring,
frombeginIndex toendofthisstring• String substring(int beginIndex, int endIndex)Ø ReturnsanewStringthatisasubstringofthisstring,
frombeginIndextoendIndex-1
String language = "Java!";String subStr = language.substring(1);String subStr2 = language.substring(2, 4);
Python Gotcha: Can’t use negative numbers for indices as in Python
Sept14,2016 Sprenkle-CSCI209 12
StringConcatena,on• Use+ operatortoconcatenateStringsString 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”
9/12/16
7
Sept14,2016 Sprenkle-CSCI209 13
StringConcatena,on• IfaStringisconcatenatedwithsomethingthatisnotaString,theothervariableisconvertedtoaStringautoma,cally.
int totalPoints = 110;int earnedPoints = 87;float testScore = (float) earnedPoints/totalPoints;
System.out.println("Your score is " + testScore);
ConvertedtoaString
Sept14,2016 Sprenkle-CSCI209 14
StringBuilders vsStrings• Stringsare“read-only”orimmutable
Ø SameasPython• UseStringBuildertomanipulateaString• Insteadofcrea,nganewStringusing
Ø String str = prevStr + " more!";• Use
• ManyStringBuildermethodsØ toString()togettheresultantstringback
StringBuilder str = new StringBuilder( prevStr );str.append(" more!");
new keyword: �allocate memory to a new object
9/12/16
8
Effec0veJava:CodeInefficiency• Avoidcrea,ngunnecessaryobjects:
• Dothisinstead:
Sept14,2016 Sprenkle-CSCI209 15
String s = new String("text"); // DON’T DO THIS
String s = "text";
Why?
Sept14,2016 Sprenkle-CSCI209 16
StringComparison:equals• boolean equals(Object anObject)Ø Comparesthisstringtothespecifiedobject
• testisfalsebecausetheStringscontaindifferentvalues
String string1 = "Hello";String string2 = "hello";boolean test;test = string1.equals(string2);
9/12/16
9
Sept14,2016 Sprenkle-CSCI209 17
PythonGotcha:StringComparisons• string1 == string4willnotyieldthesameresultasstring1.equals(string4)Ø ==testsiftheobjectsarethesame
• notifthecontentsoftheobjectsarethesameØ Similartois operatorinPython
"same"
"same"
string1string2
string4
Memory
string1 != string4BUTstring1.equals(string4)
Equals.java
Sept14,2016 Sprenkle-CSCI209 18
Stringmethod:equalsIgnoreCase• Doeswhatit’snamed!
• testistrue!
String string1 = "Hello";String string2 = "hello";boolean test;test = string1.equalsIgnoreCase(string2);
9/12/16
10
Sept14,2016 Sprenkle-CSCI209 19
Stringmethods:andmanymore!• boolean endsWith(String suffix)• boolean startsWith(String prefix)• int length()• String toLowerCase()• String trim():removetrailingandleadingwhitespace
• …• Seejava.lang.StringAPIforall
CONTROLSTRUCTURES
Sept14,2016 Sprenkle-CSCI209 20
9/12/16
11
Review• Whatisthesyntaxofacondi0onalstatementinPython?
Sept14,2016 Sprenkle-CSCI209 21
Sept14,2016 Sprenkle-CSCI209 22
ControlFlow:Condi,onalStatements
• ifstatementØ CondiGonmustbesurroundedby() Ø Condi,onmustevaluatetoabooleanØ Bodyisenclosedby{} ifmul,plestatements
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 { }
9/12/16
12
Sept14,2016 Sprenkle-CSCI209 23
• ifstatement
• Everythingbetween{ } isablockofcodeØ Hasanassociatedscope
ControlFlow:Condi,onalStatements
if (purchaseAmount < availCredit) {System.out.println("Approved");availableCredit -= purchaseAmount;
}else
System.out.println("Denied");
Condition
Block of code
ScopingIssues:PythonGotcha• Everythingbetween{ } isablockofcode
Ø Hasanassociatedscope if (purchaseAmount < availableCredit) {
availableCredit -= purchaseAmount;boolean approved = true;
}
if( ! approved ) System.out.println("Denied");
Out of scopeWill get a compiler error(cannot find symbol)
Sept14,2016 24Sprenkle-CSCI209
How do we fix this code?
9/12/16
13
Fixed• Moveapproved outsideoftheif statement
boolean approved = false;if (purchaseAmount < availableCredit) {
availableCredit -= purchaseAmount;approved = true;
}
if( ! approved ) System.out.println("Denied");
Sept14,2016 25Sprenkle-CSCI209
LogicalOperators
Sept14,2016 Sprenkle-CSCI209 26
OperaGon Python JavaAND &&OR ||NOT !
In Python, these are …?
9/12/16
14
LogicalOperators
Sept14,2016 Sprenkle-CSCI209 27
OperaGon Python JavaAND and &&OR or ||NOT not !
ControlFlow:else if• InPython,waselif
Sept14,2016 Sprenkle-CSCI209 28
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?
9/12/16
15
ControlFlow:switchstatement• Likeabigif/else if statement• Workswithvariableswithdatatypesbyte,short,char,int, and String
Sept14,2016 Sprenkle-CSCI209 29
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.");
}
Sept14,2016 Sprenkle-CSCI209 30
ControlFlow:switchstatementswitch(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
9/12/16
16
ControlFlow:while Loops• while loopØ Condi,onmustbeenclosedinparenthesesØ Bodyofloopmustbeenclosedin {} ifmul,ple
statements
Sept14,2016 Sprenkle-CSCI209 31
int counter = 0;while (counter < 5) {
System.out.println(counter);counter++;
}System.out.println("Done: " + counter);
shortcut
Sept14,2016 Sprenkle-CSCI209 32
Changingcontrolflow:break• Exitsthecurrentloop
while ( <readingdata> ) {… if( <somethingbad> ) { // shouldn’t happen
break;}
}
9/12/16
17
Review• HowdoyouwriteaforloopinPythonforcoun,ng?
Sept14,2016 Sprenkle-CSCI209 33
ControlFlow:for Loop• VerydifferentsyntaxfromPython• Syntax:
Sept14,2016 Sprenkle-CSCI209 34
for (<init>; <condition>; <execution_expr>)
Loop’s counter variable,Usually used in condition
Executed at end of each iteration.Typically increments or �
decrements counter
9/12/16
18
ControlFlow:for LoopExample
• Whatisthecountervariable?• Whatisthecondi,on?• Whatistheoutput?• HowwriqeninPython?
Sept14,2016 Sprenkle-CSCI209 35
System.out.println("Counting down…");
for (int count=5; count >= 1; count--) { System.out.println(count);}System.out.println("Blastoff!"); shortcut
Can’t print out count with Blastoff. Why?
ARRAYS
Sept14,2016 Sprenkle-CSCI209 36
9/12/16
19
Sept14,2016 Sprenkle-CSCI209 37
PythonListsàJavaArrays• AJavaarrayislikeafixed-lengthlist• Todeclareanarrayofintegers: int[] arrayOfInts;Ø Declara,ononlymakesavariablenamed
arrayOfIntsØ Doesnotini,alizearrayorallocatememoryforthe
elements
• Todeclareandini3alizearrayofintegers:int[] arrayOfInts = new int[100];
new keyword: �allocate memory to a new object
Sept14,2016 Sprenkle-CSCI209 38
ArrayIni,aliza,on• Ini,alizeanarrayatitsdeclara,on:
Ø int[] fibNums = {1, 1, 2, 3, 5, 8, 13};
Ø Notethatwedonotusethenew keywordwhen
alloca,ngandini,alizinganarrayinthismannerØ fibNums haslength7
1 1 2 3 5 8 130 1 2 3 4 5 6Position/index
Value
9/12/16
20
ArrayAccess• AccessavalueinanarrayasinPython:
Ø fibNums[0]Ø fibNums[x] = fibNums[x-1] + fibNums[x-2]
• UnlikeinPython,cannotusenega,venumberstoindexitems
Sept14,2016 Sprenkle-CSCI209 39
Sept14,2016 Sprenkle-CSCI209 40
ArrayLength• AllarrayvariableshaveafieldcalledlengthØ Note:noparenthesesbecausenotamethod
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
9/12/16
21
Sept14,2016 Sprenkle-CSCI209 41
OversteppingArrayLength• JavasafeguardsagainstoversteppinglengthofarrayØ Run,meExcep,on:“Arrayindexoutofbounds”Ø Moreonexcep,onslater…
• Exampleint[] array = new int[100];Ø Aqemptstoaccessorwritetoindex<0orindex>=
array.length(100)willgenerateexcep,on
Sept14,2016 Sprenkle-CSCI209 42
Arrays• AssigningonearrayvariabletoanotherèbothvariablesrefertothesamearrayØ SimilartoPython
• Drawpictureofbelowcode:int [] fibNums = {1, 1, 2, 3, 5, 8, 13};int [] otherFibNums;
otherFibNums = fibNums;otherFibNums[2] = 99;
System.out.println(otherFibNums[2]);System.out.println(fibNums[2]);
fibNums[2]andotherFibNums[2]arebothequalto99
9/12/16
22
Sept14,2016 Sprenkle-CSCI209 43
ArrayCopying• Copyanarray(element-by-element)usingthearraycopy methodintheSystemclass
• Forexample:
fibNums[2] = 2, otherNums[2]= 99
System.arraycopy(from, fromIndex, to, toIndex, count);
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]);
Sept14,2016 Sprenkle-CSCI209 44
ControlFlow:foreachLoop• IntroducedinJava5Ø Suncalls“enhancedfor”loop
• Iterateoverallelementsinanarray(orCollec,on)Ø SimilartoPython’sfor loopint[] a;int result = 0; . . .for (int i : a){ result += i; }
for each int element iin the array a,the loop body is visited once for each element of a.
“in”
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
9/12/16
23
Sept14,2016 Sprenkle-CSCI209 45
java.util.Arrays• Arraysisaclassinjava.util• Methodsforsor,ng,searching,deepEquals,fillarrays
• Touseclass,needimport statementØ Goesattopofprogram,beforeclassdefini,on
import java.util.Arrays;
ArraysExample.java
Summary:PythontoJavaGotchas• Everyvariableneedstobedeclaredbeforeitisused
• Everyvariableneedsasta,cally-declareddatatype
• Scopeofvariables• SyntaxØ SemicolonsattheendofstatementsØ BracesaroundblocksofcodeØ Keywords
Sept14,2016 Sprenkle-CSCI209 46