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:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents
a sequence of characters. The java.lang.String class is used to create a string object.
Java String methods
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.
1. Get string length: str.length()
2. Get character at index: str.charAt(index)
3. Get substring from index: str.substring(index)
4. Get substring between indexes: str.substring(startIndex, endIndex)
5. Find index of substring: str.indexOf(substring)
6. Convert to uppercase: str.toUpperCase()
7. Convert to lowercase: str.toLowerCase()
8. Trim whitespaces: str.trim()
9. Check if starts with: str.startsWith(prefix)
10. Check if ends with: str.endsWith(suffix)
ow to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
If the string doesn't exist in the pool, a new string instance is created and placed in the
pool.
For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
2) By new keyword
1. String s=new String("Welcome”);//creates two objects and one reference variable
Java String Example
StringExample.java
1. public class StringExample
2. {
3. public static void main(String args[]){
4. String s1="java";//creating string by Java string literal
5. char ch[]={'s','t','r','i','n','g','s'};
6. String s2=new String(ch);//converting char array to string
7. String s3=new String("example");//creating Java string by new keyword
8. System.out.println(s1);
9. System.out.println(s2);
10. System.out.println(s3);
11. }}
Output:
java
strings
example
STRING BUFFER CLASS
Java StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
The StringBuffer class in Java is used to create mutable (modifiable) string objects.
Unlike the regular String class, a StringBuffer can be changed after creation.
Notably, StringBuffer is thread-safe, meaning that multiple threads cannot access it
simultaneously, ensuring safety and order.
Important Constructors of StringBuffer Class
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length
Important methods of StringBuffer class
append(String s) It is used to append the specified string
with this string.
insert(int offset, String s) It is used to insert the specified string
with this string at the specified position
replace(int startIndex, int endIndex, It is used to replace the string from
String str) specified startIndex and endIndex.
delete(int startIndex, int endIndex) It is used to delete the string from
specified startIndex and endIndex.
reverse() is used to reverse the string.
charAt(int index) It returns the character at the specified
index.
length() It is used to return the length of the
string i.e. total number of characters.
What is a mutable String?
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
Example code for string buffer class
public class StringBufferExample {
public static void main(String[] args) {
// Create a StringBuffer with an initial value
StringBuffer stringBuffer = new StringBuffer("Hello");
// Append additional text to the StringBuffer
stringBuffer.append(" World");
System.out.println("After appending: " + stringBuffer);
// Insert text at a specific position
stringBuffer.insert(5, " Beautiful");
System.out.println("After inserting: " + stringBuffer);
// Delete characters from index 6 to 16
stringBuffer.delete(6, 16);
System.out.println("After deleting: " + stringBuffer);
// Reverse the content of the StringBuffer
stringBuffer.reverse();
System.out.println("After reversing: " + stringBuffer);
// Get the length of the StringBuffer
int length = stringBuffer.length();
System.out.println("Length of the StringBuffer: " + length);
// Get the character at a specific index
char character = stringBuffer.charAt(2);
System.out.println("Character at index 2: " + character);
// Replace a portion of the StringBuffer
stringBuffer.replace(0, 3, "Hi");
System.out.println("After replacement: " + stringBuffer);
Output:
After appending: Hello World
After inserting: Hello Beautiful World
After deleting: Hello World
After reversing: dlroW olleH
Length of the StringBuffer: 11
Character at index 2: r
After replacement: Hi World
Difference between multithreading and multitasking
S.NO Multitasking Multithreading
While in multithreading, many
In multitasking, users are allowed to threads are created from a
1.
perform many tasks by CPU. process through which
computer power is increased.
S.NO Multitasking Multithreading
While in multithreading also,
Multitasking involves often CPU
2. CPU switching is often involved
switching between the tasks.
between the threads.
While in multithreading,
In multitasking, the processes share
3. processes are allocated the
separate memory.
same memory.
While the multithreading
The multitasking component
4. component does not involve
involves multiprocessing.
multiprocessing.
While in multithreading also, a
In multitasking, the CPU is provided
CPU is provided in order to
5. in order to execute many tasks at a
execute many threads from a
time.
process at a time.
In multitasking, processes don’t
While in multithreading, each
share the same resources, each
6. process shares the same
process is allocated separate
resources.
resources.
Multitasking is slow compared to
7. While multithreading is faster.
multithreading.
While in multithreading,
In multitasking, termination of a
8. termination of thread takes less
process takes more time.
time.
Isolation and memory protection Isolation and memory protection
9.
exist in multitasking. does not exist in multithreading.
S.NO Multitasking Multithreading
It helps in developing efficient It helps in developing efficient
10.
programs. operating systems.
Examples: running multiple
Examples: splitting a video encoding task into
applications on a computer,
multiple threads, implementing a responsive
running multiple servers on
user interface in an application
a network
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous
memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
1. int a[]={33,3,4,5};//declaration, instantiation and initialization
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Output:
10
20
70
40
50
Types of Arrays in java
There are two types of arrays.
o Single Dimensional Array
o Multidimensional Array
In Java, there are mainly three types of arrays:
Single-Dimensional Arrays:
A single-dimensional array is the simplest type of array.
It contains elements of the same data type arranged in a single row.
The elements are accessed using a single index.
int[] numbers = {1, 2, 3, 4, 5};
Multi-Dimensional Arrays:
Multi-dimensional arrays contain elements in multiple rows and columns.
The most common type is a two-dimensional array (matrix).
Elements are accessed using two indices (row and column).
java
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Jagged Arrays:
A jagged array is an array of arrays where each row can have a different length.
It's an array of arrays, where each "sub-array" can have a different size.
java
Copy code
int[][] jaggedArray = {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}};
Example of types of array
public class ArrayTypesExample {
public static void main(String[] args) {
// Single-Dimensional Array
int[] numbers = {1, 2, 3, 4, 5};
// Multi-Dimensional Array (2D)
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Jagged Array (2D)
int[][] jaggedArray = {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}};
// Accessing elements
System.out.println("Element at index 2 of numbers array: " + numbers[2]);
System.out.println("Element at row 1, column 2 of matrix: " + matrix[1][2]);
System.out.println("Element at row 2, index 1 of jaggedArray: " + jaggedArray[2][1]);
Understanding these basic types of arrays and their usage is crucial for working with
collections of data in Java.
Output
Element at index 2 of numbers array: 3
Element at row 1, column 2 of matrix: 6
Element at row 2, index 1 of jaggedArray: 7
Difference between interfaces and class
Class Interface
The keyword used to create a The keyword used to create an interface is
class is “class” “interface”
Class Interface
A class can be instantiated i.e., An Interface cannot be instantiated i.e.
objects of a class can be created. objects cannot be created.
Classes do not support multiple The interface supports
inheritance. multiple inheritance.
It can be inherited from another
It cannot inherit a class.
class.
It can be inherited by a class by using the
It can be inherited by another keyword ‘implements’ and it can be
class using the keyword ‘extends’. inherited by an interface using the
keyword ‘extends’.
It can contain constructors. It cannot contain constructors.
It cannot contain abstract
It contains abstract methods only.
methods.
Variables and methods in a class
can be declared using any access All variables and methods in an interface
specifier(public, private, default, are declared as public.
protected).
Variables in a class can be static,
All variables are static and final.
final, or neither.
Defines behaviors (methods). Defines a contract for implementing
Classes
Steps to create packages in java