1 / 20

Array creation defines the size of the array and allocates space for the array object

Java Arrays. Obtaining a Java array is a two step process:. 1. Declare a variable that can reference an array object. 2. Create the array object by using operator "new". The two steps may be done separately. int numbers[ ]; or int[ ] numbers;

dore
Télécharger la présentation

Array creation defines the size of the array and allocates space for the array object

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Arrays Obtaining a Java array is a two step process: 1. Declare a variable that can reference an array object 2. Create the array object by using operator "new" The two steps may be done separately ... int numbers[ ]; or int[ ] numbers; numbers=new int[10]; numbers=new int[10]; or together ... int numbers[ ]=new int[10]; or int[ ] numbers=new int[10]; Array creation defines the size of the array and allocates space for the array object

  2. Programmer-Initialization of Arrays: int[] nums={ 30,50,-23,16 }; Automatic Initialization of Arrays: If not programmer-initialized, array elements will be automatically initialized as follows: type default initialization integer 0 boolean false char null char String null String object null object

  3. Array Access: if given the declaration … int[] nums={ 30,50,-23,16 }; then array access may be obtained, for example … int n=nums[2]; // n set to -23 (-23 is returned) nums[0]=19; // 0th nums element set to 19 (19 is returned) Array subscripts are automatically checked for out of range errors An array's length may be obtained by accessing the array object's length attribute ... int len=nums.length; // returns 4 for example above

  4. Declaring a Primitive Type Variable: With Initialization: n1 n2 int n2=19; int n1; 0 19 Declaring an Instance of a Class: With Object Creation And Initialization: <classname> <refname>; Robot r1; Robot r2=new Robot(3,4,”EAST”); r1 r2 null 3 4 etc “EAST”

  5. Java's Built-in String Class The String class represents character strings Syntax: String s1=“abc”; String s2=new String( ); All string literals in Java programs, such as “abc” are implemented as instances of this class Strings are immutable (constant) i.e., their values cannot be changed after they are created (although a string reference may be set to reference a different value) The class String includes methods for… examining individual characters of the sequence comparing strings extracting substrings searching strings creating a copy of a string String Arithmetic – use the “+” operator to concatenate Strings E.g., float radius=21.6; System.out.println(“radius = ” + radius); (radius value automatically converted to a String) String buffer class objects support mutable strings.

  6. Selection Statements if statement: if ( <boolean_expression> ) <statement> if-else statement: if ( <boolean_expression> ) <statement_1> else <statement_2> switch statement: switch ( <integer_expression> ) { <case_label_list_1> <statement_1> <case_label_list_2> <statement_2> . . <case_label_list_n> <statement_n> [default: <statement>] } case-label-list: case <num_1> : case <num_2> : . . case <num_n> : Each <statement> is usually terminated with "break;"

  7. Iteration Statements while statement: while ( <boolean_expression> ) <statement> do-while statement: do <statement> while ( <boolean_expression> ) ; for statement: for (<initial_statement(s)>; <boolean_expression>; <loop_expression(s)>) <statement> Use of break and continue

  8. An Example: Calculate the mean of the absolute values in an array An approach in pseudocode: Begin constructor Declare and initialize an array (object) Display the array display( ) Replace array elements with absolute values absolute( ) Display the array summation( ) Sum the array values Calculate the mean of the array mean( ) Display the mean End

  9. //File AbsMean1.java -- Calculate the mean of the absolute values in an array import java.io.*; class AbsMeanStuff { double[] array; AbsMeanStuff(double[] a) { //constructor array=new double[a.length]; for (int i=0; i<array.length; i++) array[i]=a[i]; } void display(String msg) { System.out.println(msg); for (int i=0; i<array.length; i++) System.out.println(i+" -> "+array[i]); } void absolute() { int k=0; while (k<array.length) { if (array[k]<0.0) array[k]*=-1.0; k++; } }

  10. double sum=0.0; void summation() { int k=0; do { //using a do-while means there must be at least 1 element in the array sum=sum+array[k]; ++k; } while (k<array.length); } double mean() { return sum/array.length; } } public class AbsMean1 { public static void main(String[] args) { double[] temp={5.0,-7.5,2.5,8.2,-4.0}; AbsMeanStuff ams=new AbsMeanStuff(temp); ams.display("The original array is:\n"); ams.absolute(); ams.display("\n\nThe array in absolute value form is:\n"); ams.summation(); System.out.println("\n\nThe mean of the array is: "+ams.mean()); } }

  11. //File AbsMean2.javaimport java.io.*; class AbsMeanStuff { double[] array; AbsMeanStuff(double[] a) {…} void display(String msg) {…} void absolute() {…} double sum=0.0; void summation() {…} double mean() {…} } class AbsMeanStuffDriver { AbsMeanStuffDriver() { double[] temp={5.0,-7.5,2.5,8.2,-4.0}; AbsMeanStuff ams=new AbsMeanStuff(temp); ams.display("The original array is:\n"); ams.absolute(); ams.display("\n\nThe array in absolute value form is:\n"); ams.summation(); System.out.println("\n\nThe mean of the array is: "+ams.mean()); } } public class AbsMean2 { public static void main(String[] args) { AbsMeanStuffDriver absd=new AbsMeanStuffDriver(); } }

  12. class Strings { public static void main(String[] args) { String s1="A string!"; String s2="A different string!"; System.out.println("Are s1 & s2 the same object? "+(s1==s2)); System.out.println("Do s1 & s2 have the same value? "+s1.equals(s2)); // false // false String s3=s1+" "+s2; System.out.println("The length of s3 is "+s3.length()); // A string! A different string! // 29 String s4="A str"; s4=s4+"ing!"; System.out.println("Are s1 & s4 the same object? "+(s1==s4)); System.out.println("Do s1 & s4 have the same value? "+s1.equals(s4)); // A string! // false // true String s5=s4; System.out.println("Are s4 & s5 the same object? "+(s4==s5)); System.out.println("Do s4 & s5 have the same value? "+s4.equals(s5)); // true // true String s6="A string!"; System.out.println("Are s1 & s6 the same object? "+(s1==s6)); System.out.println("Do s1 & s6 have the same value? "+s1.equals(s6)); // true // true System.out.println("Are s5 & s6 the same object? "+(s5==s6)); System.out.println("Do s5 & s6 have the same value? "+s5.equals(s6)); } } // false // true

  13. //File RobotStuff.java import java.io.*; class Robot { static final int EAST=0; static final int NORTH=1; static final int WEST=2; static final int SOUTH=3; private int x,y; private int direction; Robot() {// Robot's x, y, and direction actually set to 0 by default x=0; y=0; direction=EAST; display(); } void move(int distance) { switch (direction) { case EAST: x+=distance; break; case NORTH: y+=distance; break; case WEST: x-=distance; break; case SOUTH: y-=distance; break; default: System.out.println("Error in move(int)!"); } display(); }

  14. private void display() { System.out.print("Current location of Robot is: ("+x+","+y+") "); switch (direction) { case EAST: System.out.println("EAST"); break; case NORTH: System.out.println("NORTH"); break; case WEST: System.out.println("WEST"); break; case SOUTH: System.out.println("SOUTH"); break; default: System.out.println("Error in display()!"); } } void display(String str) { System.out.print(str+" ("+x+","+y+") "); switch (direction) { case EAST: System.out.println("EAST"); break; case NORTH: System.out.println("NORTH"); break; case WEST: System.out.println("WEST"); break; case SOUTH: System.out.println("SOUTH"); break; default: System.out.println("Error in display(String)!"); } } void leftFace() { direction=(direction+1)%4; display(); } void rightFace() { direction=(direction+3)%4; display(); }

  15. int xPosition() { return x; } int yPosition() { return y; } int orientation() { return direction; } } public class RobotStuff { public static void main(String[] args) { System.out.println("begin...\n"); Robot r=new Robot(); r.move(19); r.rightFace(); r.move(29); r.leftFace(); r.leftFace(); r.move(2); r.display("Final location of Robot is: "); System.out.print("\n...end!"); } }

  16. The Contents Within Java Classes Attributes: Instance variables e.g., int n; Class variables e.g., static int m; Includes constant variables Methods: Instance methods e.g., void capture(…); Class methods e.g., static int max(…); Includes final methods

  17. Java Modifiers Visibility Modifiers*(i.e., modifiers that affect scope): public method or variable -- can be accessed by methods within any class private method or variable -- only accessed by methods within its own class protected method or variable -- can be accessed by methods within its own class and its class’ subclasses default (no modifier) preceding a method or variable (friendly access) -- can be accessed by methods within its own class and classes within its package Some Other Modifiers: static method or variable -- method is a class method; variable is a class variable final class, method, or variable -- class cannot be subclassed; method cannot be overridden in a subclass; variable is a constant * See Table 7.2 (p.293) in Core Web Programming, M.Hall, Prentice-Hall, 1998

  18. The Scope of Variables Within Methods A method’s formal parameter may be accessed over the entire method A method’s local variable may be accessed from its point of declaration to the end of the block in which it has been declared (a block may be defined as the code found between matching curly brackets) Parameter Passing Primitive type variables are passed by value Objects are also passed by value but… Since objects are referenced through reference variables, Object parameters are, in effect, passed by reference

  19. A Pair of Keywords this Is a way for an object to reference itself (the current object) Is implicit when referring to instance variables and instance methods within methods of the current class May be used anywhere the object’s name might appear e.g., t=this.x; // where x is an instance variable of the current object this.reset(); // where reset is a method of the current object return this; // return the current object super Is a way for an object to reference an ancestor Passes a message (a call to a method) up the class hierarchy until it finds a definition of the method e.g., super.print(); // where print is an ancestor method super(); // invocation of an ancestor constructor

  20. Naming Conventions The first letter of a class name is in uppercase The first letter of a method name or data element is in lowercase but if the name consists of more than 1 word then the first letter of each word beyond the first is in uppercase String literal constants are capitalized

More Related