Lesson 1: Java Core: Arrays and Its Variants, String Manipulation
Lesson 1: Java Core: Arrays and Its Variants, String Manipulation
Arrays
Arrays are container objects that hold a finite number of elements of the same type.
Creating arrays are as follows: int[] array = new int[10];
To access array values just refer to them using their indexes. Java implements 0-indexing. x[7] = 8;
Multi-dimensional Arrays
Multi-dimensional arrays can also be done in Java by simply extending the definition like so: int[][] array = new int [5][10];
arraycopy
Copying arrays can be done by the System class arraycopy method arraycopy(Object array1, int srcStart, Object array2, int destStart, int lengthCopy)
Example of arraycopy
char v = ,b,e,d,o,g-; char c = char[3]; System.arraycopy(v,2,c,0,3); System.out.print(new String(c)); //prints dog
Java Strings
Normally Strings are sequences of objects in arrays, in Java Strings are objects. There are multiple ways of creating strings in Java: String s = Harry Styles; String s = new String(*c,a,t+);
Java Strings
To access the length of the String, simply call the length method of the object:
String name = One Direction; int length = name.length(); System.out.print(length)://prints 13
Concatenating Strings
Java provides various ways to concatenate Strings: string1.concat(string2); What makes you.concat( beautiful); Youve got that + one thing!;
String substrings
Getting parts of strings or substrings is as simple as: name.substring(int beginIndex, int endIndex); name.substring(int beginIndex); The methods return the string at the beginning index to the end index 1
Comparing Strings
boolean equals(String s) - returns true if the two strings are equal (case sensitive) boolean matches(String regexp) - tests whether the string matches the given regex
Illustrative Example
capacity
R
length
Constructors
StringBuilder() - creates an empty StringBuilder class with 16 cells as capacity StringBuilder(CharSequence cs) - creates a StringBuilder with the char sequence plus 16 more cells StringBuilder(int initCapacity) - creates the StringBuilder with the given capacity
Constructor
StringBuilder(String s) - constructs a StringBuilder containing the given string plus 16 more cells for capacity.
Length Operations
void setLength(int newLength) - sets new length of the StringBuilder, truncates when the length is shorter
StringBuilder Methods
append() - appends the given data to the StringBuilder. Converts into a string before appending. delete(int start, int end) - deletes from start to end-1 of the StringBuilder deleteCharAt(int index) - deletes the character at the located index
StringBuilder Methods
replace(int start, int end, String s) - replaces the specified characters in this the StringBuilder reverse() -reverses the sequence of characters in this StringBuilder