1 CISC 370: Object-Oriented Programming with Java Instructor: James Atlas June 10, 2008.

Slides:



Advertisements
Similar presentations
Air Force Institute of Technology Electrical and Computer Engineering
Advertisements

Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Lab#1 (14/3/1431h) Introduction To java programming cs425
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 Java Basics. 2 Compiling A “compiler” is a program that translates from one language to another Typically from easy-to-read to fast-to-run e.g. from.
Java Syntax Primitive data types Operators Control statements.
Outline Java program structure Basic program elements
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 2 - Java Programming Fundamentals1 Chapter 2 Java Programming Fundamentals.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Introduction to Java Tavaris J. Thomas Ph.D. BNAI ZION SCIENTISTS DIVISION JOB ORIENTATION & TERMINOLOGY CLASSES Fall 2012.
DAT602 Database Application Development Lecture 5 JAVA Review.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
INTRODUCTION TO JAVA CHAPTER 1 1. WHAT IS JAVA ? Java is a programming language and computing platform first released by Sun Microsystems in The.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
CS591x A very brief introduction to Java. Java Developed by Sun Microsystems was intended a language for embedded applications became a general purpose.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Java Programming Presented by Daniel Rosenthal Friday, November 30 th, 2007.
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.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
CIT 590 Intro to Programming First lecture on Java.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Introduction to Java Java Translation Program Structure
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Applied Computing Technology Laboratory QuickStart Java Learning to Program in Java Dr. Tom Way October 21, 2005.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
CSC 212 Object-Oriented Programming and Java Part 2.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
Developed at Sun Microsystems in 1991 James Gosling, initially named “OAK” Formally announced java in 1995 Object oriented and cant write procedural.
Today… “Hello World” ritual. Brief History of Java & How Java Works. Introduction to Java class structure. But first, next slide shows Java is No. 1 programming.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Java Computer Industry Lab. 1 Programming Java Java Basics Incheon Paik.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CS 106 Introduction to Computer Science I 01 / 24 / 2007 Instructor: Michael Eckmann.
Object Oriented Programming Lecture 2: BallWorld.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
CMSC 202 Computer Science II for Majors Fall 2010 Introduction Version 9/101.
Introduction CMSC 202 Fall Instructors Mr. Ryan Bergeron – Lecture Section 01 Tues/Thu 1:00 – 2:15 am, Sondheim 111 – Lecture Section 04 Tues/Thu.
Information and Computer Sciences University of Hawaii, Manoa
Working with Java.
Intro to ETEC Java.
Java Primer 1: Types, Classes and Operators
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Starting JavaProgramming
(Computer fundamental Lab)
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Review of Java Fundamentals
JAVA. Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of platforms, such.
Presentation transcript:

1 CISC 370: Object-Oriented Programming with Java Instructor: James Atlas June 10, 2008

James Atlas - CISC3702 What is Java? … and, why should I learn it?

June 10, 2008James Atlas - CISC3703 What is Java? … and, why should I learn it? From Sun Microsystems From Sun Microsystems  1995, James Gosling and Patrick Naughton  Specifications Develop cross-platform applications Develop cross-platform applications  Web, desktop, embedded Object-oriented Object-oriented Simpler than C++ Simpler than C++ Rich and large library Rich and large library Solid industry presence Solid industry presence

June 10, 2008James Atlas - CISC3704 What to Expect from this Class Programming intensive Programming intensive  Interesting assignments and projects  Building on large library of classes  Learn to use software industry tools Learning on your own Learning on your own  Online resources

June 10, 2008James Atlas - CISC3705 Class Details Tuesday, Thursday lectures Tuesday, Thursday lectures  Quiz at beginning of each Tuesday class  Programming assignment due every Thursday class  See web page for example code, lecture slides Optional Textbooks Optional Textbooks  Plentiful online resources

June 10, 2008James Atlas - CISC3706 Class Details Weekly Programming Assignments Weekly Programming Assignments  Due one week after assigned 2 Projects 2 Projects  First is individual; everyone has the same project  Second is team; choice of topics 1 Exam 1 Exam  Final: Comprehensive

June 10, 2008James Atlas - CISC3707 Survey Says… More about you! More about you!

June 10, 2008James Atlas - CISC3708 What is Java? Java Programming Language Java Programming Language Java Virtual Machine Java Virtual Machine Java Class Libraries Java Class Libraries

June 10, 2008James Atlas - CISC3709 Java Programming Language Object-oriented Object-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, 2008James Atlas - CISC37010 Java Virtual Machine (JVM) Emulates the CPU, usually specified in software Emulates the CPU, usually specified in software Executes the program’s bytecode Executes the program’s bytecode  Bytecode: virtual machine code Different versions for each platform Java supports Different versions for each platform Java supports  program portability Sun’s Hotspot VM Sun’s Hotspot VM  Code dynamically compiled to machine code Garbage Collection Garbage Collection

June 10, 2008James Atlas - CISC37011 Java Virtual Machine (JVM) Program.class Mac JVM Bytecode Windows JVM UNIX JVM Same bytecode executes on each platform Same bytecode executes on each platform  What happens in C++? … CPU (machine code)

June 10, 2008James Atlas - CISC37012 Java Class Libraries Pre-defined classes Pre-defined classes  Included with the Java 2 Software Development Kit (SDK) and the Java 2 Runtime Environment (JRE)  View the available classes online: Similar in purpose to library functions included with ANSI C Similar in purpose to library functions included with ANSI C

June 10, 2008James Atlas - CISC37013 Benefits of Java Rapid development of programs Rapid development of programs  Large library of classes, including GUIs Portability Portability  run program on multiple platforms without recompiling

June 10, 2008James Atlas - CISC37014 Java Development Kit (J2SDK) J2SDK: Java 2 Software Development Kit J2SDK: Java 2 Software Development Kit Free from Sun Free from Sun Contains Contains  javac: Java compiler  java: Java Virtual Machine  Java class libraries

June 10, 2008James Atlas - CISC37015 Java Development Kit (J2SDK) Installed on mahler Installed on mahler  Java 1.5 should be reachable using default path   Run java -version to determine which version you’re running Run java -version to determine which version you’re running You can download the JDK for your machine from You can download the JDK for your machine from   JRE is for running Java applications does not include the compiler

June 10, 2008James Atlas - CISC37016 Summary of Java Platform SE 6.0 Image from Sun’s site

June 10, 2008James Atlas - CISC37017 Using the J2SDK Compile and run TestProgram.java Compile and run TestProgram.java  javac TestProgram.java Compiles the program into TestProgram.class Compiles the program into TestProgram.class  java TestProgram Runs the JVM, which executes the bytecode Runs the JVM, which executes the bytecode

June 10, 2008James Atlas - CISC37018 Intro to Java Programming Language Examples Examples Data types Data types Control structures Control structures

June 10, 2008James Atlas - CISC37019 First Java Program public class Hello { public static void main(String[] args) { System.out.println(“Hello”); }

June 10, 2008James Atlas - CISC37020 public class Hello { public static void main(String[] args) { System.out.println(“Hello”); } First Java Program Everything in Java is a class Everything in Java is a class  This class is named “Hello”

June 10, 2008James Atlas - CISC37021 public class Hello { public static void main(String[] args) { System.out.println(“Hello”); } First Java Program Access Modifier: controls if other classes can use code in this class

June 10, 2008James Atlas - CISC37022 First Java Program public class Hello { public static void main(String[] args) { System.out.println(“Hello”); } Defines the class “Hello”

June 10, 2008James Atlas - CISC37023 First Java Program Class contains one method Class contains one method  Functions are called methods in Java public class Hello { public static void main(String[] args) { System.out.println(“Hello”); } method

June 10, 2008James Atlas - CISC37024 First Java Program main methods main methods  Similar to main in C++  Takes one parameter: an array of Strings  Must be “public static”  Must be void: returns nothing public class Hello { public static void main(String[] args) { System.out.println(“Hello”); }

June 10, 2008James Atlas - CISC37025 public class Hello { public static void main(String[] args) { System.out.println(“Hello”); } First Java Program Method contains one line of code Method contains one line of code  What do you think it does?

June 10, 2008James Atlas - CISC37026 First Java Program Calls the println method on the System.out object Calls the println method on the System.out object println takes one parameter, a String println takes one parameter, a String Displays string on terminal, terminates the line with new line (\n) character Displays string on terminal, terminates the line with new line (\n) character public class Hello { public static void main(String[] args) { System.out.println(“Hello”); }

June 10, 2008James Atlas - CISC37027 First Java Program Comments: same as C++ Comments: same as C++  /* */ or // /* Our first Java program */ public class Hello { public static void main(String[] args) { // Print a message System.out.println(“Hello”); }

June 10, 2008James Atlas - CISC37028 Eclipse An open source development platform An open source development platform You will need to use it for this course You will need to use it for this course First programming assignment First programming assignment

June 10, 2008James Atlas - CISC37029 Java Fundamentals

June 10, 2008James Atlas - CISC37030 Java keywords/reserved words Case-sensitive Case-sensitive Can’t be used for variable or class names Can’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 …  public  class  static  void Exhaustive list Exhaustive list

June 10, 2008James Atlas - CISC37031 Data Types Java is strongly-typed Java is strongly-typed  Every variable must be a declared type All data in Java is an object except for the primitive data types All data in Java is an object except for the primitive data types  int – 4 bytes (-2,147,483,648 -> 2,147,483,647)  short – 2 bytes (-32,768 -> 32,767)  long – 8 bytes (really big integers)  byte – 1 byte (-128 -> 127)  float – 4 bytes (floating point)  double – 8 bytes (floating point)  char – 2 bytes (Unicode representation)  boolean – false or true

June 10, 2008James Atlas - CISC37032 Variables Declared and initialized same as C and C++ Declared and initialized same as C and C++ Typically, names start with lowercase letter Typically, names start with lowercase letter  ‘_’ also a valid first character  Convention: Subsequent words are capitalized Called “Camel Casing” Called “Camel Casing” Examples: Examples:  int x;  double pi = 3.14;  char q = ‘p’;  boolean isValid = false; Camel Casing

June 10, 2008James Atlas - CISC37033 More Data Type Information Default data types Default data types  Result of integer division is an int Same as C++ Same as C++ Example: 1/2 = ?? Example: 1/2 = ?? Casting Casting  Same as C++ for primitive types  Example: 1/(double) 2

June 10, 2008James Atlas - CISC37034 Final Members Cannot be assigned new value Cannot be assigned new value Keyword final precedes data type or method Keyword final precedes data type or method final double CM_PER_INCH = 2.540; public final void getValue() What was the equivalent keyword in C++?

June 10, 2008James Atlas - CISC37035 Final Members Cannot be assigned new value Cannot be assigned new value Keyword final precedes data type or method Keyword final precedes data type or method final double CM_PER_INCH = 2.540; public final void getValue() What was the equivalent keyword in C++? Trick question!

June 10, 2008James Atlas - CISC37036 Static Members Can be referenced without an instance of a class Can be referenced without an instance of a class Keyword static precedes data type or method Keyword static precedes data type or method  static: “for whole class” public static final double CM_PER_IN = 2.540; public static void main(String[] args)

June 10, 2008James Atlas - CISC37037 Operators Java has most of the same operators as C and C++: Java has most of the same operators as C and C++:  +, -, *, /, % (add, subtract, multiple, divide, modulus)  ++ and -- (increment and decrement)  ==, !=,, = (relational operators, evaluate to a boolean value)  &&, ||, ! (logical operators: AND, OR, NOT)  &, |, ^, ~ (bitwise AND, OR, XOR, NOT)

June 10, 2008James Atlas - CISC37038 Mathematical Functions and Constants java.lang.Math class java.lang.Math class  Similar to  Similar to  Included in the Java class libraries in the JDK  Included by default in every Java program  Includes useful mathematical functions (methods) and related constants ( final 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 online Look at java.lang.Math API online

June 10, 2008James Atlas - CISC37039 Java API Documentation API: Application Programming Interface API: Application Programming Interface  What the class can do for YOU! Complete documentation on every class included with the JDK and on every method and variable contained within each class. Complete documentation on every class included with the JDK and on every method and variable contained within each class. Bookmark it! Bookmark it!  Too many classes, methods to remember them all  Refer to it often

June 10, 2008James Atlas - CISC37040 Strings Java makes strings very easy, compared to C, C++, and many other languages. Java makes strings very easy, compared to C, C++, and many other languages. The Java class libraries include a predefined ‘String’ class in java.lang.String The Java class libraries include a predefined ‘String’ class in java.lang.String  All java.lang classes are automatically included in Java programs

June 10, 2008James Atlas - CISC37041 Strings Strings are represented by double quotes: “” Strings are represented by 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, 2008James Atlas - CISC37042 String Concatenation Use ‘+’ operator to concatenate Strings 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”

June 10, 2008James Atlas - CISC37043 String Concatenation If a string is concatenated with something that is not a string, the other variable is converted to a string. If a string is concatenated with something that is not a string, the other variable is converted to a string. int totalPoints = 110; int earnedPoints = 87; float testScore = (float)earnedPoints/totalPoints; System.out.println(“Your score is ” + testScore);

June 10, 2008James Atlas - CISC37044 String methods: substring 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, 2008James Atlas - CISC37045 String methods: equal 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 are different

June 10, 2008James Atlas - CISC37046 String methods: equal string1 == string2 will not yield the same result   Tests if the objects are the same   Not if the contents of the objects are the same

June 10, 2008James Atlas - CISC37047 String methods: equalsIgnoreCase Does what it’s named! Does what it’s named! String string1 = “Hello”; String string2 = “hello”; boolean test; test = string1.equalsIgnoreCase(string2); test is true!

June 10, 2008James Atlas - CISC37048 String methods: charAt A String is a collection of characters A String is a collection of characters String testString1; testString1 = “Demonstrate Strings”; char character1; char character2 = testString1.charAt(3); character1 = testString1.charAt(2);

June 10, 2008James Atlas - CISC37049 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 space trim(): remove trailing and leading white space … See Java API for java.lang.String for all See Java API for java.lang.String for all

June 10, 2008James Atlas - CISC37050 Control Structures

June 10, 2008James Atlas - CISC37051 Control Flow: Conditional Statements if statement if statement if (purchaseAmount < availableCredit) { availableCredit = availableCredit – purchaseAmount;System.out.println(“Approved”);}elseSystem.out.println(“Denied”); Condition must evaluate to a boolean (booleans are not ints in Java)

June 10, 2008James Atlas - CISC37052 if statement if statement if (purchaseAmount < availableCredit) { availableCredit = availableCredit – purchaseAmount;System.out.println(“Approved”);}elseSystem.out.println(“Denied”); Control Flow: Conditional Statements Block of code

June 10, 2008James Atlas - CISC37053 Blocks of Code Everything between { } is a block of code Everything between { } is a block of code  Has an associated scope if (purchaseAmount < availableCredit) { availableCredit = availableCredit – purchaseAmount; boolean approved = true; } if (approved) System.out.println(“Approved”); System.out.println(“Approved”);

June 10, 2008James Atlas - CISC37054 Blocks of Code Everything between { } is a block of code Everything between { } is a block of code  Has an associated scope if (purchaseAmount < availableCredit) { availableCredit = availableCredit – purchaseAmount; boolean approved = true; } if (approved) System.out.println(“Approved”); System.out.println(“Approved”);

June 10, 2008James Atlas - CISC37055 Blocks of Code Everything between { } is a block of code Everything between { } is a block of code  Has an associated scope boolean approved = false if (purchaseAmount < availableCredit) { availableCredit = availableCredit – purchaseAmount; approved = true; } if (approved) System.out.println(“Approved”); System.out.println(“Approved”);

June 10, 2008James Atlas - CISC37056 Control Flow: Conditional Statements switch statement switch statement 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.”); }

June 10, 2008James Atlas - CISC37057 Control Flow: while Loops int counter = 0; while (counter < 10) {System.out.println(counter);counter++;}System.out.println(“Done.”);

June 10, 2008James Atlas - CISC37058 Control Flow: do-while loop Loop runs at least once Loop runs at least once int counter = 0; do { System.out.println(counter);counter++; } while (counter < 10);

June 10, 2008James Atlas - CISC37059 Control Flow: for Loop for (int count=10; count >= 1; count--) { System.out.println(“Counting down…” + count); System.out.println(“Counting down…” + count);}System.out.println(“Blastoff!”);

June 10, 2008James Atlas - CISC37060 Control Flow: foreach Loop New to Java 1.5 New to Java 1.5  Sun calls “enhanced for” loop Iterate over all elements in an array (or Collection) Iterate over all elements in an array (or Collection) Simple, easy-to-read form Simple, easy-to-read form int[] 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, 2008James Atlas - CISC37061 Changing control flow: break In general, I do not recommend using break In general, I do not recommend using break  But, you should know it for reading other people’s code Exits the current loop Exits the current loop while ( ) { … if( data is null ) { // shouldn’t happen break; }

June 10, 2008James Atlas - CISC37062 Changing control flow: labeled break Does not exist in C++ Does not exist in C++ Add a label to a block of code Add a label to a block of code tagged_loop: while ( ) { … for ( ) { // not tagged if( error condition ) { // get out of both loops break tagged_loop; }

June 10, 2008James Atlas - CISC37063 Changing control flow: continue Jump to the next iteration of the loop Jump to the next iteration of the loop while ( ) { … if( data is null ) { // shouldn’t happen continue; } doStuff(); } Alternative way to write code without using continue?

June 10, 2008James Atlas - CISC37064 Arrays To declare an array of integers: To declare an array of integers: int[] arrayOfInts;  declaration makes only a variable named arrayOfInts  does not initialize array or allocate memory for the elements To declare and initialize array of integers: To declare and initialize array of integers: int[] arrayOfInts = new int[100];

June 10, 2008James Atlas - CISC37065 Array 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 new keyword when allocating and initializing an array in this manner

June 10, 2008James Atlas - CISC37066 Array Length All array variables have a field called length All array variables have a field called length int[] array = new int[10]; for (int a = 0; a < array.length; a++) { array[a] = 6; } for (int a = 0; a < array.length; a++) { System.out.println(array [a]); }

June 10, 2008James Atlas - CISC37067 Overstepping Array Length Java safeguards against overstepping length of array Java safeguards against overstepping length of array  Runtime Exception: “Array index out of bounds”  More on exceptions later… int[] arrayOfInts = new int[100];  Attempts to access or write to index = array.length (100) will generate exception

June 10, 2008James Atlas - CISC37068 Array Copying It is possible to copy one array variable into another, but then both variables refer to the same array It is possible to copy one array variable into another, but then both variables refer to the same array  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, 2008James Atlas - CISC37069 Array Copying The copying of an array (element-by-element) can be done using the arraycopy method in the System class The copying of an array (element-by-element) can be done using the arraycopy method in the System class System.arraycopy(from, fromIndex, to, toIndex, 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, 2008James Atlas - CISC37070 Arrays: Java vs C++ int[] array = new int[100]; // Java is not the same as: int array[100]; // C++ but is the same as: int * array = new int[100] // C++ array variable is the same as a pointer that points to the beginning of an array in C++. array variable is the same as a pointer that points to the beginning of an array in C++. … except that Java arrays belong to a class … except that Java arrays belong to a class