Understanding Arrays, Strings, and Vectors

arrays strings and vectors n.w
1 / 29
Embed
Share

Learn about the advantages, disadvantages, and types of arrays, along with examples of single-dimensional Java arrays and how to declare, instantiate, and initialize Java arrays efficiently.

  • Arrays
  • Strings
  • Vectors
  • Java
  • Data Structures

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. ARRAYS, STRINGS AND VECTORS

  2. Arrays Array is a collection of similar type of elements that have contiguous memory location. Array provides a convenient means of grouping related information. We can store only fixed elements in an array. Array is index based, first element of the array is stored at 0 index.

  3. Advantage of Array Code Optimization: It makes the code optimized, we can retrieve or sort the data easily. Random access: We can get any data located at any index position. Disadvantage of Array Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.

  4. Types of Array There are two types of array. Single Dimensional Array Multidimensional Array

  5. Single Dimensional Array A list of items are given in one variable name using only one subscript. Syntax to Declare an Array in java dataType[ ] arrayRefVar; (or) dataType [ ]arrayRefVar; (or) dataType arrayRefVar[ ]; Instantiation of an Array in java arrayRefVar=new datatype[size];

  6. Example of single dimensional java array class B { public static void main(String args[]) { int a[]=new int[5]; //declaration and instantiation a[0]=10; //initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //printing array for(int i=0; i<a.length; i++) //length is the property of array System.out.println(a[i]); }}

  7. Declaration, Instantiation and Initialization of Java Array We can declare, instantiate and initialize the java array in single statement together by: int a[]={33,3,4,5}; //declaration, instantiationand initialization class B{ public static void main(String args[]) { //declaration, instantiation and initialization int a[]={33,3,4,5}; //printing array for(int i=0;i<a.length;i++) System.out.println(a[i]); } }

  8. Passing Java Array in the method class B{ static void min(int arr[]) { int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]) { int a[]={33,3,4,5}; min(a); //passing array in the method }}

  9. Multidimensional array In such case, data is stored in row and column based index (also known as matrix form). Syntax to Declare Multidimensional Array in java dataType[ ][ ] arrayRefVar; (or) dataType [ ][ ]arrayRefVar; (or) dataType arrayRefVar[ ][ ]; (or) dataType [ ]arrayRefVar[ ];

  10. Example to instantiate Multidimensional Array in java int[ ][ ] arr=new int[3][3]; //3 row and 3 column Example to initialize Multidimensional Array in java arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9;

  11. Example of Multidimensional java array class B { } public static void main(String args[]) { int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { } System.out.println(); } } //declaring and initializing 2D array System.out.print(arr[i][j]+" ");

  12. Variable Size Arrays Java treats multidimensional array as arrays of array int x[ ][ ]=new int [3][ ]; These statements create a two dimensional array as having different lengths for each array. x[0]=new int[2]; x[1]=new int[4]; x[2]=new int[3]; X[0][2] X[0] X[1] X[1][4] X[2] X[2][3]

  13. Strings The String class is commonly used for holding and manipulating strings of text. In java, strings are class objects and implemented using two classes namely, String and StringBuffer. A java string is an instantiated object of the String class. A java string is not a character array and is not NULL terminated.

  14. Strings String objects are handled specially by the compiler. String is the only class which has "implicit" instantiation. The String class is defined in the java.lang package. Strings are immutable. The value of a String object can never be changed. For mutable Strings, use the StringBuffer class.

  15. Creating String Objects Normally, objects in Java are created with the new keyword. String name; name = new String( John"); However, String objects can be created "implicitly": String name; name = John"; Strings can also be created using the + operator. The + operator, when applied to Strings means concatenation. int age = 21; String message = John wishes he was " + age + " years old";

  16. String Methods - length, charAt Returns the number of characters in the string. int length(); char charAt(i); Returns the char at position i. Character positions in strings are numbered starting from 0 just like arrays. Returns: Problem".length(); Window".charAt (2); 7 n'

  17. Method substring Returns a new String by copying characters from an existing String. television String subs = word.substring (i, k); returns the substring of chars in positions from i to k-1 i k String subs = word.substring (i); returns the substring from the i-th char to the end television i Returns: lev" mutable" "" (empty string) television".substring (2,5); immutable".substring (2); bob".substring (9);

  18. Methods Concatenation String word1 = re , word2 = think ; word3 = ing ; int num = 2; String result = word1 + word2; //concatenates word1 and word2 rethink String result = word1.concat (word2); //the same as word1 + word2 rethink result+= word3; //concatenates word3 to result rethinking result += num; //converts num to String //and concatenates it to result rethinking2

  19. Methods Find (indexOf) 0 2 6 10 15 String name = President George Washington"; Returns: name.indexOf ( P'); name.indexOf ( e'); name.indexOf ( George"); 10 name.indexOf ( e', 3); 0 2 (starts searching at position 3) 6 name.indexOf ( Bob"); name.lastIndexOf ( e'); -1 15 (not found)

  20. Methods Equality boolean b = word1.equals(word2); returns true if the string word1 is equal to word2 boolean b = word1.equalsIgnoreCase(word2); returns true if the string word1 matches word2, case-blind b = b = Raiders .equals Raiders .equals( Raiders );// ( Raiders );//true true b = b = Raiders .equals Raiders .equals( raiders );// ( raiders );//false false b = Raiders . b = Raiders .equalsIgnoreCase equalsIgnoreCase( raiders );//true ( raiders );//true

  21. Methods Comparison int diff = word1.compareTo(word2); returns the difference word1-word2 int diff = word1.compareToIgnoreCase(word2); returns the difference word1 - word2, case-blind Usually programmers don t care what the numerical difference of word1 - word2 is, just whether the difference is negative (word1 comes before word2), zero (word1 and word2 are equal) or positive (word1 comes after word2). Often used in conditional statements. if(word1.compareTo(word2) > 0){ //word1 comes after word2 }

  22. Comparison Examples //negative //negative differences differences diff = apple . diff = apple .compareTo diff = Zebra . diff = Zebra .compareTo diff = dig . diff = dig .compareTo diff = dig . diff = dig .compareTo compareTo( berry );//a before b ( berry );//a before b compareTo( apple );//Z before a ( apple );//Z before a compareTo( dug ( dug ); // ); //i before u compareTo( digs ( digs ); // ); //dig is shorter i before u dig is shorter //zero //zero differences differences diff = apple . diff = apple .compareTo diff = dig . diff = dig .compareToIgnoreCase compareToIgnoreCase( DIG );//equal compareTo( apple );//equal ( apple );//equal ( DIG );//equal //positive //positive differences differences diff = berry . diff = berry .compareTo diff = apple . diff = apple .compareTo diff = BIT . diff = BIT .compareTo diff = huge . diff = huge .compareTo compareTo( apple );//b after a ( apple );//b after a compareTo( Apple );//a after A ( Apple );//a after A compareTo( BIG ( BIG ); // T ); // T after G compareTo( hug ( hug ); // ); //huge is longer after G huge is longer

  23. Methods trim String word2 = word1.trim (); returns a new string formed from word1 by removing white space at both ends does not affect whites space in the middle String word1 = Hi Bob ; String word2 = word1.trim(); //word2 is Hi Bob no spaces on either end //word1 is still Hi Bob with spaces

  24. Methods replace String word2 = word1.replace(oldCh, newCh); returns a new string formed from word1 by replacing all occurrences of oldCh with newCh String word1 = rare ; String word2 = rare .replace( r , d ); //word2 is dade , but word1 is still rare

  25. Methods Changing Case String word2 = word1.toUpperCase(); String word3 = word1.toLowerCase(); returns a new string formed from word1 by converting its characters to upper (lower) case String word1 = HeLLo ; String word2 = word1.toUpperCase();// HELLO String word3 = word1.toLowerCase();// hello //word1 is still HeLLo

  26. Numbers to Strings Three ways to convert a number into a string: 1. String s = "" + num; s = + 123;// 123 Integer and Double are wrapper classes from java.lang that represent numbers as objects. They also provide useful static methods. 2. String s = Integer.toString (i); String s = Double.toString (d); s = Integer.toString(123);// 123 s = Double.toString(3.14); // 3.14 3. String s = String.valueOf (num); s = String.valueOf(123);// 123

  27. Method Description Compares this string to the specified object. equals(Object anObject) Compares this String to another String, ignoring case. equalsIgnoreCase(String another) concat(String str) Concatenates the specified string to the end of this string. Compares two strings and returns int compareTo(String str) Compares two strings, ignoring case differences. compareToIgnoreCase(str) Returns a new string that is a substring of this string. substring(int beginIndex) Converts all of the characters in this String to upper case toUpperCase() Converts all of the characters in this String to lower case. toLowerCase() Returns a copy of the string, with leading and trailing whitespace omitted. trim() charAt(int index) Returns the char value at the specified index. length() Returns the length of this string.

  28. The StringBuffer Class StringBuffer objects are similar to String objects Strings are immutable StringBuffers are mutable StringBuffer(): creates an empty string buffer with the initial capacity of 16. StringBuffer(String str): creates a string buffer with the specified string. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length. StringBuffer nameBuffer = new StringBuffer("Joe");

  29. Method Task a Modifies the nth character to x StringBuffer s1=new StringBuffer( vijay ); s1.setCharAt(3, e ); Appends the string s2 to s1 at the end. StringBuffer s1=new StringBuffer( Vijay ); StringBuffer s2=new StringBuffer( Dinanath ); s1.append(s2); Inserts the string s2 at the position n of the string s1. s1.insert(3,s2); Sets the length of string s1 to n. If n<s1.length( ) s1 is truncated. If n>s1.length( ) zeros are added to s1. s1.setCharAt(n, x ) s1.append(s2) s1.insert(n,s2) s1.setLength(n) This method is used to reverse the string. StringBuffer s1=new StringBuffer( Vijay ); s1.reverse(); Used to delete multiple characters at once from position m to n. StringBuffer s1=new StringBuffer( Vijay ); s1.delete(2,5); reverse() delete(m,n) Used to delete specific character. s1.deleteCharAt(5); deleteCharAt()

More Related Content