1 cisc 370: object-oriented programming with java instructor: james atlas [email protected]:tbd...
TRANSCRIPT
11
CISC 370: Object-Oriented CISC 370: Object-Oriented Programming with JavaProgramming with Java
Instructor: James AtlasInstructor: James [email protected]@cis.udel.edu
TA:TBDTA:TBD
June 10, 2008June 10, 2008
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 22
What is Java?What is Java?… and, why should I learn it?… and, why should I learn it?
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 33
What is Java?What is Java?… and, why should I learn it?… and, why should I learn it?
• From Sun MicrosystemsFrom Sun Microsystems 1995, James Gosling and Patrick Naughton1995, James Gosling and Patrick Naughton SpecificationsSpecifications
• Develop cross-platform applicationsDevelop cross-platform applications Web, desktop, embeddedWeb, desktop, embedded
• Object-orientedObject-oriented• Simpler than C++Simpler than C++• Rich and Rich and largelarge library library• Solid industry presenceSolid industry presence
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 44
What to Expect from this ClassWhat to Expect from this Class
• Programming intensiveProgramming intensive Interesting assignments and projectsInteresting assignments and projects Building on large library of classesBuilding on large library of classes Learn to use software industry toolsLearn to use software industry tools
• Learning on your ownLearning on your own Online resourcesOnline resources
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 55
Class DetailsClass Details
• Tuesday, Thursday lecturesTuesday, Thursday lectures Quiz at beginning of each Tuesday classQuiz at beginning of each Tuesday class Programming assignment due every Thursday Programming assignment due every Thursday
classclass See web page for example code, lecture slidesSee web page for example code, lecture slides
• Optional TextbooksOptional Textbooks Plentiful online resourcesPlentiful online resources
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 66
Class DetailsClass Details
• Weekly Programming AssignmentsWeekly Programming Assignments Due one week after assignedDue one week after assigned
• 2 Projects2 Projects First is individual; everyone has the same projectFirst is individual; everyone has the same project Second is team; choice of topicsSecond is team; choice of topics
• 1 Exam1 Exam Final: ComprehensiveFinal: Comprehensive
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 77
Survey Says…Survey Says…
• More about you!More about you!
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 88
What is Java?What is Java?
• Java Programming LanguageJava Programming Language• Java Virtual MachineJava Virtual Machine• Java Class LibrariesJava Class Libraries
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 99
Java Programming LanguageJava Programming Language
• Object-orientedObject-oriented
• Similar syntax to C++Similar syntax to C++
Program.java
Written in Java Programming Language
javac
Compiler
Program.class
Bytecode: machine code for a virtual CPU
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1010
Java Virtual Machine (JVM)Java Virtual Machine (JVM)
• Emulates the CPU, usually specified in Emulates the CPU, usually specified in softwaresoftware
• Executes the program’s bytecodeExecutes the program’s bytecode Bytecode: virtual machine code Bytecode: virtual machine code
• Different versions for each platform Java Different versions for each platform Java supportssupports program portabilityprogram portability
• Sun’s Hotspot VMSun’s Hotspot VM Code dynamically compiled to machine codeCode dynamically compiled to machine code
• Garbage CollectionGarbage Collection
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1111
Java Virtual Machine (JVM)Java Virtual Machine (JVM)
Program.class
Mac JVMMac JVM
Bytecode Windows JVMWindows JVM
UNIX JVMUNIX JVM
• Same bytecode executes on each platformSame bytecode executes on each platform What happens in C++?What happens in C++?
… CPU(machine code)
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1212
Java Class LibrariesJava Class Libraries
• Pre-defined classesPre-defined classes Included with the Java 2 Software Development Included with the Java 2 Software Development
Kit (SDK) and the Java 2 Runtime Environment Kit (SDK) and the Java 2 Runtime Environment (JRE)(JRE)
View the available classes online:View the available classes online:http://java.sun.com/j2se/6/docs/api/index.html
• Similar in purpose to library functions Similar in purpose to library functions included with ANSI Cincluded with ANSI C
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1313
Benefits of JavaBenefits of Java
• Rapid development of programsRapid development of programs Large library of classes, including GUIsLarge library of classes, including GUIs
• PortabilityPortability run program on multiple platforms without run program on multiple platforms without
recompilingrecompiling
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1414
Java Development Kit (J2SDK)Java Development Kit (J2SDK)
• J2SDK: Java 2 Software Development KitJ2SDK: Java 2 Software Development Kit
• Free from SunFree from Sun
• ContainsContains javac: Java compilerjavac: Java compiler java: Java Virtual Machinejava: Java Virtual Machine Java class librariesJava class libraries
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1515
Java Development Kit (J2SDK)Java Development Kit (J2SDK)
• Installed on mahlerInstalled on mahler Java 1.5 should be reachable using default pathJava 1.5 should be reachable using default path http://www.udel.edu/topics/os/unix/package/
java/
• Run Run java -version java -version to determine which to determine which version you’re runningversion you’re running
• You can download the JDK for your machine You can download the JDK for your machine from from http://java.sun.com/javase/downloads/index.jsp
JRE is for running Java applications• does not include the compiler
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1616
Summary of Java Platform SE 6.0Summary of Java Platform SE 6.0
Image from Sun’s site
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1717
Using the J2SDKUsing the J2SDK
• Compile and run TestProgram.javaCompile and run TestProgram.java javac TestProgram.javajavac TestProgram.java
• Compiles the program into TestProgram.classCompiles the program into TestProgram.class java TestProgramjava TestProgram
• Runs the JVM, which executes the bytecodeRuns the JVM, which executes the bytecode
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1818
Intro to Java Programming Intro to Java Programming LanguageLanguage• ExamplesExamples
• Data typesData types
• Control structuresControl structures
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 1919
First Java ProgramFirst Java Programpublic class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2020
public class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
}
First Java ProgramFirst Java Program
• Everything in Java is a classEverything in Java is a class This class is named “Hello”This class is named “Hello”
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2121
public class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
}
First Java ProgramFirst Java Program
Access Modifier: controls if other classes can use code in this class
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2222
First Java ProgramFirst Java Programpublic class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
} Defines the class “Hello”
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2323
First Java ProgramFirst Java Program
• Class contains one methodClass contains one method Functions are called Functions are called methodsmethods in Java in Java
public class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
}method
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2424
First Java ProgramFirst Java Program
•mainmain methods methods Similar to Similar to mainmain in C++ in C++ Takes one parameter: an array of StringsTakes one parameter: an array of Strings Must be “Must be “public staticpublic static”” Must be void: returns nothingMust be void: returns nothing
public class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2525
public class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
}
First Java ProgramFirst Java Program
• Method contains one line of codeMethod contains one line of code What do you think it does?What do you think it does?
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2626
First Java ProgramFirst Java Program
• Calls the Calls the printlnprintln method on the method on the System.outSystem.out object object
•printlnprintln takes one parameter, a String takes one parameter, a String• Displays string on terminal, terminates the Displays string on terminal, terminates the
line with new line (\n) characterline with new line (\n) character
public class Hello{
public static void main(String[] args){
System.out.println(“Hello”);}
}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2727
First Java ProgramFirst Java Program
• Comments: same as C++Comments: same as C++ /* */ or ///* */ or //
/*Our first Java program*/public class Hello{
public static void main(String[] args)
{// Print a messageSystem.out.println(“Hello”);
}}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2828
EclipseEclipse
• An open source development platformAn open source development platform
• http://www.eclipse.org/http://www.eclipse.org/
• You will need to use it for this courseYou will need to use it for this course
• First programming assignmentFirst programming assignment
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 2929
Java FundamentalsJava Fundamentals
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3030
Java keywords/reserved wordsJava keywords/reserved words
• Case-sensitiveCase-sensitive
• Can’t be used for variable or class namesCan’t be used for variable or class names
• Many same as in C/C++Many same as in C/C++
• Seen so far …Seen so far … publicpublic classclass staticstatic voidvoid
• Exhaustive list Exhaustive list http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3131
Data TypesData Types• Java is Java is strongly-typedstrongly-typed
Every variable must be a declared typeEvery variable must be a declared type
• All data in Java is an All data in Java is an objectobject except for the except for the primitiveprimitive data typesdata types intint – 4 bytes (-2,147,483,648 -> 2,147,483,647) – 4 bytes (-2,147,483,648 -> 2,147,483,647) shortshort – 2 bytes (-32,768 -> 32,767) – 2 bytes (-32,768 -> 32,767) longlong – 8 bytes (really big integers) – 8 bytes (really big integers) bytebyte – 1 byte (-128 -> 127) – 1 byte (-128 -> 127) floatfloat – 4 bytes (floating point) – 4 bytes (floating point) doubledouble – 8 bytes (floating point) – 8 bytes (floating point) charchar – 2 bytes (Unicode representation) – 2 bytes (Unicode representation) booleanboolean – – falsefalse or or truetrue
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3232
VariablesVariables
• Declared and initialized same as C and C++Declared and initialized same as C and C++• Typically, names start with lowercase letterTypically, names start with lowercase letter
‘‘_’ also a valid first character_’ also a valid first character Convention: Subsequent words are capitalized Convention: Subsequent words are capitalized
• Called “Camel Casing”Called “Camel Casing”
• Examples:Examples: int x;int x; double pi = 3.14;double pi = 3.14; char q = ‘p’;char q = ‘p’; boolean isValid = false;boolean isValid = false;
Camel Casing
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3333
More Data Type InformationMore Data Type Information
• Default data typesDefault data types Result of integer division is an Result of integer division is an intint
• Same as C++Same as C++
• Example: Example: 1/21/2 = ?? = ??
• CastingCasting Same as C++ for primitive typesSame as C++ for primitive types Example: Example: 1/(double) 21/(double) 2
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3434
Final MembersFinal Members
• Cannot be assigned new valueCannot be assigned new value
• Keyword Keyword finalfinal precedes data type or precedes data type or methodmethod
final double CM_PER_INCH = 2.540;public final void getValue()
What was the equivalent keyword in C++?
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3535
Final MembersFinal Members
• Cannot be assigned new valueCannot be assigned new value
• Keyword Keyword finalfinal precedes data type or precedes data type or methodmethod
final double CM_PER_INCH = 2.540;public final void getValue()
What was the equivalent keyword in C++?
Trick question!
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3636
Static MembersStatic Members
• Can be referenced without an instance of a Can be referenced without an instance of a classclass
• Keyword Keyword staticstatic precedes data type or precedes data type or methodmethod static: “for whole class”static: “for whole class”
public static final double CM_PER_IN = 2.540;
public static void main(String[] args)
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3737
OperatorsOperators
• Java has most of the same operators as C Java has most of the same operators as C and C++:and C++: +, -, *, /, % (add, subtract, multiple, divide, +, -, *, /, % (add, subtract, multiple, divide,
modulus)modulus) ++ and -- (increment and decrement)++ and -- (increment and decrement) ==, !=, <, >, <=, >= (relational operators, ==, !=, <, >, <=, >= (relational operators,
evaluate to a evaluate to a booleanboolean value) value) &&, ||, ! (logical operators: AND, OR, NOT)&&, ||, ! (logical operators: AND, OR, NOT) &, |, ^, ~ (bitwise AND, OR, XOR, NOT)&, |, ^, ~ (bitwise AND, OR, XOR, NOT)
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3838
Mathematical Functions and Mathematical Functions and ConstantsConstants• java.lang.Math class java.lang.Math class
Similar to <math.h>Similar to <math.h> Included in the Java class libraries in the JDKIncluded in the Java class libraries in the JDK Included by default in every Java programIncluded by default in every Java program Includes useful mathematical functions (methods) Includes useful mathematical functions (methods)
and related constants (and related constants (finalfinal values): values):• double y = Math.pow(x, a);double y = Math.pow(x, a);• double z = Math.sin(y);double z = Math.sin(y);• double d = Math.exp(4.59) * Math.PI;double d = Math.exp(4.59) * Math.PI;
• Look at java.lang.Math API onlineLook at java.lang.Math API online
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 3939
Java API DocumentationJava API Documentation
• API:API: Application Programming Interface Application Programming Interface What the class can do for YOU!What the class can do for YOU!
• Complete documentation on every class Complete documentation on every class included with the JDK and on every method included with the JDK and on every method and variable contained within each class.and variable contained within each class.http://java.sun.com/j2se/6/docs/api/
• Bookmark it!Bookmark it! Too many classes, methods to remember them allToo many classes, methods to remember them all Refer to it oftenRefer to it often
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4040
StringsStrings
• Java makes strings very easy, compared to Java makes strings very easy, compared to C, C++, and many other languages.C, C++, and many other languages.
• The Java class libraries include a predefined The Java class libraries include a predefined ‘String’ class in java.lang.String‘String’ class in java.lang.String All java.lang classes are automatically included All java.lang classes are automatically included
in Java programsin Java programs
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4141
StringsStrings
• Strings are represented byStrings are represented by double quotes: double quotes: “”“”
• Examples:Examples:String emptyString = “”;String niceGreeting = “Hello there.”;String badGreeting = “What do you want?”;
Note that you don’t need to specify the String’s size
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4242
String ConcatenationString Concatenation
• Use ‘+’ operator to concatenate StringsUse ‘+’ 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”
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4343
String ConcatenationString Concatenation
• If a string is concatenated with something If a string is concatenated with something that is not a string, the other variable is that is not a string, the other variable is converted to a string.converted to a string.
int totalPoints = 110;int earnedPoints = 87;float testScore = (float)earnedPoints/totalPoints;
System.out.println(“Your score is ” +testScore);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4444
String methods: String methods: substringsubstring
• String substring(int beginIndex)Returns a new string that is a substring of this
string, from beginIndex through 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
String greeting = “Hello, Clark Kent!”;
String subStr = greeting.substring(7);
String subStr2 = greeting.substring(7, 11);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4545
String methods: String methods: equalequal
• boolean equals(Object anObject)Compares this string to the specified objectString string1 = “Hello”;String string1 = “Hello”;
String string2 = “hello”;String string2 = “hello”;
boolean test;boolean test;
test = string1.equals(string2);test = string1.equals(string2);
•test is false because the strings are different
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4646
String methods: String methods: equalequal
•string1 == string2 will not yield the same resultTests if the objects are the sameNot if the contents of the objects are the same
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4747
String methods: String methods: equalsIgnoreCaseequalsIgnoreCase• Does what it’s named!Does what it’s named!
String string1 = “Hello”;String string1 = “Hello”;
String string2 = “hello”;String string2 = “hello”;
boolean test;boolean test;
test = string1.equalsIgnoreCase(string2);test = string1.equalsIgnoreCase(string2);
•test is true!
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4848
String methods: String methods: charAtcharAt
• A String is a collection of charactersA String is a collection of characters
String testString1;testString1 = “Demonstrate Strings”;
char character1;char character2 = testString1.charAt(3);character1 = testString1.charAt(2);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 4949
String methods: and many more!String methods: and many more!
• boolean endsWith(String suffix)boolean endsWith(String suffix)
• boolean startsWith(String prefix)boolean startsWith(String prefix)
• length()length()
• toLowerCase()toLowerCase()
• trim(): remove trailing and leading white trim(): remove trailing and leading white spacespace
• ……
• See Java API for java.lang.String for allSee Java API for java.lang.String for all
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5050
Control StructuresControl Structures
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5151
Control Flow: Conditional Control Flow: Conditional StatementsStatements• ifif statement statement
if (if (purchaseAmount < availableCreditpurchaseAmount < availableCredit))
{{
availableCredit = availableCredit –availableCredit = availableCredit –
purchaseAmount;purchaseAmount;
System.out.println(“Approved”);System.out.println(“Approved”);
}}
elseelse
System.out.println(“Denied”);System.out.println(“Denied”);
Condition must evaluate to a boolean (booleans are not ints in Java)
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5252
• ifif statement statement
if (purchaseAmount < availableCredit)if (purchaseAmount < availableCredit)
{{
availableCredit = availableCredit –availableCredit = availableCredit –
purchaseAmount;purchaseAmount;
System.out.println(“Approved”);System.out.println(“Approved”);
}}
elseelse
System.out.println(“Denied”);System.out.println(“Denied”);
Control Flow: Conditional Control Flow: Conditional StatementsStatements
Block of code
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5353
Blocks of CodeBlocks of Code
• Everything between { } is a block of codeEverything between { } is a block of code Has an associated Has an associated scopescope
if (purchaseAmount < availableCredit)if (purchaseAmount < availableCredit)
{{
availableCredit = availableCredit –availableCredit = availableCredit –
purchaseAmount;purchaseAmount;
boolean approved = true;boolean approved = true;
}}
if (approved)if (approved)
System.out.println(“Approved”);System.out.println(“Approved”);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5454
Blocks of CodeBlocks of Code
• Everything between { } is a block of codeEverything between { } is a block of code Has an associated Has an associated scopescope
if (purchaseAmount < availableCredit)if (purchaseAmount < availableCredit)
{{
availableCredit = availableCredit –availableCredit = availableCredit –
purchaseAmount;purchaseAmount;
boolean approved = true;boolean approved = true;
}}
if (approved)if (approved)
System.out.println(“Approved”);System.out.println(“Approved”);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5555
Blocks of CodeBlocks of Code
• Everything between { } is a block of codeEverything between { } is a block of code Has an associated Has an associated scopescope
boolean approved = falseboolean approved = false
if (purchaseAmount < availableCredit)if (purchaseAmount < availableCredit)
{{
availableCredit = availableCredit –availableCredit = availableCredit –
purchaseAmount;purchaseAmount;
approved = true;approved = true;
}}
if (approved)if (approved)
System.out.println(“Approved”);System.out.println(“Approved”);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5656
Control Flow: Conditional Control Flow: Conditional StatementsStatements• switchswitch statement statement
int x = 3;int x = 3;
switch(x) {switch(x) {
case (1) :case (1) :
System.out.println(“It’s a 1.”);System.out.println(“It’s a 1.”);
break;break;
case (2) :case (2) :
System.out.println(“It’s a 2.”);System.out.println(“It’s a 2.”);
break;break;
default:default:
System.out.println(“Not a 1 or 2.”);System.out.println(“Not a 1 or 2.”);
}}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5757
Control Flow: while LoopsControl Flow: while Loops
int counter = 0;int counter = 0;
while (counter < 10)while (counter < 10)
{{
System.out.println(counter);System.out.println(counter);
counter++;counter++;
}}
System.out.println(“Done.”);System.out.println(“Done.”);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5858
Control Flow: do-while loopControl Flow: do-while loop
• Loop runs at least onceLoop runs at least once
int counter = 0;int counter = 0;
do {do {
System.out.println(counter);System.out.println(counter);
counter++;counter++;
} while (counter < 10);} while (counter < 10);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 5959
Control Flow: for LoopControl Flow: for Loop
for (int count=10; count >= 1; count--)for (int count=10; count >= 1; count--)
{{
System.out.println(“Counting down…” + System.out.println(“Counting down…” + count);count);
}}
System.out.println(“Blastoff!”);System.out.println(“Blastoff!”);
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6060
Control Flow: foreach LoopControl Flow: foreach Loop
• New to Java 1.5New to Java 1.5 Sun calls “enhanced for” loopSun calls “enhanced for” loop
• Iterate over all elements in an array (or Iterate over all elements in an array (or Collection)Collection)
• Simple, easy-to-read formSimple, easy-to-read formint[] a;int result = 0;
. . .for (int i : a){ result += i; }
for each int element i in the array a
The loop body is visited once for each value of i.
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6161
Changing control flow: Changing control flow: breakbreak
• In general, I do In general, I do notnot recommend using break recommend using break But, you should know it for reading other But, you should know it for reading other
people’s codepeople’s code
• Exits the current loopExits the current loop
while ( <readingdata> ) {… if( data is null ) { // shouldn’t happen
break;}
}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6262
Changing control flow: labeled Changing control flow: labeled breakbreak• Does not exist in C++Does not exist in C++
• Add a label to a block of codeAdd a label to a block of code
tagged_loop:while ( <readingdata> ) {
… for ( ) { // not tagged
if( error condition ) {// get out of both loopsbreak tagged_loop;
}}
}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6363
Changing control flow: Changing control flow: continuecontinue
• Jump to the next iteration of the loopJump to the next iteration of the loop
while ( <readingdata> ) {… if( data is null ) { // shouldn’t happen
continue;} doStuff();
}
Alternative way to write code without using continue?
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6464
ArraysArrays
• To declare an array of integers:To declare an array of integers:int[] arrayOfInts;int[] arrayOfInts;
declaration makes only a variable named declaration makes only a variable named arrayOfIntsarrayOfInts
does not initialize array or allocate memory for does not initialize array or allocate memory for the elementsthe elements
• To declare To declare and initializeand initialize array of integers: array of integers:int[] arrayOfInts = new int[100];int[] arrayOfInts = new int[100];
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6565
Array InitializationArray Initialization
• Initialize an array at its declaration:Initialize an array at its declaration:
int [] fibNumbs = {1, 1, 2, 3, 5, 8, 13};
Note that we do not use the Note that we do not use the new new keyword when keyword when allocating and initializing an array in this mannerallocating and initializing an array in this manner
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6666
Array LengthArray Length
• All array variables have a All array variables have a fieldfield called called lengthlengthint[] array = new int[10];int[] array = new int[10];
for (int a = 0; a < for (int a = 0; a < array.lengtharray.length; a++); a++)
{ {
array[a] = 6; array[a] = 6;
}}
for (int a = 0; a < for (int a = 0; a < array.lengtharray.length; a++); a++)
{ {
System.out.println(array [a]); System.out.println(array [a]);
}}
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6767
Overstepping Array LengthOverstepping Array Length
• Java safeguards against overstepping length Java safeguards against overstepping length of arrayof array Runtime Exception: “Array index out of bounds”Runtime Exception: “Array index out of bounds” More on exceptions later…More on exceptions later…
int[] arrayOfInts = new int[100];int[] arrayOfInts = new int[100];
Attempts to access or write to index < 0 or index Attempts to access or write to index < 0 or index >= array.length (100) will generate exception>= array.length (100) will generate exception
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6868
Array CopyingArray Copying
• It is possible to copy one array variable into It is possible to copy one array variable into another, but then both variables refer to the another, but then both variables refer to the same array same array like manipulating pointers in C++like manipulating pointers in C++
int [] fibNumbs = {1, 1, 2, 3, 5, 8, 13};int [] otherFibNumbs;
otherFibNumbs = fibNumbs;otherFibNumbs[2] = 99;
System.out.println(otherFibNumbs[2]);System.out.println(fibNumbs[2]);
fibNumbs[2] and otherFibNumbs[2] are both equal to 99.
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 6969
Array CopyingArray Copying• The copying of an array (element-by-element) can The copying of an array (element-by-element) can
be done using the arraycopy method in the System be done using the arraycopy method in the System classclass
System.arraycopy(from, fromIndex, to, toIndex, System.arraycopy(from, fromIndex, to, toIndex, count);count);
• For example:For example:
int [] fibNumbs = {1, 1, 2, 3, 5, 8, 13};int [] otherFibNumbs = new int[7];System.arraycopy(fibNumbs,0,otherFibNumbs,0,7);otherFibNumbs[2] = 99;System.out.println(otherFibNumbs[2]);System.out.println(fibNumbs[2]);
fibNumbs[2] = 2, otherFibNumbs[2]= 99
June 10, 2008June 10, 2008 James Atlas - CISC370James Atlas - CISC370 7070
Arrays: Java vs C++Arrays: Java vs C++int[] array = new int[100]; // Javaint[] array = new int[100]; // Java
is not the same as:is not the same as:int array[100]; // C++int array[100]; // C++
but is the same as:but is the same as:int * array = new int[100] // C++int * array = new int[100] // C++
•arrayarray variable is the same as a pointer that variable is the same as a pointer that points to the beginning of an array in C++.points to the beginning of an array in C++.
• … … except that Java arrays belong to a classexcept that Java arrays belong to a class