Ii-I R21 Oopj Module-2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 67

ARRAYS AND STRINGS

MODULE-2
SYLLABUS

 Arrays: Declaration, Initialization and accessing values,


One-Dimensional Arrays, Multi-dimensional arrays,
Alternative Array Declaration Syntax, var-arg methods,
Wrapper Classes.

Strings: String, StringBuffer and StringBuilder classes.


ARRAYS
 An array is a group of like-typed variables that are
referred to by a common name.
Arrays of any type can be created and may have one or
more dimensions.
A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related
information.
ONE-DIMENSIONAL ARRAYS
 A one-dimensional array is, essentially, a list of like-typed
variables.

To create an array, you first must create an array variable of the
desired type.

The general form of a one-dimensional array declaration is


type var-name[ ];
ONE-DIMENSIONAL ARRAYS
 For example, the following declares an array named month_days
with the type “array of int”:
int
month_days[];
Although this declaration establishes the fact that month_days is
an array variable, no array actually exists.
To link month_days with an actual, physical array of integers, you
must allocate one using new and assign it to month_days.
new is a special operator that allocates memory.
ONE-DIMENSIONAL ARRAYS
 The general form of new as it applies to one dimensional arrays
appears as follows:
array-var = new type [size];

That is, to use new to allocate an array, you must specify the type
and number of elements to allocate.

The elements in the array allocated by new will automatically be


initialized to zero (for numeric types), false (for boolean), or null.
ONE-DIMENSIONAL ARRAYS
It is possible to combine the declaration of the array variable with
the allocation of the array itself, as shown here:
type var-name[ ] = new type [size];
ONE-DIMENSIONAL ARRAYS
Arrays can be initialized when they are declared.

An array initializer is a list of comma-separated expressions


surrounded by curly braces.

The array will automatically be created large enough to hold the


number of elements you specify in the array initializer. There is no
need to use new.
ONE-DIMENSIONAL ARRAYS
For example, to store the number of days in each month, the
following code creates an initialized array of integers:
MULTI-DIMENSIONAL ARRAYS
In Java, multidimensional arrays are actually arrays of arrays.

To declare a multidimensional array variable, specify each


additional index using another set of square brackets.

For example, the following declares a two-dimensional array


variable called twoD:
int twoD[][]=new int[4][5];
MULTI-DIMENSIONAL ARRAYS
Conceptually, this array will look like the one shown in Figure
MULTI-DIMENSIONAL ARRAYS
When you allocate dimensions manually, you do not need to
allocate the same number of elements for each dimension.

As stated earlier, since multidimensional arrays are actually arrays


of arrays, the length of each array is under your control.

For example, the following program creates a two-dimensional


array in which the sizes of the second dimension are unequal:
MULTI-DIMENSIONAL ARRAYS
The use of uneven (or irregular) multidimensional arrays may not
be appropriate for many applications, because it runs contrary to
what people expect to find when a multidimensional array is
encountered.

It is possible to initialize multidimensional arrays. To do so, simply


enclose each dimension’s initializer within its own set of curly
braces.
ALTERNATIVE ARRAY DECLARATION
There is a second form that may be used to declare an array:
type[ ] var-name;

Here, the square brackets follow the type specifier, and not the
name of the array variable.

For example,
ALTERNATIVE ARRAY DECLARATION
The following declarations are also equivalent:
VARIABLE-LENGTH ARGUMENTS
Java has included a feature that simplifies the creation of methods
that need to take a variable number of arguments.

This feature is called varargs and it is short for variable-length


arguments.

A method that takes a variable number of arguments is called a


variable-arity method, or simply a varargs method.
VARIABLE-LENGTH ARGUMENTS
variable-length arguments could be handled two ways,
neither of which was particularly pleasing.

First, if the maximum number of arguments was small


and known, then you could create overloaded versions of
the method, one for each way the method could be called.
VARIABLE-LENGTH ARGUMENTS

In cases where the maximum number of potential


arguments was larger, or unknowable, a second approach
was used in which the arguments were put into an array,
and then the array was passed to the method.

This approach is illustrated by the following program:


VARIABLE-LENGTH ARGUMENTS
In the program, the method vaTest( ) is passed its arguments
through the array v.
This old-style approach to variable-length arguments does enable
vaTest( ) to take an arbitrary number of arguments.
However, it requires that these arguments be manually packaged
into an array prior to calling vaTest( ).
Not only is it tedious to construct an array each time vaTest( ) is
called, it is potentially error-prone.
VARIABLE-LENGTH ARGUMENTS
A variable-length argument is specified by three periods (…).
For example, here is how vaTest( ) is written using a vararg:
static void vaTest(int … v) {
}
This syntax tells the compiler that vaTest( ) can be called with zero
or more arguments. As a result, v is implicitly declared as an array
of type int[ ].
Thus, inside vaTest( ), v is accessed using the normal array syntax.
VARIABLE-LENGTH ARGUMENTS
There are two important things to notice about this program.

First, as explained, inside vaTest( ), v is operated on as an array.

This is because v is an array. The … syntax simply tells the


compiler that a variable number of arguments will be used, and
that these arguments will be stored in the array referred to by v.
VARIABLE-LENGTH ARGUMENTS

Second, in main( ), vaTest( ) is called with different numbers of


arguments, including no arguments at all.

The arguments are automatically put in an array and passed to v.

In the case of no arguments, the length of the array is zero.


VARIABLE-LENGTH ARGUMENTS
A method can have “normal” parameters along with a variable-
length parameter.

However, the variable-length parameter must be the last parameter


declared by the method.

For example, this method declaration is perfectly acceptable


int doIt(int a, int b, double c, int … vals)
VARIABLE-LENGTH ARGUMENTS
For example, the following declaration is incorrect:
int doIt(int a,int b, double c, int … vals, Boolean stopFlag)

There is one more restriction to be aware of: there must be only


one varargs parameter.

For example, this declaration is also invalid:


VARIABLE-LENGTH ARGUMENTS
OVERLOADING VARARG METHODS
You can overload a method that takes a variable-length
argument

This program illustrates both ways that a varargs method


can be overloaded.
VARIABLE-LENGTH ARGUMENTS
OVERLOADING VARARG METHODS
 First, the types of its vararg parameter can differ. This is the case for vaTest(int
…) and vaTest(boolean …).

 Therefore, just as you can overload methods by using different types of array
parameters, you can overload vararg methods by using different types of
varargs.

 In this case, Java uses the type difference to determine which overloaded
method to call.
VARIABLE-LENGTH ARGUMENTS
OVERLOADING VARARG METHODS
The second way to overload a varargs method is to add one or
more normal parameters.

This is what was done with vaTest(String, int …).

In this case, Java uses both the number of arguments and the
type of the arguments to determine which method to call.
VARIABLE-LENGTH ARGUMENTS
VARARG AND AMBIGUITY
Somewhat unexpected errors can result when overloading a
method that takes a variable-length argument.

These errors involve ambiguity because it is possible to create an


ambiguous call to an overloaded varargs method.
VARIABLE-LENGTH ARGUMENTS
VARARG AND AMBIGUITY
In this program, the overloading of vaTest( ) is perfectly correct.

However, this program will not compile. Because the vararg


parameter can be empty, this call could be translated into a call to
vaTest(int …) or vaTest(boolean …). Both are equally valid.

Thus, the call is inherently ambiguous.


VARIABLE-LENGTH ARGUMENTS
VARARG AND AMBIGUITY
Here is another example of ambiguity. The following overloaded
versions of vaTest( ) are inherently ambiguous even though one
takes a normal parameter.

Although the parameter lists of vaTest( ) differ, there is no way for


the compiler to resolve the following call: vaTest(1)
WRAPPER CLASSES
Java uses primitive types such as int or double, to hold the basic
data types supported by the language.
Primitive types, rather than objects, are used for these quantities
for the sake of performance.
Using objects for these values would add an unacceptable
overhead to even the simplest of calculations.
Thus, the primitive types are not part of the object hierarchy, and
they do not inherit Object.
WRAPPER CLASSES
Despite the performance benefit offered by the primitive types,
there are times when you will need an object representation.

 For example, you can’t pass a primitive type by reference to a


method.

 Also, many of the standard data structures implemented by Java


operate on objects, which means that you can’t use these data
structures to store primitive types.
WRAPPER CLASSES
To handle these situations, Java provides type wrappers, which are
classes that encapsulate a primitive type within an object.

The type wrappers are Double, Float, Long, Integer, Short, Byte,
Character, and Boolean.

These classes offer a wide array of methods that allow you to fully
integrate the primitive types into Java’s object hierarchy.
WRAPPER CLASSES
CHARACTER
Character is a wrapper around a char. The constructor for
Character is Character(char ch)
Here, ch specifies the character that will be wrapped by the
Character object being created.
To obtain the char value contained in a Character object, call
charValue( ), shown here: char charValue( )
It returns the encapsulated character.
WRAPPER CLASSES
BOOLEAN
 Boolean is a wrapper around boolean values. It defines these
constructors:
Boolean(boolean boolValue)
Boolean(String boolString)
 In the first version, boolValue must be either true or false.
 In the second version, if boolString contains the string "true" (in
uppercase or lowercase), then the new Boolean object will be true.
Otherwise, it will be false.
WRAPPER CLASSES
BOOLEAN
To obtain a boolean value from a Boolean object, use
booleanValue( ), shown here:

boolean booleanValue( )

It returns the boolean equivalent of the invoking object.


WRAPPER CLASSES
THE NUMERIC TYPE WRAPPERS
 These are
 Byte,
 Short,
 Integer,
 Long,
 Float, and
 Double.
 All of the numeric type wrappers inherit the abstract class Number.
WRAPPER CLASSES
THE NUMERIC TYPE WRAPPERS
 Number declare methods that return the value of an object in each of the different
number formats. These methods are shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
 These methods are implemented by each of the numeric type wrappers.
WRAPPER CLASSES
THE NUMERIC TYPE WRAPPERS
 All of the numeric type wrappers define constructors that allow an object
to be constructed from a given value, or a string representation of that
value.
 For example, here are the constructors defined for Integer:
Integer(int num)
Integer(String str)
 If str does not contain a valid numeric value, then a
NumberFormatException is thrown.
WRAPPER CLASSES
THE NUMERIC TYPE WRAPPERS
 This program wraps the integer value 100 inside an Integer object
called iOb.
 The program then obtains this value by calling intValue( ) and stores
the result in i.
 The process of encapsulating a value within an object is called boxing.
 Thus, in the program, this line boxes the value 100 into an Integer
Integer iOb = new Integer(100);
WRAPPER CLASSES
THE NUMERIC TYPE WRAPPERS
The process of extracting a value from a type wrapper is called
unboxing.

For example, the program unboxes the value in iOb with this
statement:
int i=iOB.intValue();
STRINGS
STRING CLASS
String is probably the most commonly used class in Java’s class
library.
The first thing to understand about strings is that every string you
create is actually an object of type String.
Even string constants are actually String objects.
For example, in the statement System.out.println(“This is a
String,too”);
The String “ This is a String,too” is a String Object.
STRING CLASS
The second thing to understand about strings is that objects of type
String are immutable; once a String object is created, its contents
cannot be altered.

An important point to note here is that, while the String object is
immutable, its reference variable is not.

The reference was made to refer to a newly formed String object.


STRING CLASS
 Java defines peer classes of String, called StringBuffer and
StringBuilder, which allow strings to be altered.

 Strings can be constructed in a variety of ways. The easiest is to use a


statement like this:
String myString=“this is a test”;

 Once you have created a String object, you can use it anywhere that a
string is allowed.
STRING CLASS
Java defines one operator for String objects: +. It is used to
concatenate two strings.

For example, this statement


String myString=“I” + ”like” +
”JAVA”;
STRING CLASS
 The String class contains several methods that you can use.
 You can test two strings for equality by using equals( ).
 You can obtain the length of a string by calling the length( ) method.
 You can obtain the character at a specified index within a string by calling
charAt( ).
 The general forms of these three methods are shown here:
boolean equals(secondStr)
int length( )
char charAt(index)
STRING CLASS
You can have arrays of strings, just like you can have arrays of any
other type of object.
STRINGBUFFER CLASS
Somewhat unexpectedly, when you create a String object, you are
creating a string that cannot be changed.

You can still perform all types of string operations.

The difference is that each time you need an altered version of an


existing string, a new String object is created that contains the
modifications. The original string is left unchanged.
STRINGBUFFER CLASS
For those cases in which a modifiable string is desired, Java
provides two options: StringBuffer and StringBuilder.

Both hold strings that can be modified after they are created.

The String, StringBuffer, and StringBuilder classes are defined


in java.lang.
STRINGBUFFER CLASS
A StringBuffer is like String, but can be modified.

StringBuffer represents growable and writable character


sequences.

StringBuffer may have characters and substrings inserted in the


middle or appended to the end.
STRINGBUFFER CLASS
The principal operations on a StringBuffer are the append
and insert methods.

Each effectively converts a given datum to a string and then


append or inserts the characters to that string to the string
buffer.
STRINGBUFFER CLASS
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.
STRINGBUFFER CLASS
Every string buffer has a capacity.

As long as the length of the character sequence contained in the
string buffer does not exceed the capacity, it is not necessary to
allocate a new internal buffer array.

If the internal buffer overflows, it is automatically made larger. It


increases the capacity by (oldcapacity*2)+2.
STRINGBUILDER CLASS
StringBuilder in Java represents a mutable sequence of characters.

The function of StringBuilder is very much similar to the


StringBuffer class.

The StringBuilder class provides no guarantee of synchronization


whereas the StringBuffer class does.
STRINGBUILDER CLASS
 This class is designed for use as a drop-in replacement for
StringBuffer in places where the StringBuffer was being used by a
single thread.

 Where possible, it is recommended that this class be used in


preference to StringBuffer as it will be faster under most
implementations.

 Instances of StringBuilder are not safe for use by multiple threads.


STRINGBUILDER CLASS
 This class is designed for use as a drop-in replacement for StringBuffer
in places where the StringBuffer was being used by a single thread.

 Where possible, it is recommended that this class be used in preference


to StringBuffer as it will be faster under most implementations.

 Instances of StringBuilder are not safe for use by multiple threads.


End of Module-2

You might also like