




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































2.1 Types of Arrays Java Arrays: Declare, Create, Initialize Java Array is a very common type of data structure which contains all the data values of the same data type. The data items put in the array are called elements and the first element in the array starts with index zero. Arrays inherit the object class and implement the serializable and cloneable interfaces. We can store primitive values or objects in an array. In simple words, it’s a programming construct which helps to replace this x0=0; x1=1; x2=2; x3=3; x4=4; x5=5; with this … x[0]=0; x[1]=1; x[2]=2; x[3]=3; x[4]=4; x[5]=5; An array is a collection of similar types of data. if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. String[] array = new String[ 100 ]; Here, the above array cannot store more than 100 names. The number of values in a Java array is always fixed. How to declare an array in Java? In Java, here is how we can declare an array. dataType[] arrayName; dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects arrayName - it is an identifier For example, double[] data; Here, data is an array that can hold values of type double. But, how many elements can array this hold?
Good question! To define the number of elements that an array can hold, we have to allocate memory for the array in Java. For example, // declare an array double[] data; // allocate memory data = new Double[ 10 ]; Here, the array can store 10 elements. We can also say that the size or length of the array is
In Java, we can declare and allocate memory of an array in one single statement. For example, double[] data = new double[ 10 ]; How to Initialize Arrays in Java? In Java, we can initialize arrays during declaration. For example, //declare and initialize and array int[] age = { 12 , 4 , 5 , 2 , 5 }; Here, we have created an array named age and initialized it with the values inside the curly brackets. Note that we have not provided the size of the array. In this case, the Java compiler automatically specifies the size by counting the number of elements in the array (i.e. 5). In the Java array, each memory location is associated with a number. The number is known as an array index. We can also initialize arrays in Java, using the index number. For example, // declare an array int[] age = new int[ 5 ]; // initialize array age[ 0 ] = 12 ; age[ 1 ] = 4 ; age[ 2 ] = 5 ; .. Java Arrays initialization Note : Array indices always start from 0. That is, the first element of an array is at index 0. If the size of an array is n, then the last element of the array will be at index n-1.
// loop through the array // using for loop System.out.println("Using for Loop:"); for(int i = 0 ; i < age.length; i++) { System.out.println(age[i]); } } } Output Using for Loop: 12 4 5 In the above example, we are using the for Loop in Java to iterate through each element of the array. Notice the expression inside the loop, age.length Here, we are using the length property of the array to get the size of the array. We can also use the for-each loop to iterate through the elements of an array. For example, Example: Using the for-each Loop class Main { public static void main(String[] args) { // create an array int[] age = { 12 , 4 , 5 }; // loop through the array // using for loop System.out.println("Using for-each Loop:"); for(int a : age) { System.out.println(a); } } } Output Using for-each Loop: 12 4 5 Example: Compute Sum and Average of Array Elements
class Main { public static void main(String[] args) { int[] numbers = { 2 , - 9 , 0 , 5 , 12 , - 25 , 22 , 9 , 8 , 12 }; int sum = 0 ; Double average; // access all elements using for each loop // add each element in sum for (int number: numbers) { sum += number; } // get the total number of elements int arrayLength = numbers.length; // calculate the average // convert the average from int to double average = ((double)sum / (double)arrayLength); System.out.println("Sum = " + sum); System.out.println("Average = " + average); } } Output : Sum = 36 Average = 3. In the above example, we have created an array of named numbers. We have used the for...each loop to access each element of the array. Inside the loop, we are calculating the sum of each element. Notice the line, int arrayLength = number.length; Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using: average = ((double)sum / (double)arrayLength); As you can see, we are converting the int value into double. This is called type casting in Java. To learn more about typecasting, visit Java Type Casting. Multidimensional Arrays Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java. A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,
int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3]; //3 rows and 3 columns //multiplying and printing multiplication of 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=0; for(int k=0;k<3;k++) { c[i][j]+=a[i][k]*b[k][j]; }//end of k loop System.out.print(c[i][j]+" "); //printing matrix element }//end of j loop System.out.println();//new line } }} Output: 6 6 6 12 12 12 18 18 18 2.2 Unit End Question
Strings in Java are Objects that are backed internally by a char array. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. Syntax: <String_Type> <string_variable> = "<sequence_of_string>"; Example: String str = "Geeks"; Java String In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: char [] ch={'j','a','v','a','t','p','o','i','n','t'}; String s= new String(ch); is same as: String s="javatpoint"; Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The java.lang.String class implements Serializable , Comparable and CharSequence interfaces. CharSequence Interface
Note: String objects are stored in a special memory area known as the "string constant pool". Why Java uses the concept of String literal? To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
of char value. 8 static String join(CharSequence delimiter, CharSequence... elements) returns a joined string. 9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string. 10 boolean equals(Object another) checks the equality of string with the given object. 11 boolean isEmpty() checks if string is empty. 12 String concat(String str) concatenates the specified string. 13 String replace(char old, char new) replaces all occurrences of the specified char value. 14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified CharSequence. 15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case. 16 String[] split(String regex) returns a split string matching regex. 17 String[] split(String regex, int limit) returns a split string matching regex and limit. 18 String intern() returns an interned string. 19 int indexOf(int ch) returns the specified char value index. 20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index. 21 int indexOf(String substring) returns the specified substring index. 22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index. 23 String toLowerCase() returns a string in lowercase.
System.out.println("String s = " + s); // Declare String using new operator String s1 = new String("GeeksforGeeks"); // Prints the String. System.out.println("String s1 = " + s1); } } Output: String s = GeeksforGeeks String s1 = GeeksforGeeks Interfaces and Classes in Strings in Java CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex. String: String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. Creating a String There are two ways to create a string in Java: String literal String s = “GeeksforGeeks”; Using new keyword String s = new String (“GeeksforGeeks”); StringBuffer: StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences. Syntax: StringBuffer s = new StringBuffer("GeeksforGeeks"); StringBuilder: The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates an immutable sequence of characters, the StringBuilder class provides an alternate to String Class, as it creates a mutable sequence of characters. Syntax: StringBuilder str = new StringBuilder(); str.append("GFG"); StringTokenizer: StringTokenizer class in Java is used to break a string into tokens. Example:
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. StringJoiner: StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write. Syntax: public StringJoiner(CharSequence delimiter) Immutable String in Java In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created. Let's try to understand the immutability concept by the example given below: class Testimmutablestring{ public static void main(String args[]){ String s="Sachin"; s.concat(" Tendulkar");//concat() method appends the string at the end System.out.println(s);//will print Sachin because strings are immutable objects } } Output:Sachin Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with sachintendulkar. That is why string is known as immutable.
String s4="Saurav"; System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s3));//true System.out.println(s1.equals(s4));//false
Output: 1
String Concatenation in Java In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java:
sachin Sachin Java String trim() method The string trim() method eliminates white spaces before and after string. String s=" Sachin "; System.out.println(s);// Sachin System.out.println(s.trim());//Sachin Sachin Sachin Java String startsWith() and endsWith() method String s="Sachin"; System.out.println(s.startsWith("Sa"));//true System.out.println(s.endsWith("n"));//true true true Java String charAt() method The string charAt() method returns a character at specified index. String s="Sachin"; System.out.println(s.charAt( 0 ));//S System.out.println(s.charAt( 3 ));//h S h Java String length() method The string length() method returns length of the string. String s="Sachin"; System.out.println(s.length());// 6 Java String intern() method A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. String s= new String("Sachin"); String s2=s.intern(); System.out.println(s2);//Sachin Sachin Java String valueOf() method The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string. int a= 10 ; String s=String.valueOf(a); System.out.println(s+ 10 ); Output: 1010 Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second sequence of character. String s1="Java is a programming language. Java is a platform. Java is an Island."; String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava" System.out.println(replaceString); Output: Kava is a programming language. Kava is a platform. Kava is an Island. Java StringBuffer class Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed. Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order. Important Constructors of StringBuffer class Constructor Description StringBuffer() creates an empty string buffer with the initial capacity of
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. What is mutable string A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.