You are on page 1of 38

Unit 1 / Chapter 5

ARRAYS, STRINGS AND


PREDEFINED CLASSES
ARRAY

Array is a collection of elements of same type.

Java provides a data structure, the array, which stores a fixed sized sequential collection of
elements of the same type.

An array is used to store a collection of data.

In java, arrays are treated as objects. while using arrays we create objects for arrays.
DEFINITION

Array is an object which represent a fixed-sized ordered group of data elements of


the same type.

It can hold primitive values or object references as its data elements.

These data elements can be accessed by index.

An array is a homogeneous collection.

Example: int BCA[100];


The arrays are classified into 2 categories,
 Single Dimension arrays

 Multidimensional Array

To create an array in java, we use 3 steps.

1. Declare a variable to hold array.

2. Create new array object and assign it to the array variable.

3. Initialize or assign values to the array elements.


DECLARING AN ARRAY
•An array is declared by specifying the data type of elements it is going to hold.

•The array declaration is usually the data type followed by a pair of square brackets
followed by the array name.

•Format: datatype[] arrayName; datatypearrayName[];

•Example: int[] numbers; int numbers[];


CREATING ARRAYS
 Like other java objects, the array objects also need to be declared at compile time.

 The actual array construction with a new keyword involves the memory allocation and
array object creation at runtime.

SYNATX: var-name = new type [size];

int [] array; // array declaration

array = new int[5]; // array construction at runtime

int array = new int[5]; // array construction at runtime


INITIALIZING ARRAY
 Array can either have all of their elements initialised at the time of declaration
or the elements can be individually initialised after declaration.
 int[] myarray = new int[ 5];
myarray[0] = 10;
myarray[1] = 20;
myarray[2] = 30;
myarray[3] = 40;
myarray[4] = 50;
Initializing array at the time of declaration,

int[ ] numbers = {10, 20, 30, 40, 50};

int[ ] numbers = new int[] {10, 20, 30, 40, 50};


ARRAY OF OBJECT REFERENCES

An array of object references type is created by specifying the object type and the size of the
array.

For example, an array of date objects is declared and constructed as,

Date[] birthdates = new Date[5];

An array of 5 Date object references will be created with each element initialised to null.

The actual construction of the array object and initialization will be done only at run time.
MULTIDIMENSIONAL
ARRAYS
A multidimensional array is an array references.

Since an array object can store object references, it can store references to other
arrays. Thus, can declared as array of arrays.

The multidimensional arrays are either regular or non-regular arrays.

A regular array’s elements are array references to the array of equal size.

Conceptually, it is a matrix like structure where number of rows and columns are
known.
DECLARATION, CREATING, INITIALIZATION

•In java, an array of arrays can be defined as follows,

<element type> [ ] [ ] … [ ] <array name>; or

element type> <array name>[ ] [ ] … [ ];

•The following declarations are all equivalent:

int [ ] [ ] arr; // 2-dimensional array

int [ ] arr [ ]; // 2-dimensional array

int arr [ ] [ ]; // 2-dimensional array


•We can combine the declaration with the construction of the multidimensional
array as follows,

int [ ] [ ] arr = new int[4][5]; // 4x5 matrix of ints

The following code shows 2 different ways of initializing,

int [ ] [ ] arr = {{1,2,7}, {3,1,7}};

int [ ] multi [ ] = { new int[2], {4,8,9,3}};


ARRAY METHODS
Arrays in java comes with a number of pre-written methods.

The methods that we discuss below are found in java.util.Array class.

To use those methods, we have to add the below statement in the program.

import java.util.Arrays;

This is to tell the compiler where to find the code for these methods.

equals(), copyOfRange(), toString(), sort().


equals()
The equals( ) method is used to determine if two arrays are equal to each other.

It returns true if the arrays are equal and false if they are not.

Two arrays are considered equal if they have the same number of elements and the
elements are arranged in the same order.

int [ ] arr1 = {0,2,4,6,8,10}; boolean result1 = Arrays.equals(arr1, arr2);

int [ ] arr2 = {0,2,4,6,8,10}; boolean result2 = Arrays.equals(arr1, arr3);

int [ ] arr3 = {10,8,6,4,2,0};


copyOfRange( )
The copyOfRange( ) method allows to copy the content of one array into another.

It requires 3 arguments.

Example, int [ ] source = {12, 1, 5, -2, 16, 14, 18, 20, 25};

We can copy the contents of source array into a new array dest,

int [ ] dest = Array.copyOfRange(source, 3, 7);


toString( )
The toString( ) returns a string that represents the contents of an array.

This makes it easy for us to display the contents of the array.

Example, int [ ] numbers = { 1, 2, 3, 4, 5};

system.out.println(Arrays.toString(numbers));
sort( )
The sort( ) method allows to sort arrays.

It takes in array as argument.

Example, int [ ] numbers = {12, 1, 3, 22, 19, 20};

We can sort by using statement, Arrays.sort(numbers);

The sort() method does not written a new array, it simply modifies the array that is
passed in as argument.

system.out.println(Arrays.toString(numbers));
STRINGS
STRING – An Array Of Characters
oOne of the most important java data type is string.

oString defines and supports character strings.

o in java strings are objects and string class is part of java.lang package.

oWhen we create string literal, we actually creating String object.

oFor example, system.out.println(“Hello World”);

oHere “Hello world” is automatically converted into a string object


by java.
How Strings Are Created?
We can construct string just like we create any other object; by using new and calling string constructor.

String str = new String(“Hello”);


 This creates a string object called str that contains the character string “Hello”.

 We can also construct string from another string,

String str = new String(“Hello”);

String str2 = new String(str);


 Another way to create a string is,

String str = “Hello World”;


Primitive Type Vs. Reference Type

All data types in java ca be classified as primitive type or a reference type.

There are only 8 primitive types in java [ byte, short, int, long, float, double, char and
Boolean] the rest are reference types.

Examples for reference types are string, arrays, classes and interfaces.

One of the main difference between a primitive type and a reference type is the data that is
stored.
WHY ARE STRINGS CALLED IMMUTABLE?

String objects are created by either using new operator or enclosing a sequence of
characters in double quotes.

The string object created by either ways is immutable, means once we create a string
object by specifying a sequence of characters, that object will always represent that same
sequence of characters throughout its life.

For instance, if we create a string object as,String str = new String(“Hello”);


Now the string object created has sequence of 5 characters.

We can never change this sequence of characters in this object, no method in
java.lang.String class allow us to do.

Any method that may appear to be changing the string actually creates a new string object.

For example, if we try to modify the string “Hello” by concatenating “World” as,

String str = new String(“Hello”);

str.concat(“World”);

system.out.println(str); //prints hello


The string object created on the first line is not modified, it is still same and contains
“Hello”.

The call to concat() creates another string object.

String str1 = new String (“Hello”);

String str2 = new String (“World”);

str1=str2;

system.out.prinln(str1);
STRING METHODS

Concat() Replace() Substring() toLowerCase()

toUpperCase() toString() equals() trim()

charAt() indexOf() length() equalsIgnoreCase()


STRING BUFFER CLASS

The StringBuffer class provides us with a better alternative, this class represents a string that
can be modified without creating too many objects.

Like the string class, StringBuffer class also represents Strings of characters in java.

The major difference between a string object and StringBuffer object is that the StringBuffer
object is mutable.

StringBuffer buffer = new StringBuffer(“Hello”);


COMMAND LINE ARGUMENTS

•The command line arguments represent the values passed to main() method.

•To receive and stores the values, main() method provides arguments called as String
args[].

•The main() method must always have the following signature,

public static void main(String[] args)


 Here args is the name of the array of strings that contains the list of arguments.
WRAPPER CLASSES
The primitives in java are not objects. However, sometimes we might want to treat them as
objects instead of primitive values.

For instance, if we want to store primitive like objects in collection, they must be objects, so
we want to represent them as objects.

To facilitate this conversion, java provides us wrapper class.

Each primitive type in java has a corresponding wrapper class.

The wrapper class contain a number of useful methods and it's defined in java.lang package,
The wrapper class can wrap [encapsulate] a single immutable primitive value.

For example, a wrapper class integer wraps an in value; a class named Boolean wraps
Boolean value and so on.
Primitive Types Corresponding Wrapper Class
boolean Boolean
byte Byte
short Short
char Character
int Integer
long Long
float Float
double double
CREATING WRAPPER CLASS OBJECTS

We can create wrapper class objects in 2 ways,

1. Use wrapper class constructor that takes primitive value as argument.

2. Invoke a static valueOf() method of a corresponding wrapper class.


a] Creating Wrapper Objects Using Wrapper Class Constructors

If we want a particular primitive value, say int 100 to be treated as object, we need to
wrap it into a wrapper object.

We can create a wrapper object as follows,

1. Find out what is the corresponding wrapper class for the primitive type; for int
primitive, it will be Integer class.

2. Create an instance of wrapper class by passing the int value,

Integer intobj = new Integer(100);


Primitive Using Wrapper Class Constructor
Int Int i=10; //convert the primitive ‘i’ to an integer object
Integer i1 = new Integer(i); //Using primitive variable as argument

//We can also pass primitive value or string as below,


Integer i1 = new Integer(i);
Integer i2 = new Integer(‘i’);
Float float f=3.14f;
Float f1 = new Float(f); //Using primitive variable as argument

//We can also pass primitive value or string as below,


Float f1 = new Float(3.14f);
Float f2 = new Float(‘f’);
b] Creating Wrapper Objects Using valueOf() method

Another way of creating a wrapper object is invoking a static method valueOf() method
of a wrapper class, this method takes a string as an argument. Valueof(String s).

 if we want to get a wrapper object for int value 100, we can do by following steps,

1. Find out what is the corresponding wrapper class for the primitive type; for int
primitive, it will be Integer class.

2. Invoke integer.valueOf() method by passing a string containing the int value,

Integer intobj = Integer.valueOf(“100”);


CHARACTER
CLASS
1. Boolean isLetter(<character>);
2. Boolean isDigit(<character>);
3. Boolean isWhitespace(<character>);
4. Boolean isUpperCase(<character>);
5. Boolean isLowerCase(<character>);
6. Character toUpperCase(<character>);
7. Character toLowerCase(<character>);
8. toString(Char ch);
Autoboxing and Unboxing
AUTOBOXING:
To convert from int to Integer, instead of writing
Integer intObj = new Integer(100);
We can write as
Integer intObj = 100;

UNBOXING:
To convert from Integer to int,
int m = intObj.intValue();
We can simply write,
int m = intObj;
THANK YOU

You might also like