Docsity

Java String Manipulation: Methods, Substrings, and Comparisons, Summaries of Computer science

Toggle sidebar
bg1
UNIT 2 Array
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?
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Java String Manipulation: Methods, Substrings, and Comparisons and more Summaries Computer science in PDF only on Docsity!

UNIT 2 Array

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

1. Write a program to print the reverse of given array.

2. Write down the different way of array declaration?

3. Explain the different types of Array?

4. Describe the 2-D Array?

5. What is Array?

UNIT 3 String &Packages

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

3.1 String

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).

  1. By new keyword String s= new String("Welcome");//creates two objects and one reference variable In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool). Java String Example public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by java string literal char ch[]={'s','t','r','i','n','g','s'}; String s2= new String(ch);//converting char array to string String s3= new String("example");//creating java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); }} java strings example Java String class methods The java.lang.String class provides many useful methods to perform operations on sequence of char values. No. Method Description 1 char charAt(int index) returns char value for the particular index 2 int length() returns string length 3 static String format(String format, Object... args) returns a formatted string. 4 static String format(Locale l, String format, Object... args) returns formatted string with given locale. 5 String substring(int beginIndex) returns substring for given begin index. 6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index. 7 boolean contains(CharSequence s) returns true or false after matching the sequence

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

  1. }
  2. } Output:true true false class Teststringcomparison2{ public static void main(String args[]){ String s1="Sachin"; String s2="SACHIN"; System.out.println(s1.equals(s2));//false System.out.println(s1.equalsIgnoreCase(s2));//true } } Output: false true
    1. String compare by == operator The = = operator compares references not values. class Teststringcomparison3{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3= new String("Sachin"); System.out.println(s1==s2);//true (because both refer to same instance) System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool) } }
  3. Output:true false
    1. String compare by compareTo() method The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string. Suppose s1 and s2 are two string variables. If:  s1 == s2 :  s1 > s2 :positive value  s1 < s2 :negative value class Teststringcomparison4{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3="Ratan"; System.out.println(s1.compareTo(s2));// System.out.println(s1.compareTo(s3));//1(because s1>s3) System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )

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:

  1. By + (string concatenation) operator
  2. By concat() method
  1. String Concatenation by + (string concatenation) operator Java string concatenation operator (+) is used to add strings. For Example: class TestStringConcatenation { public static void main(String args[]){ String s="Sachin"+" Tendulkar"; System.out.println(s);//Sachin Tendulkar } } Output:Sachin Tendulkar The Java compiler transforms above code to this: String s=( new StringBuilder()).append("Sachin").append(" Tendulkar).toString(); In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also. For Example: class TestStringConcatenation2{ public static void main(String args[]) { String s= 50 + 30 +"Sachin"+ 40 + 40 ; System.out.println(s);//80Sachin } } 80Sachin Note: After a string literal, all the + will be treated as string concatenation operator.
  2. String Concatenation by concat() method The String concat() method concatenates the specified string to the end of current string. Syntax: public String concat(String another) class TestStringConcatenation3{ public static void main(String args[]){ String s1="Sachin "; String s2="Tendulkar"; String s3=s1.concat(s2); System.out.println(s3);//Sachin Tendulkar }

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.

  1. StringBuffer append() method The append() method concatenates the given argument with this string. class StringBufferExample{ public static void main(String args[]){ StringBuffer sb= new StringBuffer("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } }
  2. StringBuffer insert() method The insert() method inserts the given string with this string at the given position. class StringBufferExample2{ public static void main(String args[]){ StringBuffer sb= new StringBuffer("Hello "); sb.insert( 1 ,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } }