Arrays , strings
Arrays
• An array is collection of elements of the same datatype.
• It can hold primitive values .
• These data elements are accessible by the index.
Declaration of an array:
syntax: datatype[] arrayname;
Ex: int[5] numbers;
Arrays size:
When an array object is created, we need to specify how many
elements is going to hold. It is the array size.
• Int number=10;
• Int total = number*2;
• Int[] intArray; /////reference of an array
• IntArray= new int[total];
• Created size is 20.
Initializing arrays at the time of
declaration
We can create the array of strings as:
type[] variable name={element1, element2,…}
int[] numbers={10,20,30,40};
Default value for array elements:
Byte, short, int=0, long=0l,float=0.0f,double=0.0, Boolean = false,
char=‘\u000’
Instantiating an Array in Java
• When an array is declared, only a reference of an array is created.(A reference of an array in
Java is essentially a variable that points to the memory location where the array is stored).
• To create or give memory to the array, you create an array like this:
• var-name = new type [size];
• Example:
//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20]
Array Literal in Java
• In a situation where the size of the array and variables of the array
are already known, array literals can be used.
• //Declaring array literal
Datatype[] arrayname={element 1,element2}
• int[] scores = { 1,2,3,4,5,6,7,8,9,10 };
• There is no need to write the new int[] part in Java’s latest versions.
// Java program to illustrate creating an array
// of integers, puts some values in the array,
// and prints each value to standard output.
arr[2]=30;
class GFG { arr[3] = 40;
public static void main(String[] args){ arr[4] = 50;
// declares an Array of integers. int[] arr;
// accessing the elements of the specified array
// allocating memory for 5 integers.
for (int i = 0; i < arr.length; i++)
arr = new int[5];
System.out.println("Element at index " + i+ " : " + arr[i]);
// initialize the first elements of the array
}
arr[0] = 10;
//initialize the second elements of the array }
arr[1] = 20; Output
• Element at index 0 : 10
• Element at index 1 : 20
• Element at index 2 : 30
• Element at index 3 : 40
• Element at index 4 : 50
Inbuilt classes like string,
character
• Strings, which are widely used in Java programming, are a sequence
of characters. In Java programming language, strings are treated as
objects.
• The Java platform provides the String class to create and manipulate
strings.
• In Java, a string is a sequence of characters. For example, "hello" is a
string containing a sequence of characters 'h', 'e', 'l', 'l', and ‘o’.
• We use double quotes to represent a string in java.
Example: Create a String in Java
• class Main {
• public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
JAVA string Operations
• Java provides various string methods to perform different operations on strings. We will look into some of the commonly
used string operations
• Get the Length of a String
• To find the length of a string, we use the length() method
•class Main {
• public static void main(String[] args) {
• // create a string create
• String greet = "Hello! World";
• System.out.println("String: " + greet);
• // get the length of greet
• int length = greet.length();
• System.out.println("Length: " + length);
•} String: Hello!
World Length: 12
•}
Join Two Java Strings
• We can join two strings in Java using the concat() method.
class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}}
•First String: Java
•Second String: Programming
•Joined String: Java Programming
Compare Two Strings
• In Java, we can make comparisons between two strings using the equals() method
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}}
• Strings first and second are equal: true
• Strings first and third are equal: false
String buffer
• String Buffer is a class in Java that represents a mutable sequence of characters. It provides an
alternative to the immutable String class, allowing you to modify the contents of a string without
creating a new object every time.
• Here are some important features and methods of the StringBuffer class:
StringBuffer objects are mutable, meaning that you can change the contents of the buffer without creating
a new object.
The initial capacity of a StringBuffer can be specified when it is created, or it can be set later with the
ensureCapacity() method.
The append() method is used to add characters, strings, or other objects to the end of the buffer.
The insert() method is used to insert characters, strings, or other objects at a specified position in the
buffer.
The delete() method is used to remove characters from the buffer.
• The reverse() method is used to reverse the order of the characters in the buffer
•Here is an example of using StringBuffer to concatenate strings by using append():
class StringBufferExample
{ public static void main(String[] args)
• {
• StringBuffer sb = new StringBuffer();
• sb.append("Hello");
• sb.append("world");
• String message = sb.toString();
• System.out.println(message);
• }
•}
•Output: Helloworld
• Important Constructors of StringBuffer class
StringBuffer(): creates an empty string buffer with an 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.
2.insert() method
• The insert() method inserts the given string with this string at the given position.
• Example
•import java.io.*;
•class A {
• public static void main(String args[])
• {
• StringBuffer sb = new StringBuffer("Hello "); sb.insert(1, "Java");
• // Now original string is changed System.out.println(sb);
• }
•} output:Hjavaello
3. replace() method:method replaces the given string from the specified beginIndex and endIndex-1
•The replace() mimport java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.replace(1, 3, "Java"); System.out.println(sb);
}
}
Output:HJavalo
4. delete() method
• The delete() method of the StringBuffer class deletes the string from the specified beginIndex to endIndex-1
•Example: import java.io.*; class A {
• public static void main(String args[])
• {
• StringBuffer sb = new StringBuffer("Hello");
• sb.delete(1, 3);
• System.out.println(sb);
• }
•}
Output:Hlo
1. reverse() method
• The reverse() method of the StringBuilder class reverses the current string.
• Example:
•import java.io.* ; class A {
• public static void main(String args[])
• {
• StringBuffer sb = new StringBuffer("Hello"); sb.reverse();
• System.out.println(sb);
• }
•}
Output:olleH
6. capacity() method
• The capacity() method of the StringBuffer class returns the
current capacity of the buffer. The default capacity of the buffer is 16. If
the number of characters increases from its current capacity, it
increases the capacity by (oldcapacity*2)+2.
• For instance, if your current capacity is 16, it will be (16*2)+2=34.
Methods of Java StringBuffer class
Methods Action Performed
append() Used to add text at the end of the existing text.
The length of a StringBuffer can be found by th length( ) method.
length()
the total allocated capacity can be found by the capacity( ) method.
capacity()
This method returns the char value in this sequ the specified index.
charAt()
Deletes a sequence of characters from the invo object.
delete()
deleteCharAt() Deletes the character at the index specified by t
Ensures capacity is at least equal to the given minimum.
ensureCapacity()
insert() Inserts text at the specified index position.
length() Returns the length of the string.
reverse() Reverse the characters within a StringBuffer ob
Replace one set of characters with another set i StringBuffer
replace() object.