0% found this document useful (0 votes)
47 views123 pages

Java Strings and Arrays Overview

Uploaded by

bevoliv249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views123 pages

Java Strings and Arrays Overview

Uploaded by

bevoliv249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PRESENTATION

Team project by:

❑ Raghav Gogoi (77)


❑ Raja Babu (78)

❑ Siddharth Kaul (88)

❑ 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:

• Before we continue to any topic related to Java,


first let us know what is Java. So, Java is a high-
level, class based, object-oriented programming
language designed for minimal implementation
dependencies.
STRINGS IN JAVA
• . String is represent a sequence of characters .

• . Define in [Link] package.


• Strings in Java are immutable (once created, cannot be changed).

• Any modification on a String creates a new object.


The easiet way to represent a sequence of character in java by
using a character array
HO W T O CA LL
Calling String class methods (built-in functions)

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() → creates an empty string.

• String(String s) → creates a string with the same value as s.

• String(char[] arr) → converts a char array to a string.

• String(byte[] arr) → converts a byte array to a string.


.
CONTI...
Primitive
Type

Reference Creating Object

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

String Manipulation means performing different operations on strings like creating,


modifying, searching, splitting, joining, etc.
ST RI NG
METHODS & EXAMPLE

• Length() Method

• It is a method that returns the length of the strings

• Example:

• [Link](“Raja”.length());

• Output: 4
ST RI NG
METHODS & EXAMPLE

• +operator

• It is a method used to concatenate two or more strings.


C ON T IN UE
METHODS & EXAMPLE

• charAt()
• Characters in a string can be retrieved in a number of ways.

• public char charAt(int index)

• Method returns the character at the specified index.


C ON T IN UE
METHODS & EXAMPLE

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

• Example: public boolean equal(anotherString);


C ON T IN UE
METHODS & EXAMPLE

• equalsIgnoreCase()
• Compares two strings, ignoring case considerations.

public Boolean equalsIgnoreCase(anotherString);


C ON T IN UE
METHODS & EXAMPLE

• startsWith()
• Checks the String starts with the specified prefix.

public boolean startsWith(String prefix)


“[Link](“Jan”);
// Output: true

 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

• Return 0(zero), if these strings are equal.


public int compareTo(String anotherString)
C ON T IN UE
METHODS & EXAMPLE

• public int compareToIgnoreCase(String str)

• To this method is similar to compareTo() method , but this does not consider the
case of string.
• indexOf()

• . Searches for the first occurrences of a character or substring.

• . Returns -1 if the character does not occure

• public int indexOf(int ch)

• . It search for the character represented by ch within this string and returns the
C ON T IN UE
METHODS & EXAMPLE

• public int indexOf(String str)

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

• public int indexOf(int ch, int index)

• . It search for the character represented by ch within this String and return
C ON T IN UE
METHODS & EXAMPLE

• public int indexOf(String str , int index)


• . It search for the substring represented by str within this string and returns the
index of first occurrence of this substring starting from the position specified by
from index .
• Example:
• String str = “How was your day today”?;
• [Link](‘a’,6); //14
• [Link](“was”,2); // 4

C ON T IN UE
METHODS & EXAMPLE

• Replace()
• .Return a new string resulting from replacing all occurrence of oldChar in
this string with newChar

• public String replace (char oldChar, char newChar);

• String str = “How was your day today?” ;


[Link] println([Link](‘a’,’3’));
// display How w3s your d3y tod3y?”
C ON T IN UE
METHODS & EXAMPLE

valueOf()
This method is used to convert a character array into String.

The result is a string representation of argument passed as character array .

public static String valueOf(char[] data);

This method is used to convert anything into String.


C ON T IN UE
METHODS & EXAMPLE

• toLowerCase()

• . Converts all characters in a string to lower case

• public String toLowerCase();

• String s = “java”.toLowerCase(); //java

• To UpperCase()

• converts characters in a string to upper case

• public String toUpperCase();


C ON T IN UE
METHODS & EXAMPLE

• Split() method
• . can split a string into n number of sub strings.
• public String[] split(String regex)

• }

• }
C ON T IN UE
METHODS & EXAMPLE

• trim() Method in Java


• The trim() method is used with String objects.
It removes any leading (start) and trailing (end) whitespace characters from the
string.
(Whitespace includes spaces, tabs \t, and newlines \n at the ends of the string.)
QUESTION ON PALINDROM

Explanation:

• We compare the first and last character, then move inward.


A PPLI CA T IO N ST RI N GS IN
JA VA
1. Storing Text Data

 Names, addresses, messages, and other textual information.

 Example: String name = "Raja";

2. User Input and Output

 Reading input from users and displaying output.

 Example: Scanner sc = new Scanner([Link]); String input = [Link]();


CONTI....
[Link] Parsing and Processing

• Splitting, searching, or replacing data in text files, CSV, logs, etc.

• Example: String[] parts = "John,25,Engineer".split(",");

4. File and Database Operations

• File names, file paths, and SQL queries are stored as Strings.

• Example: String query = "SELECT * FROM students";

5. Web and Network Programming

• URLs, HTTP requests, JSON, and XML data are handled as Strings.

• Example: String url = "[Link]


CONTI....
6. Dynamic Message Generation

 Creating messages, reports, and notifications.

 Example: String msg = [Link]("Hello %s", name);


M CQ T IM E
Which method is used to compare two strings ignoring case?
A) equals()
B) equalsIgnoreCase()
C) compareTo()
D) compare()
ijws
M CQ T IM E

What will "Java".concat("Script")


ijws return?

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) String str = 'Hello';


B) String str = new String("Hello");
C) String str = String("Hello");
D) String str = Hello;
M CQ T IM E
Why are Strings immutable 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

What is the output ?

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.

• Fundamental for Input/Output

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

• Immutable Nature (Security + Optimization)

• Strings in Java are immutable → once created, cannot be changed.


• This provides:
• Security (passwords, URLs remain unchanged in memory).
• Performance (String Pool saves memory by reusing objects)
•Used in Every Java Application

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

•Powerful Built-in Methods


•Java’s String class provides 50+ ready-made methods like substring(), replace(), split(),
equals(), compareTo(), etc.
•This makes text processing easy.

•Foundation for Other Classes


•Used in Every Java Application

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

•Powerful Built-in Methods


•Java’s String class provides 50+ ready-made methods like substring(), replace(), split(),
equals(), compareTo(), etc.
•This makes text processing easy.

•Foundation for Other Classes


•To understand StringBuffer, StringBuilder, StringTokenizer, you must first know String.
•It’s the base for learning mutability, memory management, and performance.

• 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

• Creates an empty, mutable character buffer.


• Initial capacity (the size of the internal char[]) = 16.
• length() is 0 after construction.
Why 16?

• A small, reasonable default so small strings don’t cause immediate resizes.


• Reduces early reallocation overhead for typical short strings.

•When to use
•When you want a small, empty buffer and you don’t know the final size.

StringBuffer sb = new StringBuffer();


[Link]([Link]()); // 0
[Link]([Link]()); // 16
2) StringBuffer(String str) — construct with initial content
What it does
• Initializes content with str.
• Sets capacity = 16 + [Link]() because the implementation allocates room for the provided string
plus 16 extra characters.

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

• StringBuffer sb = new StringBuffer("Hello");


• [Link]([Link]()); // Hello
• [Link]([Link]()); // 5
• [Link]([Link]()); // 16 + 5 = 21
3) StringBuffer(int capacity) — construct with specified capacity
What it does
• Allocates the internal char[] with exactly the given capacity.
• length() is 0 initially.

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

• StringBuffer sb = new StringBuffer(50);


• [Link]([Link]()); // 0
• [Link]([Link]()); // 50
4) StringBuffer(CharSequence seq) — construct from CharSequence
What it does
• Initializes content with the characters from seq and sets capacity to 16 + [Link]().
• Works with any CharSequence implementer (String, StringBuilder, StringBuffer, CharBuffer, etc.).

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

• StringBuffer sb = new StringBuffer("Hello");


• [Link](" World");
• [Link](sb); // Hello World

1.
•2. insert()

•Description: Inserts text at the specified index.

• EXAMPLE
3. replace()
• Description: Replaces characters between start and end indexes.

• Example:

• StringBuffer sb = new StringBuffer("HelloWorld");


• [Link](5, 10, " Java");
• [Link](sb); // Hello Java
1.

•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:

StringBuffer sb = new StringBuffer("Hello");


[Link]();
[Link](sb);
1.
// olleH

6. capacity()
• Description: Returns the current capacity of the buffer.
• Example:

StringBuffer sb = new StringBuffer("Hello");


[Link]([Link]()); // 21 (16 + 5)
•7. length()
•Description: Returns the current length (number of characters).

• Example:

• StringBuffer sb = new StringBuffer("Hello");


• [Link]([Link]()); // 5
1.

•8. ensureCapacity(int minCapacity)


•Description: Ensures that capacity is at least minCapacity.

•Example:

• StringBuffer sb = new StringBuffer("Hello");


• [Link](50);
• [Link]([Link]()); // 50 (or more)
•9. setCharAt(int index, char ch)

•Description: Changes the character at the specified index.

•Example:

•StringBuffer sb 1.
= new StringBuffer("Hello");
•[Link](0, 'Y');
•[Link](sb); // Yello

•10. substring()

•Description: Returns a substring (similar to String class).

• Example:

• StringBuffer sb = new StringBuffer("HelloWorld");


• [Link]([Link](5)); // World
•MCQ SE PEHLE EK MERA

1.

•QUESTION
• DIFFERENCE BETWEEN STRING VS STRING
BUFFER
Aspect String StringBuffer
1.

Mutability Immutable (cannot change once created) Mutable (can be modified)

Faster (modifies same


Performance Slower (creates new object on modification)
object)

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

• Strings are widely used in sensitive places like network connections,


database URLs, file paths, usernames, passwords.
• If String
1.
were mutable, a hacker could change its value (e.g., modify a
DB connection string), leading to security issues.

• Caching & Reusability (String Pool)

• Java uses the String Constant Pool to store string literals.


• If String were mutable, changing "Java" would also affect all other
references to "Java" in the pool → inconsistent behavior.
• Immutability ensures safe sharing.
• Thread Safety

• Since Strings cannot change, multiple threads can safely use the
same string object without synchronization.
1.

• Hashcode Caching (Performance in Collections)


• Strings are frequently used as keys in HashMap, HashSet,
Hashtable.
• Being immutable means their hashCode never changes → lookup
remains consistent.
• If mutable, the hash could change after insertion → data loss in
collections.
• Why StringBuffer is Mutable?
•Frequent Modifications Needed
•For cases like text editing, log building, dynamic SQL queries, frequent
modifications are required.
•If we used
1. String, every change would create a new object → slow +
memory waste.
•StringBuffer allows modification in the same object.

•Efficient Memory Usage


•Maintains an internal character array (buffer) with extra capacity.
•Modifications happen in-place without creating new objects.

•Thread Safety
•StringBuffer methods are synchronized, so multiple threads can safely
1.
MCQ TIME

1.

Which of the following is true about StringBuffer in Java?


A. StringBuffer is immutable
B. StringBuffer is mutable
C. StringBuffer is faster than StringBuilder
D. StringBuffer is not thread-safe
MCQ TIME

1.

Default capacity of a StringBuffer object is:


A. 8
B. 16
C. 32
D. 0
MCQ TIME

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

2. TYPES OF ARRAYS(1D AND 2D

[Link] AND DISADVANTAGES OF ARRAY

4. DECLARING AN ARRAY

5. CREATING AN ARRAY
1.
. [Link] ARRAYS(SHOW,SORT,MAXMIN)

7. THE FOR-EACH LOOP


[Link] IN JAVA
ARRAYS IN JAVA
AN ARRAY IS A COLLECTION OF SIMILAR TYPE OF ELEMENTS WHICH ISSTORED
IN A CONTIGUOUS MEMORY LOCATION. JAVA ARRAY IS AN OBJECTWHICH
CONTAINS ELEMENTS OF A SIMILAR DATA TYPE. ADDITIONALLY, THEELEMENTS
OF AN ARRAY ARE STORED IN A CONTIGUOUS MEMORYLOCATION. IT IS A
DATA STRUCTURE WHERE WE STORE SIMILAR [Link] CAN STORE ONLY
A FIXED SET OF ELEMENTS IN A JAVA ARRAY. ARRAY INJAVA IS INDEX-BASED,
THE FIRST ELEMENT OF THE ARRAY IS STORED AT THE0TH INDEX, 2ND
ELEMENT IS STORED ON 1ST INDEX AND SO ON.

TO UTILIZE THE UTILITY METHODS PROVIDED BY THE ARRAYS CLASS IN JAVA,IT


1. IS NECESSARY TO IMPORT IT. THE ARRAYS CLASS IS PART
OFTHE [Link] [Link] [Link];
INITIALIZING AN ARRAY
Arrays can be initialized at the time of declaration orlater in the code. There are several ways to initialize anarray in
Java.

Method 1: Initialization at Declaration

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

➢ FIXED SIZE: ARRAYS HAVE A FIXED SIZE SET AT CREATION. EXPANDING AN


ARRAY REQUIRES CREATING A NEW ONE AND COPYING ELEMENTS, WHICH IS
TIME-CONSUMING AND MEMORY-INTENSIVE. EVEN DYNAMIC SIZED ARRAYS
INTERNALLY USE FIXED SIZED MEMORY ALLOCATION AND DE-ALLOCATION.

➢ MEMORY ALLOCATION ISSUES: ALLOCATING LARGE ARRAYS CAN CAUSE


MEMORY EXHAUSTION, LEADING TO CRASHES, ESPECIALLY ON SYSTEMS WITH
LIMITED RESOURCES.

➢ INSERTION AND DELETION CHALLENGES: ADDING OR REMOVING ELEMENTS


REQUIRES
1. SHIFTING SUBSEQUENT ELEMENTS, MAKING THESE OPERATIONS
INEFFICIENT.
T Y P E S O F A R R A Y S I N J AVA

 THERE ARE GENERALLY TWO TYPES OF ARRAYS IN JAVA :

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

 Memory Organization of a One-Dimensional Array

 In memory, a one-dimensional array in Java is a contiguous block of the memory locations


 allocated to the hold elements of the same data type. Each element occupies a fixed amount of memory
 determined by the data type.

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

CONSIDER A SCENARIO WHERE WE WISH TO STORE THE MARKS


ATTAINED BY 3 STUDENTS IN MATHS, ENGLISH, AND SCIENCE
SUBJECTS. HERE, WE ARE STORING A COLLECTION OF MARKS (MARKS
OF ENGLISH, MATHS, AND SCIENCE) FOR EACH STUDENT. HENCE, WE
CAN USE A TABLE TO REPRESENT AND STORE STUDENT MARKS. IN THE
STUDENT MARKS TABLE, THE ROWS WILL REPRESENT THE MARKS OF A
PARTICULAR STUDENT, AND THE COLUMNS WILL REPRESENT THE
SUBJECT IN WHICH THE STUDENT ATTAINED THOSE MARKS, AS
SHOWN BELOW:

1.
IMPORT [Link];

PUBLIC CLASS MAIN {


PUBLIC STATIC VOID MAIN(STRING ARGS[]) {
INT[][] STUDENTMARKS = NEW INT[3][3];
OUTPUT
// MARKS ATTAINED BY STUDENT 1
STUDENTMARKS[0][0] = 90; // ENGLISH
STUDENTMARKS[0][1] = 70; // MATHS
STUDENTMARKS[0][2] = 84; // SCIENCE Student Marks Matrix [[90,70,84] ,
[75,77,89] , [69,93,83]]
// MARKS ATTAINED BY STUDENT 2
STUDENTMARKS[1][0] = 75; // ENGLISH
STUDENTMARKS[1][1] = 77; // MATHS
STUDENTMARKS[1][2] = 89; // SCIENCE

// MARKS ATTAINED BY STUDENT 3


STUDENTMARKS[2][0] = 69; // ENGLISH
STUDENTMARKS[2][1] = 93; // MATHS
STUDENTMARKS[2][2] = 83; // SCIENCE

// DISPLAYING MARKS OF STUDENTS


[Link]("STUDENT MARKS MATRIX");

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

. WHICH OF THESE IS AN INCORRECT ARRAY DECLARATION?


A) INT ARR[] = NEW INT[5]
B) INT [] ARR = NEW INT[5]
C) INT ARR[] = NEW INT[5]
D) INT ARR[] = INT [5] NEW

1.
MCQ TIME

. HOW CAN YOU FIND THE LENGTH OF AN ARRAY ARR IN JAVA?


A) [Link]();
B) [Link];
C) [Link];
D) LENGTH(ARR);

1.
MCQ TIME

. WHICH OF THE FOLLOWING IS NOT A VALID WAY TO DECLARE A


TWO-DIMENSIONAL ARRAY IN JAVA?
A) INT[][] ARR = NEW INT[3][3];
B) INT ARR[][] = NEW INT[3][3];
C) INT[] ARR = NEW INT[3][];
D) INT[][] ARR = NEW INT[][];

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];

PUBLIC CLASS ARRAYTOSTRINGEXAMPLE {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
INT[] NUMBERS = {1, 2, 3, 4, 5};
STRING RESULT = [Link](NUMBERS);
[Link]("ARRAY AS STRING: " + RESULT);
}
}

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

1. Traversing means going through each element in an array

• 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

Update all elements using a loop

O
UPDATIN IN ARRAY
Update using Scanner (user input)
I N S E R T I O N I N A RR AY

DEFINATION ; WHILE INSERITON IN ARRRAY WE SHIFT THE ELEMENT AND


THEN INSERT THE ELEMENT IN THE ARRAY AT THE REQUIRED POSITON
SMALL CODE ON INSERTION
DELETION

deletion in an array in Java also requires shifting elements, because arrays have fixed
size (no direct remove operation like in ArrayList).

Deletion from Array (by index)


Deletion by Value
Using ArrayList (Easy Way) )
SEARCH IN A RR AY
• Linear Search → simple, works on unsorted arrays.

• Binary Search → faster, but array must be sorted.

• [Link]() → built-in method.


CODE ON SEARCHING
Linear Search (works on any array)
CODE ON SEARCHING
Binary Search (only for sorted arrays)
CODE ON SEARCHING
Using Java’s built-in method
WRAPPER CLASS

What are Wrapper Classes?


• In Java, wrapper classes are used to convert primitive data types (like int, char, boolean, etc.) into objects.

• Each primitive type has a corresponding wrapper class in the [Link] package.

This concept is also called Boxing (primitive → object) and Unboxing (object → primitive).

Why Use Wrapper Classes?


• Collection Frameworks (like ArrayList, HashMap) only work with objects, not primitives.
• Provide utility methods for parsing, converting, and comparing.
• Used in serialization (converting objects to stream).
• Enable object-oriented features (like null values, method calls).
• Allow autoboxing/unboxing, making code simpler.
"The wrapper classes have a number of unique methods for handling primitive data types and
objects.
"The wrapper classes have a number of unique methods for handling primitive data types and
objects.
Key Features of Wrapper Classes

• Final → cannot be extended.


• Provide constants (e.g., Integer.MAX_VALUE).
• Provide parsing methods (parseInt(), parseDouble()).
• Provide conversion methods (valueOf(), xxxValue()).
• Support Autoboxing & Unboxing.

• Why do we need Wrapper Classes?


•Collections Framework
Collections like ArrayList, HashMap, etc. work with objects only, not primitives.
Example: ArrayList<int> (not allowed)
ArrayList<Integer> (allowed)

•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:

•Integer obj = new Integer(10); // Boxing


•int a = [Link](); // Unboxing

Autoboxing/unboxing removes this boilerplate:

Integer obj = 10; // autoboxed


int a = obj; // auto-unboxed
Supports Generics
• Generics in Java work only with objects, not primitives.
• Example:

ArrayList<Integer> list = new ArrayList<>(); // works

ArrayList<int> list2 = new ArrayList<>(); // doesn't work

Improves Readability
• No need to write extra conversion code.
• Example:

• [Link](5); // automatically converts 5 (int) → Integer


• int x = [Link](0); // automatically converts Integer → int
• Consistency with Object-Oriented Design

• Java is object-oriented, but primitives are not objects.


• Wrapper classes + autoboxing/unboxing provide a bridge between
primitives and objects.
Key Points

• Autoboxing → Primitive → Object


int → Integer, char → Character, double → Double, etc.
• Unboxing → Object → Primitive
Integer → int, Character → char, etc.
• This feature was introduced in Java 5.

You might also like