Java Strings and Arrays Overview
Java Strings and Arrays Overview
❑ Yudhveer (109)
ST RI NGS & AR RAY I N
JA VA
JAVA OVERVIEW
Java is a high-level, class-based, object-oriented programming
language and computing platform. Developed by Sun
Microsystems (now Oracle) and released in 1995, it is renowned
for its "Write Once, Run Anywhere" (WORA) capability, meaning
compiled Java code can run on any platform supporting the
Java Virtual Machine (JVM) without recompilation
STRINGS IN JAVA
• Basic Introduction:
In Java, String is a class, so you can call its methods (functions) using the dot operator (.).
HO W T O CA LL
Calling your own function with a string
You can also pass a String into your own function and call it.
.
STRING
Constructors of String Class
String
Type Type
Array Type
CONTI....
1. primitive types _- are the most basic data types. They are not objects and represent raw values.
Java provides 8 primitive types:
.
CONTI...
2. object type - unlike primitive types, everything else is an object type. Object types are based on classes and
store references (addresses in memory) rather than raw values.
CONTI.....
3. Array object - arrays are actually objects (not just containers).
• Even if they store primitives, the array itself is an object on the heap.
• The variable you declare (e.g., int[] arr) is just a reference pointing to that array object.
CONTI.....
4. Reference type - a reference type is a type that refers to an object in memory.
STRING MANIPULATION
String manipulation in Java means working with and modifying strings using various
methods and classes. Since strings are very common in Java programming (for input,
output, data processing, etc.), Java provides many built-in features for string manipulation.
OR
• Length() Method
• Example:
• [Link](“Raja”.length());
• Output: 4
ST RI NG
METHODS & EXAMPLE
• +operator
• charAt()
• Characters in a string can be retrieved in a number of ways.
• equals()
• In this method, it compares the string with string. It returns true if the argument is
not null and it contains the same sequence of character.
• equalsIgnoreCase()
• Compares two strings, ignoring case considerations.
• startsWith()
• Checks the String starts with the specified prefix.
endsWith()
Checks the String ends with the specified suffix.
public boolean endsWith(String suffix)
“January”.endsWith(“ry”);
// Output true
C ON T IN UE
METHODS & EXAMPLE
• compareTo()
• Compares two strings and to know which is bigger or smaller
• Return negative integer, if this String object is less than the argument string
• Return positive integer if this String object is greater than the argument string
• To this method is similar to compareTo() method , but this does not consider the
case of string.
• indexOf()
• . It search for the character represented by ch within this string and returns the
C ON T IN UE
METHODS & EXAMPLE
• . It search for the substring Specified by str within this string and return the index
of first occurrence of this substring.
Example:
String str = “How was your day today?”;
[Link](‘t’); //17
[Link](“was”); // 4
• . It search for the character represented by ch within this String and return
C ON T IN UE
METHODS & EXAMPLE
• Replace()
• .Return a new string resulting from replacing all occurrence of oldChar in
this string with newChar
valueOf()
This method is used to convert a character array into String.
• toLowerCase()
• To UpperCase()
• Split() method
• . can split a string into n number of sub strings.
• public String[] split(String regex)
• }
• }
C ON T IN UE
METHODS & EXAMPLE
Explanation:
• File names, file paths, and SQL queries are stored as Strings.
• URLs, HTTP requests, JSON, and XML data are handled as Strings.
A) Java Script
B) JavaScript
C) ScriptJava
D) Error
M CQ T IM E
iWhat is the correct way to declare a String in Java?
A) To improve performance
B) To allow modifications in-place
C) To ensure thread safety and security
D) Because Java does not support mutable objects
M CQ T IM E
i
String s = "Hello";
[Link](" World");
[Link](s);
A) Hello World
B) Hello
C) World
D) Compilation Error
H U M S A B Y E ST R I N G
PA D H H I Q R H E H K YA
VA J A H H P D H N E K I
WH Y STU DY STR IN G IN
JA VA ?
• Most Commonly Used Data Type
• In real-world applications (websites, apps, databases, etc.), text data is everywhere: names, addresses, passwords,
messages, file paths, JSON/XML data.
• All these are handled using strings.
• Whatever we type as input in Java (from console, files, or network), it is first received as a string.
• Example: [Link]() always returns a String.
•Whether you’re working in Core Java, JDBC, Servlets, JSP, Spring, Hibernate, or even Android, you’ll always
need strings for:
•Database queries (SQL is written as string).
•File handling.
•Web requests/responses.
•Data transfer between systems.
•Whether you’re working in Core Java, JDBC, Servlets, JSP, Spring, Hibernate, or even Android, you’ll always
need strings for:
•Database queries (SQL is written as string).
•File handling.
•Web requests/responses.
•Data transfer between systems.
• In Simple Words:
• We study Strings in Java because they are the backbone of text handling in every
ST RI NGB UF FER C LASS
A ND
ST RI NGB UF FER C LASS P REDEF IN ED
M ETH ODS
STRING BUFFER
Introduction
• Definition
•StringBuffer is a mutable sequence of characters in Java.
•Unlike String (immutable), a StringBuffer object can be modified without creating new
objects.
•It is synchronized (thread-safe), so multiple threads can use it safely, but this makes it
slightly slower than StringBuilder.
KE Y F E AT UR E S OF
ST R ING B UF FE R
• Mutable – Unlike String, StringBuffer objects can be changed without creating new objects.
• Thread-safe – Methods of StringBuffer are synchronized, meaning multiple threads can safely
use it.
• Capacity management –
• By default, it starts with a capacity of 16 characters.
• If content grows beyond capacity, it automatically increases capacity ((oldCapacity * 2) +
2).
EXAMPLE ON STRING BUFFER ….. HOW
BE DECLARED
STRING CONSTRUCTORS
Constructor Description
StringBuffer() Empty buffer, capacity = 16
StringBuffer(String str) Initializes with given string, capacity = 16 + [Link]()
StringBuffer(int capacity) Empty buffer with given capacity
StringBuffer(CharSequence seq) Initializes with given sequence
1 ) StringBuffer() — default constructor
What it does
•When to use
•When you want a small, empty buffer and you don’t know the final size.
Important edge-case
• If str == null → calling this constructor causes a NullPointerException (the constructor uses
[Link]() internally).
•When to use
•When you want an initial text already in the buffer and some extra room to append.
• EXAMPLE
Edge-cases / errors
• If capacity is negative → constructing the internal char[] throws
NegativeArraySizeException.
• Very large capacity may cause OutOfMemoryError.
•When to use
•When you can estimate the final size and want to avoid repeated resizing (best for
performance/memory trade-off).
Edge-case
• If seq == null → NullPointerException (because the constructor calls [Link]()).
• EXAMPLE
• CharSequence cs = "Java";
• StringBuffer sb = new StringBuffer(cs);
• [Link]([Link]()); // 16 + 4 = 20
• [Link]([Link]()); // Java
ST RI NGS B UF FER MET HO D
1. append()
• Description: Adds text at the end of the buffer.
• EXAMPLE
1.
•2. insert()
• EXAMPLE
3. replace()
• Description: Replaces characters between start and end indexes.
• Example:
•4. delete()
•Description: Deletes characters between start and end indexes.
•Example:
•
• StringBuffer sb = new StringBuffer("Hello Java");
• [Link](5, 10);
• [Link](sb); // Hello
5. reverse()
• Description: Reverses the sequence of characters.
• Example:
6. capacity()
• Description: Returns the current capacity of the buffer.
• Example:
• Example:
•Example:
•Example:
•StringBuffer sb 1.
= new StringBuffer("Hello");
•[Link](0, 'Y');
•[Link](sb); // Yello
•10. substring()
• Example:
1.
•QUESTION
• DIFFERENCE BETWEEN STRING VS STRING
BUFFER
Aspect String StringBuffer
1.
Synchronized (thread-
Thread Safety Not synchronized
safe)
Less memory (reuse
Memory Usage More memory (new objects)
buffer)
Frequently modified
Best Use Fixed text / rarely modified
strings
Why String is Immutable in Java?
• Security
• Since Strings cannot change, multiple threads can safely use the
same string object without synchronization.
1.
•Thread Safety
•StringBuffer methods are synchronized, so multiple threads can safely
1.
MCQ TIME
1.
1.
If we create
1.
StringBuffer sb = new
StringBuffer("Java"); what will [Link]() return?
A. 4
B. 16
C. 20
D. 0
MCQ TIME
1.
A. HelloWorld
B. Hello World
C. WorldHello
D. Compilation error
ARR AYS IN JAVA
1.
1. ARRAYS IN JAVA
4. DECLARING AN ARRAY
5. CREATING AN ARRAY
1.
. [Link] ARRAYS(SHOW,SORT,MAXMIN)
You can initialize an array at the time of declarationusing curly braces {} with the values separated bycommas.
Syntax
dataType[] arrayName = {value1, value2, ..., valueN};
EXAMPLE:
INT[] NUMBERS={1,2,3,4,5};
1.
String [] name={“sid”, “bob”, “ram”};
F E AT U R E S O F A R R AY
I N JAVA
Array in Java possess several key features:
• Fixed Size:
• Once an array is created, its size is fixed and cannot be changed. This
means the number of elements it can hold is determined at the time of
instantiation.
• Homogeneous Elements:
• Arrays store elements of the same data type. This can be primitive types
(like int, char, boolean) or objects of a specific class.
• Zero-Based Indexing:
• Elements in a Java array are accessed using an index, which starts from 0
A DVA N TAG E S O F
A R R AY
ARRAYS MAINLY HAVE ADVANTAGES LIKE RANDOM ACCESS AND CACHE FRIENDLINESS OVEROTHER
DATA STRUCTURES THAT MAKE THEM USEFUL.
➢ STORING AND ACCESSING DATA: ARRAYS STORE ELEMENTS IN A SPECIFIC ORDER AND ALLOW CONSTANT-TIME O(1)ACCES
TO ANY ELEMENT.
SEARCHING: IF DATA IN ARRAY IS SORTED, WE CAN SEARCH AN ITEM IN O(LOG N) TIME. WE CAN ALSO FIND
FLOOR(),CEILING(), KTH SMALLEST, KTH LARGEST, ETC EFFICIENTLY.
➢ MATRICES: TWO-DIMENSIONAL ARRAYS ARE USED FOR MATRICES IN COMPUTATIONS LIKE GRAPH ALGORITHMS ANDIMAGE
PROCESSING.
➢ IMPLEMENTING OTHER DATA STRUCTURES: ARRAYS ARE USED AS THE UNDERLYING DATA STRUCTURE FORIMPLEMENTING
STACKS AND QUEUES.
➢ DYNAMIC PROGRAMMING: DYNAMIC PROGRAMMING ALGORITHMS OFTEN USE ARRAYS TO STORE INTERMEDIATERESULTS O
SUBPROBLEMS IN ORDER TO SOLVE A LARGER PROBLEM.
➢ DATA BUFFERS: ARRAYS SERVE AS DATA BUFFERS AND QUEUES, TEMPORARILY STORING INCOMING DATA LIKENETWORK
PACKETS, FILE STREAMS, AND DATABASE RESULTS BEFORE PROCESSING.
ADVANTAGES OF ARRAY DATA STRUCTURE:
➢ EFFICIENT AND FAST ACCESS: ARRAYS ALLOW DIRECT AND EFFICIENT ACCESS TO ANY ELEMENT IN THE COLLECTIONWITH
CONSTANT ACCESS TIME, AS THE DATA IS STORED IN CONTIGUOUS MEMORY LOCATIONS
➢ [Link]: ARRAYS STORE ELEMENTS IN CONTIGUOUS MEMORY, ALLOWING EFFICIENT ALLOCATION IN ASINGLE
BLOCK AND DOES NOT REQUIRE EXTRA STORAGE FOR LINKING DIFFERENT BLOCKS.
➢ VERSATILITY: ARRAYS CAN BE USED TO STORE A WIDE RANGE OF DATA TYPES, INCLUDING INTEGERS, FLOATING-POINT
D I S A D VA N TA G E O F
A R R AY
1-D ARRAY-A one-dimensional array can be visualized as a single row or a column of array elements that
are represented by a variable name and whose elements are accessed by index values.
For example, the score of a series of football matches can be stored in a one-dimensional array.
1.
THERE ARE GENERALLY TWO TYPES OF ARRAYS IN JAVA :
2-D ARRAYS
➢ A 2D array in Java is an array of arrays. Think of it like a table with rows and columns, where
each cell holds a value. It’s like a grid or matrix that can store data in a more organized way.
➢ Java arrays allow storing data in contiguous memory, where each element is accessed using two
indices: one for the row and another for the column.
➢ This structure is useful for representing grids, tables, matrices, and other data structures that
require rows and columns.
Create Two Dimensional Array in Java
Everything, including the array data structure, in Java language is treated as objects. Hence, we
must use the new keyword to create a two-dimensional array object, as shown below. Let’s describe
it below:
THERE ARE GENERALLY TWO TYPES OF ARRAYS IN JAVA :
2-D ARRAYS
➢ A 2D array in Java is an array of arrays. Think of it like a table with rows and columns, where each cell holds a
value. It’s like a grid or matrix that can store data in a more organized way.
➢ Java arrays allow storing data in contiguous memory, where each element is accessed using two indices: one for the
row and another for the column.
➢ This structure is useful for representing grids, tables, matrices, and other data structures that require rows and
columns.
Create Two Dimensional Array in Java
Everything, including the array data structure, in Java language is treated as objects. Hence, we must use the new
keyword to create a two-dimensional array object, as shown below. Let’s describe it below:
E X A M P L E O F 2 - D A R R A Y I N J AV A
1.
IMPORT [Link];
}
}
1.
MCQ TIME
. . WHICH OF THESE OPERATORS IS USED TO ALLOCATE MEMORY TO ARRAY VARIABLE
IN JAVA?
A) MALLOC
B) ALLOC
C) NEW
D) NEW MALLOC
1.
MCQ TIME
..
1.
MCQ TIME
1.
MCQ TIME
1.
MCQ TIME
HOW MANY COLUMNS DOES A HAVE IF IT IS CREATED AS
FOLLOWS INT[][] A = { {2, 4, 6, 8}, {1, 2, 3, 4}};?
A. 2
B. 4
C. 8
D. NONE
1.
MCQ TIME
-
HOW WOULD YOU GET THE VALUE 6 OUT OF THE FOLLOWING
ARRAY INT[][] A = { {2, 4, 6, 8}, {1, 2, 3, 4}};?
A. A[0][3]
B. A[1][3]
C. A[0][2]
D. A[2][0]
E. A[3][1]
1.
NG
[Link]() IN JAVA IS USED TO RETURN A STRING REPRESENTATION OFTHE
CONTENTS OF AN ARRAY. WHEN APPLIED TO AN ARRAY OBJECT, IT RETURNS
ASTRING CONTAINING THE ELEMENTS OF THE ARRAY SEPARATED BY COMMAS.
IMPORT [Link];
1.
❖ ARRAY OPERATION
1 . TRAVERSING AN ARRAY
2 . UPDATING ELEMENTS
3 . INSERTION
4 . DELETION
5 . SEARCHING IN ARRAYS
❖ T RA VERSIN G O F A RR AY
• Traversing an array in Java means visiting (or accessing) each element of the array
one by one. It is usually done to display, update, or process elements.
❖ T RA VERSIN G O F A RR AY
Using for loop (basic loop)
}
❖ T RA VERSIN G O F A RR AY
Using for-each loop
}
❖ T RA VERSIN G O F A RR AY
Using while loop
}
❖ T RA VERSIN G O F A RR AY
Using do-while loop
}
❖ T RA VERSIN G O F A RR AY
. Using Streams (Java 8+)
}
UPDATIN IN ARRAY
• arrays are mutable, meaning you can update (modify) the value of any element by
accessing it with its index.
UPDATIN IN ARRAY
Update using index
}
UPDATIN IN ARRAY
O
UPDATIN IN ARRAY
Update using Scanner (user input)
I N S E R T I O N I N A RR AY
deletion in an array in Java also requires shifting elements, because arrays have fixed
size (no direct remove operation like in ArrayList).
• Each primitive type has a corresponding wrapper class in the [Link] package.
This concept is also called Boxing (primitive → object) and Unboxing (object → primitive).
•Utility Methods
Wrapper classes provide many useful methods.
Example: [Link]("123") → converts string to number.
•Serialization
Objects can be stored/transmitted (serialization), primitives cannot.
Autoboxing and Unboxing in Java (Wrapper Classes)
Autoboxing
• Converting a primitive type → Wrapper class object (automatically by the compiler).
• Example:
Autoboxing and Unboxing in Java (Wrapper Classes)
Unboxing
• Converting a Wrapper class object → primitive type (automatically by the compiler).
• Example:
Why Autoboxing and Unboxing Exist in Java?
• Collections Only Store Objects
• Java’s Collections Framework (like ArrayList, HashMap) can only store objects, not primitive types.
• Example: ArrayList<int> is not allowed, but ArrayList<Integer> is.
• Autoboxing automatically converts primitives to objects so you don’t have to manually wrap them.
• Cleaner and Simpler Code
• Before autoboxing, you had to manually create objects and extract primitives:
Improves Readability
• No need to write extra conversion code.
• Example: