0% found this document useful (0 votes)
20 views15 pages

Understanding Arrays and Strings in Java

Uploaded by

ks5158660
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)
20 views15 pages

Understanding Arrays and Strings in Java

Uploaded by

ks5158660
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

Chapter 9

Working with Array a1nd String

Quick Chapter Summ~ry


Array
~Array is a variable representing a collection of
homogeneous type of elements.
tArrays are useful to represent vector, matrix and other
multi-dimensional data.
tvector Is a one dimensional (1-D) data structure that can
be used to store list of items like characters, numbers.
t Matrix is used to represent two dimensional (2-D) data
structure like table of rows and columns.
[TI
Creating an Array
t Creating an array Is a 2 step process :
(1) Declare an array object

(2) Create an array object

t An array object can be ueated In 2 ways :


(1) Using new operator and specifying the size

(2) Directly Initializing the concept of array

[TI
1-D array
t Array with single dimension is known as 1-D array.
t Example : Vector
t Instead of declaring individual variables like
markl, mark2, mark3, mark4, markS
we declare array mark[S]
t Index Position : mark[0],mark[1],mark[2],mark[3],mark[4]
tTo declare a 1-D array we use a pair of square brackets [ ].
t Syntax:<data type><array name>[ ]; Example : int marks[ ];
CT]
To declare 1-D array
int marks[ ] = new int [SJ;
- - ----
tHere,
marks= name of array.

Int data type uses 4 bytes storage space.

Thus array marks require 5 x 4 = 20 bytes In contiguous


location In memory.

[I]
Example : 1-D array
tThe array variable martls has an index I•~=i,t,A.\'-\ ltl;I
value from Oto 4.
. . Amy Amy
t marks[O] refers to the first element. ldatact C. Wti
t marks[4] refers to the last element.
t 1-D array is initialized using comma RMftct
VnNt
separated values of data element In
braces { }.
t Example : Int marks[ J = {90, 60, 70, 65, 80};
[TI
2-D array
t Array with two dimension Is known as 2-D array.
t 2-D arrays are used to store tabular data In the form of
rows and columns.
t Example : To store 5 student's marks in 3 tests, we may
use a tabular arrangement of marks 5 rows and 3 columns.
St•d~nts Tesll Testl Tes&J
I ~o 60 70
2 3S 30 so
3 70 1S 80
4 80 85 90
s 40 so 55

[TI
t In Java, 2-0 array can be declared using array name and
two pairs of square brackets [ ] [ ] to specify the size of
two dimensions row and column respectively.

int marks [ ] [ ] = new in [SJ [3];


t Here, the logical view of array element is a table of 5 rows
and 3 columns.
t So, 5 x 3 = 15 Integer values.
tint store 4 bytes, so 15 x 4 = 60 bytes memory store.
t Java does not support multi-dimensional arrays directly.
o=J
- -
tTo create 2-D array, we have to create an array of array.
t In marks [S] [3], it creates 1-D array object of 5 elements
and each element is 1-D array object of 3 integers.
intnuui..s =- new int (5)(3);

V,u ·fablt-

,f)(O) _..(4)(11 ---141(2)

Rderence
\ ·11ri11bles

[TI
Points to be remembered
...,,,,-it Array Is a collection of homogeneous type of data.
~ r a y elements can be accessed using Index for each
dl_menslon In [ ].

It Index value starts with O(zero).


It Attribute 'length' Is used to determine the size of the
dimension.
String_
t String Is nothing but a sequence of characters.
t String or Sequence of characters Is enclosed between
double quoteO
t In Java, characters are stored u s l n ~
tJava supports 2 types of strings: (1) String (2) StringBuffer
t Determine the length of string using length() method.
t Convert a string Into an array of bytes using getBytes()

00
String class methods
t String class provides methods for below tasks :
• Compare string
• Find length of string
• Combining strings
• Obtaining substrings
• Converting strings
• Splitting strings
• Searching for character or patterns In string
Date class
Date object using current system
(1) Date()
time
Number of milliseconds since 1,
(2) Long getTime()
Janua 1970 GMT
Date Specified time In milliseconds
(3) elapsed since 1, January 1970
(long elapsedTime) GMT (GMT : Greenwich Mean Time)
(4) String toString() Representing date and time
void setTime
(5) Sets new date and time
(long elapsedTime)
calendar class
Year of calendar
MONTH Month of calendar (O-Jan, 11-Dec)
DATE Day of calendar month.
(4) DAY_OF_MONTH Same as DATE.
(5) HOUR Hour in 12-hour notation
(6) HOUR_OF_DAY Hour in 24-hour notation
(7) MINUTE Minute
(8) SECOND Second
~
(9) AM_PM 0 for AM and 1 for PM
Day number within a week
Sun-1 ..... Sat-7
) WEEK_OF_MONTH Week number within the month
WEEK_OF_YEAR Week number within the year
DAY_OF_YEAR Day number In the year 1 for 1st day
t Date class/ Cal_e ndar class provided In [Link] package.
t Date class encapsulate both date and time and represents
the value using milliseconds precision.
tCalendar store year, month, date, hour, minute, second.

Common questions

Powered by AI

In Java, a 1-D array represents a vector, which is a sequence of elements accessible via a single index. It is declared using a pair of square brackets, such as `int marks[] = new int[5];`, and commonly used for lists of items like characters or numbers . A 2-D array, or matrix, is represented using two pairs of square brackets to specify rows and columns, like `int marks[][] = new int[5][3];`. This structure is suitable for tabular data representation, such as storing student test scores in rows and tests in columns . Java does not directly support multi-dimensional arrays; instead, it creates arrays of arrays .

Java's array implementation lacks direct support for genuine multi-dimensional arrays, such as those found in languages like Fortran or more modern structures in Python's Numpy library. Instead, Java creates arrays of arrays, essentially nesting 1-D arrays within one another. For example, a 2-D array `int marks[][] = new int[5][3];` creates an outer array of 5 elements, each of which is an array of 3 integers, rather than a single contiguous block of 15 elements. This implementation requires additional memory references and can lead to increased complexity in managing data structures for large-scale applications .

For a 1-D array in Java containing integers, memory storage is calculated by multiplying the number of elements by the byte size of the integer data type. Since an integer typically requires 4 bytes, an array like `int marks[ ] = new int[5];` occupies 5 (elements) * 4 (bytes per element) = 20 bytes of contiguous memory location .

Developers might prefer `StringBuffer` over `String` in scenarios requiring frequent modifications of strings, such as within loops or recursive functions, due to its mutable nature. Unlike `String`, where any modification creates new objects due to immutability, `StringBuffer` allows direct editing of the object, reducing memory footprint and improving performance by avoiding unnecessary object creation and garbage collection overhead. This is particularly beneficial in high-performance applications where memory efficiency and processing speed are critical .

In Java, arrays use the `length` attribute, such as `array.length`, which returns the number of elements directly allocated in the array, providing a constant-time operation since the size is fixed at creation. In contrast, strings utilize the `length()` method, reflecting their nature as objects managed by the `String` class. This method dynamically calculates the string's length, offering a higher-level abstraction suitable for objects which can be more complex or flexible in size than arrays . These differences illustrate arrays as primitive structures and strings as managed objects within Java’s memory model.

Java's management of strings as immutable objects, rather than traditional null-terminated strings like in C, provides significant advantages in security and usability. This approach prevents buffer overflow vulnerabilities, a common security issue associated with manually managed memory in null-terminated strings. Java's immutable strings reduce the risk of unintentional data modification, enhancing data integrity within applications. Usability benefits from wrapped methods for string operations like comparison, concatenation, and transformation, which abstract away the complexities of memory management and allow developers to focus on implementing functionality rather than handling memory issues explicitly .

Java strings are not null-terminated as they are in languages like C. In Java, strings are objects managed by the `String` class, ending automatically based on their length property, not a null character. Arrays, while simple containers for homogeneous data types, do not inherently include such management. They rely on an index-based system for access and manipulation, whereas Java strings encapsulate this data and provide methods for complex operations within an object-oriented framework . This distinction changes how memory and string operations are managed, highlighting Java's focus on security and ease of use.

In Java, the differentiation between arrays and strings influences program design significantly by dictating how data is handled and manipulated. Arrays offer simplicity and speed for fixed-size homogeneous data storage but lack flexibility and built-in manipulation methods, thus suitable for performance-critical areas or when simplicity is desired. Strings, as immutable objects with robust manipulation functions provided by the `String` class, support complex operations like searching, splitting, and concatenation without manual handling of size and termination. This allows program designs that encapsulate business logic closely tied to the object-oriented paradigm, making the maintenance and expansion of code structures more modular and less error-prone .

For a 2-D array of integers in Java, memory allocation is determined by the product of rows and columns, multiplied by the byte size of an integer. For instance, `int marks[ ][ ] = new int[5][3];` allocates memory for 5 rows and 3 columns, necessitating 5 * 3 * 4 = 60 bytes, given each integer uses 4 bytes. This approach respects Java's standard practice of forming arrays of arrays, affecting how memory is distributed across the heap, potentially increasing fragmentation .

Strings in Java offer a variety of manipulation methods using the `String` class, such as comparing `string.compareTo()`, finding lengths `length()`, concatenation `string.concat()`, obtaining substrings `string.substring()`, converting cases, splitting `string.split()`, and pattern search `string.contains(pattern)`. Arrays, however, do not natively support such high-level operations because they are lower-level data structures focused on storing homogeneous data . Strings handle character sequences and support more complex operations than basic arrays, highlighting their object-oriented handling of data .

You might also like