Przejdź do głównej zawartości

Java -Arrays

Array - data structure that allows us to store multiple values of the same type into a single variable

Default value - zero
Arrays are zero indexed - Array with ten elements will be indexed from 0 to 9
Array[]

How to create array:

  1. int[] array = new int[5]; (boxes have value zero - secured slot in memory to hold values)
  2. int[] myArray = {1,2,3,4,5}; this type of initializing an array is also known as an anonymous array

boolean type arrays - default value is false

Errors while working with arrays


  1. ArrayIndexOutOfBoundsExeption

  2. int[] my Array = {10,35,45,78,55}
    myArray[5] = 55; out of bound
    index 5 does not exist





  1. int[] myArray = {10,15,20,17,18};


  2. for (int i=1; i < myArray.lenght; i++) 

    System.out.println("value= " + myArray[i]

    it will return values from index 1

How to print out simple int array?
example:

int[] myArray = new int[2];myArray[0]=0;myArray[1]=1;


System.out.println("My array: " + 
        Arrays.toString(myArray));


static StringtoString(int[] a)
Returns a string representation of the contents of the specified array.


public class Arrays - This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

Komentarze

Popularne posty z tego bloga

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if

String-1 > endsLy

Given a string, return true if it ends in "ly". endsLy("oddly") → true endsLy("y") → false endsLy("oddy") → false public boolean endsLy ( String str ) { if ( str . length ()< 2 ){ return false ; } if (( str . substring ( str . length ()- 2 , str . length ())). equals ( "ly" )){ return true ; } return false ; }

String-1 > withouEnd2

Given a string, return a version without both the first and last char of the string. The string may be any length, including 0. withouEnd2("Hello") → "ell" withouEnd2("abc") → "b" withouEnd2("ab") → "" public String withouEnd2 ( String str ) { if ( str . length ()== 1 ){ return str . substring ( 1 ); } else if ( str . length ()== 0 ){ return str ; } return ( str . substring ( 1 , str . length ()- 1 )); }