1 / 81

Arrays in Java

Arrays in Java. An array is a collection of elements where each element is the same type. Element type can be primitive or Object Each element is a single value The length of the array is set when it is created. It cannot change. Individual array elements are accessed via an index.

eamon
Download Presentation

Arrays in Java

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. Arrays in Java An array is a collection of elements where each element is the same type. Element type can be primitive or Object Each element is a single value The length of the array is set when it is created. It cannot change. Individual array elements are accessed via an index. Array index numbering starts at 0.

  2. Creating Arrays • Creating an array is a 2 step process • It must be declared (declaration does not specify size) • in java, all arrays are dynamically allocated. • It must be created (ie. memory must be allocated for the array) • Array Creation syntax: • arrayName=new type[size]; type[] arrayName; declaration syntax: note the location of the [] int[] grades; // declaration grades = new int[5]; // Create array. // specify size // assign new array to // array variable

  3. Creating Arrays • When an array is created, all of its elements are automatically initialized • 0 for integral types • 0.0 for floating point types • false for boolean types • null for object types grades array indices 0 0 int[] grades = new int[5]; 0 1 0 2 0 3 0 4 Note: maximum array index is length -1

  4. int[] sequence = new int[5]; for (inti=0; i< sequence.length; i++) { sequence[i] = i * 25; } Initializing and Using Arrays • Because array elements are initialized to 0, the array should be initialized with usable values before the array is used. • This can be done with a loop • Arrays have a length attribute which can be used for bounds checking • Elements are accessed using an index and [] array length: ensures loop won't go past end of the array Array element being accessed. In this case, it is being assigned a value.

  5. Eg: class test { void cal(int[] a) { int s=0; for(inti=0;i<a.length;i++) { s=s+a[i]; } System.out.println("sum= "+s); } } class arraytest { public static void main(String[] args) { int[] a=new int[10]; for(inti=0;i<args.length;i++) { a[i]=Integer.parseInt(args[i]); } test t=new test(); t.cal(a); } }

  6. Example: class input { int[] sequence = new int[5]; void get() { for (inti=0; i< sequence.length; i++) { sequence[i] = i * 25; } } void display() { for (inti=0; i< sequence.length; i++) { System.out.println(sequence[i]); } } } class test { public static void main(String[] arg) { input in=new input(); in.get(); in.display(); } }

  7. import java.io.*; class test { char[] ch=new char[10]; void get()throws IOException { System.out.println("Enter a character\n"); for(inti=0;i<ch.length;i++) { ch[i]=(char)System.in.read(); } } void display() { for(inti=0;i<ch.length;i++) { System.out.println(ch[i]); } } }

  8. class testarray { public static void main(String[] args)throws IOException { test t=new test(); t.get(); t.display(); } }

  9. type[] arrayName = {initializer_list}; int[] grades = {100, 96, 78, 86, 93}; Using initializer lists • Another way of initializing lists is by using initializer lists. • The array is automatically created • The array size is computed from the number of items in the list. String[] colours = { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};

  10. int[] sequence = new int[5]; sequence[0] = 50; // ok sequence[1] = 60; // ok sequence[-1] = 100; // Exception sequence[5] = 30; // Exception Array Bounds Checking • Whenever and array is accessed, the index is checked to ensure that it within the bounds of the array. • Attempts to access an array element outside the bounds of the array will cause an ArrayIndexOutOfBounds exception to be thrown.

  11. Eg: find the average of a given array Program: class input { double[] sequence = {10.1,11.2,12.3,13.4,14.5}; double result=0.0; double average; void avg() { for (inti=0; i< sequence.length; i++) { result=result+sequence[i]; } average=result/sequence.length; } void display() { System.out.println("sum of an array elements : "+result); System.out.println("average = "+average); } }

  12. class avgtest { public static void main(String[] arg) { input in=new input(); in.avg(); in.display(); } }

  13. Array Copying • An array is copied into another array in two ways. • Method 1: it is directly copying the array reference into another array. In this method, both array point to the same memory location. So, changes in one array will affect other. General form destination_array = source array Eg: copyarray.java • Method 2: System.arraycopy(source,source_index,destination,destination_index,count); It copies the content of one array in another. But the destination must have sufficient memory space to hold the source values. Eg:copyofarray.java

  14. Multi-dimensional Arrays • Arrays with multiple dimensions can also be created. • They are created and initialized in the same way as single dimensioned arrays. • In java, multi-dimensional arrays are actually arrays of array. • a two dimensional array can be like a table of rows and columns. • Syntax: • datatype[][] array_name=new datatype[n][m]; • here utilize in n rows and m columns totally n X m elements in the above array. • Eg1: twoarray.java • Eg2:additionarray.java declaration syntax: type[][] arrayName; each [] indicates another dimension

  15. Like a one-dimensional array, a multidimensional array can be initialized using an array literal. Simply use nested sets of curly braces to nest arrays within arrays. For example, we can declare, create, and initialize a 5×5 multiplication table like this: int[][] products = { {0, 0, 0, 0, 0},{0, 1, 2, 3, 4},{0, 2, 4, 6, 8},{0, 3, 6, 9, 12},{0, 4, 8, 12, 16} };

  16. Initializing two-dimensional arrays • the first dimension represents the rows, the second dimension, the columns • curly braces {} may also be used to initialize two dimensional arrays. Again they are only valid in array declaration statements. • int[][] twoDimArray = { {1,2,3}, {4,5,6}, {7,8,9} }; • you can initialize the row dimension without initializing the columns but not vice versa • int[][] myArray = new int[5][]; // illegal • int[][] myArray = new int[][5]; • the length of the columns can vary • Character array can be string or numbers have the same characters. Character array are variable but string is constant

  17. VECTOR • The java.util package has a class called vector, which permits an array to store different elements that are of different class. • Vector automatically increases its size when needed. Ordinary array cannot do that. • Constructors for Vector • 1.Vector () – 10 elements • 2. Vector (int size) • 3. Vector (int size, int increment)

  18. Methods in vector AddElement() : add new elements into the vector at the last position size() : Gives the no. of object present capacity() : Gives no. of spaces it has allocated elementAt(inti) : returns the object at position i in the vector insertElementAt() : to insert an element at the given index removeElement() : it removes the given element Eg:vect.java

  19. Strings • The String is not a sipledata type, it is a class. • The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. • Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. • For example: • String str = "abc"; • is equivalent to: • char[] data = {'a', 'b', 'c'}; • String str = new String(data); • The String class is final. The String class contains • several methods that allow us to accomplish a variety • of string manipulation tasks. • Eg:Test.java • Palindrome.java

  20. String is a predefined Java class (in java.lang.String) • a String object encapsulates a sequence of characters String firstName = "Dave"; which is equivalent to String firstName = new String("Dave"); • you can display Strings using System.out.print and System.out.println System.out.println(firstName); • the '+' operator concatenates two strings (or string and number) together String str = "foo" + "lish"; str = str + "ly"; int age = 19; System.out.println("Next year, you will be " + (age+1));

  21. Difference between Character Array and String Eg:chararraytest.java Chararray.cpp

  22. String Methods Method Call Task Performed s2 = s1.toLowerCase() Converts the string S1 to all lowercase s2 = s1.toUpperCase() Converts the string S1 to all uppercase s2 = s1.replace(‘o’,’i’); Replace all appearances of o with i s2 = s1.trim(x); Remove white spaces at the beginning and end of the string S1 S1.equals(S2) Returns ‘true’ if S1 is equals to S2 S1.equalsIgnoreCase(S2) Returns ‘true’ if S1 = S2, ignoring the case of characters S1.length() Gives the length of S1 S1.chartAt (n) Gives nth character of S1 S1.compareTo(S2) Returns negative if S1<S2, positive if S1>S2, and zero if S1 = S2 S1.concat(S2)Concatenates S1 and S2 S1.substring(n) Gives substring starting from nth character S1.substring(n,m) Gives substring starting from nth character up to mth (not including mth) String.valueOf(p) Creates a string object of the parameter p Eg:stringtest.java

  23. StringBuffer • It is a peer class of string. While string creates strings of fixed length, string buffer creates strings of flexible length that can be modified in terms of both length and content. • We can insert characters and sub strings in the middle of the string, or append another string to the end.

  24. Constructors for StringBuffer 1.StringBuffer() – 16 characters 2.StringBuffer(int size) 3.StringBuffer(String str) Every StringBuffer has two methods 1.length() – no. of characters 2.capacity() - no. of characters, it can contain without being expanded.

  25. Commonly Used StringBuffer Methods: S1.setCharAt(n,’x’) : Modifies the nth character to x S1.append(S2) : Appends the strings S2 to S1 at the end S1.insert(n,S2) : Inserts the string S2 at the position n of the string S1 S1.reverse(String s) Eg:stringbuf.java

  26. Java Comments In java, three types of comment statement. It helps make the code more readable. They are Single line comment(//) Multi line comment(/* and */) Documentation comment(/** and */)

  27. Single line comment(//) - for a single line comment we use double slash(//) to begin a comment. It ends at the end of the line. Eg: int a=10; //assgin 10 to a Book b=new Book; //create an object Multi line comment(/* and */) - If the comment exceeds more than one line, we can use the multi line comment. Here we start with /* and end with */ Eg: /* this is a second java program called this file as “second.java”*/

  28. Java Documentation Comment • to produce a professional looking documentation, comments are used in the source files. • if you are using this type of comment, javadoc utility program to extract the information and out into an HTML file. • This HTML documentation is generated by the javadoc tool of JDK. • it is similar to a multi line comment except that it starts with a forward slash followed by 2 asterisks (/**) and • end with */. • comments contain free form statements and tags. • free-form text must be a summary statement. Javadoc automatically generates summary pages that extract these sentences. • a tag in comments start with @ symbol

  29. Types of comments • class comments • method comments • field comments • package and overview comments • class comments: • - a class comment must be placed after the all import statements, but before the class definition. • @ author • @ version • @ see • @ deprecated • @ since

  30. @author • May be used for class and interface declarations @author Mary Wollstonecraft • A documentation comment may contain more than one @author tag

  31. @version • May be used for class and interface declarations @version 493.0.1beta • A documentation comment may contain at most one version tag @ since • This tag adds entry about the version that introduced this feature.

  32. @deprecated @deprecateddeprecated-text • Adds a comment indicating that this API should no longer be used (even though it may continue to work). Javadoc moves the deprecated-text ahead of the description, placing it in italics and preceding it with a bold warning: "Deprecated". • The text should tell a replacement.

  33. @see • Used to specify a cross-reference • @see java.lang.String • @see String • @see java.io.InputStream; • @see String#equals • @see java.lang.Object#wait(int) • @see java.io.RandomAccessFile#RandomAccessFile(File, String) • @see Character#MAX_RADIX • @see <a href="spec.html">Java Spec</a>

  34. Method comments • Each method comment must be defined immediately before the method that it describes. In addition to the general purpose tags, the following tags can be used in the comments. • @param • @return • @exception • @throws

  35. @param • May be used in comments for method and constructor declarations @param file the file to be searched • Parameters should be documented in the order in which they are declared

  36. @return • may be used in documentation comments for declarations of methods whose result type is not void @return the number of widgets to be used • Use to provide a short description of the return value

  37. @exception (@throws) • may be used in documentation comments for method and constructor declarations @exception IndexOutOfBoundsException the matrix is too large • The name of the class followed by a short description of when it is thrown

  38. Field comments • This adds description to the public fields, generally that means static constants Eg: /** * max_count for objects */ public static final intmax_count=10;

  39. Package and overview comments • Class, method, and variable comments are placed directly into the Java source files delimited by /** ... */ documentation comments. But, to generate package comments, a separate file is to be added in each package directory. For this two methods are used Method-l • An HTML file named package.html is created and supplied. All the text between the tags <body> ... </body> are extracted. Method-2 • A Java file named package-info.java is created and supplied. The file must contain an initial Javadoc comment with /** and */ followed by a package statement. It should not contain other code or comments.

  40. JavaDoc Example /** * The root of the Class hierarchy. Every Class in the * system has Object as its ultimate parent. Every variable * and method defined here is available in every Object. * @see Class * @version 1.37, 26 Jun 1996 */ public class Object { /** * Compares two Objects for equality. * Returns a boolean that indicates whether this Object * is equivalent to the specified Object. This method is * used when an Object is stored in a hashtable. * @paramobj the Object to compare with * @return true if these Objects are equal; * false otherwise. * @see java.util.Hashtable */ public boolean equals(Object obj) { return (this == obj); } /** * Creates a clone of the object. A new instance is * allocated and a bitwise clone of the current object * is placed in the new object. * @return a clone of this Object. * @exception OutOfMemoryError If there is not enough * memory. * @exception CloneNotSupportedException * Object explicitly does not want to be * cloned, or it does not support * the Cloneable interface. */

  41. Introduction to Inheritance • Popularity of OOP is that it enables programmers to reuse previously written code saved as classes • All Java classes are arranged in a hierarchy, starting with Object, which is the superclass of all Java classes • Inheritance in OOP is analogous to inheritance in humans

  42. Inheritance • Inheritance is the ability to define a new class in terms of an existing class • The existing class is the parent, base or superclass • The new class is the child, derived or subclass • The child class inherits all of the attributes and behaviour of its parent class • It can then add new attributes or behaviour • Or even alter the implementation of existing behaviour • Inheritance is therefore another form of code reuse

  43. Inheritance • Allows programmers to customize a class for a specific purpose, without actually modifying the original class (the superclass) • The derived class (subclass) is allowed to add methods or redefine them • The subclass can add variables, but cannot redefine them

  44. Inheritance Example • The definition of one class from another class is by using extends keyword. Syntax: class derivedclassname extends baseclassname { } • Class C is a subclass of class B (its superclass) if its declaration has the form class C extends B { … }

  45. A Superclass and a Subclass • Consider two classes: Computer and Laptop • A laptop is a kind of computer and is therefore a subclass of computer

  46. A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding its own. Inheritance represents the is a relationship between data types. For example: a FemaleDanceris aDancer.

  47. subclass or derived class superclass or base class extends Inheritance Terminology: public class FemaleDancer extends Dancer { ... }

  48. Inheritance (cont’d) Example:

  49. Protected Visibility for Superclass Data Fields • Private data fields are not accessible to derived classes • Protected visibility allows data fields to be accessed either by the class defining it or any subclass • Public variables and methods are visible to all subclasses

More Related