Você está na página 1de 15

Arrays

An array is a collection of variables of the same type, referred to by a common name. In Java,
arrays can have one or more dimensions, although the one-dimensional array is the most common.
Arrays are used for a variety of purposes because they offer a convenient means of grouping together
related variables.
For example, you might use an array to hold a record of the daily high temperature for a month, a
list of stock price averages, or a list of your collection of programming books.
The principal advantage of an array is that it organizes data in such a way that it can be easily
manipulated. For example, if you have an array containing the incomes for a selected group of
households, it is easy to compute the average income by cycling through the array. In Java Arrays are
implemented as objects.

One-Dimensional Arrays
A one-dimensional array is a list of related variables. For example, you might use a one-
dimensional array to store the account numbers of the active users on a network. Another array might be
used to store the current batting averages for a cricket team.

Declaration of one Dimensional Arrays:


type array-name[ ] = new type[size];
1. Here, type declares the element type of the array.
2. The element type determines the data type of each element contained in the array.
3. The number of elements that the array will hold is determined by size.
4. Since arrays are implemented as objects, the creation of an array is a two-step process. First, you
declare an array reference variable. Second, you allocate memory for the array, assigning a
reference to that memory to the array variable.
5. Thus, arrays in Java are dynamically allocated using the new operator.
Here is an example. The following creates an int array of 10 elements and links it to an array reference
variable named sample:
int sample[] = new int[10];
This declaration works just like an object declaration. The sample variable holds a reference to the
memory allocated by new. This memory is large enough to hold 10 elements of type int. As with objects,
it is possible to break the preceding declaration in two. For example:
int sample[]; sample = new int[10];
In this case, when sample is first created, it refers to no physical object. It is only after the second
statement executes that sample is linked with an array.
An individual element within an array is accessed by use of an index. An index describes the position of
an element within an array. In Java, all arrays have zero as the index of their first element. Because
sample has 10 elements, it has index values of 0 through 9. To index an array, specify the number of the
element you want, surrounded by square brackets. Thus, the first element in sample is sample[0], and
the last element is sample[9].

Example 1:-
class Arr{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length-1;i++){
System.out.println(arr[i]);
}

Developed by: Rajani, CSE Dept., RGUKT Page 1


}}

Example 2 :-

public class Arrays1 {


public static void main(String args[]) {
int sample[] = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
for(i = 0; i < 10; i = i+1)
System.out.println("This is sample[" + i + "]: " + sample[i]);
}
}
Output:
The output from the program is shown here:
This is sample[0]: 0
This is sample[1]: 1
This is sample[2]: 2
This is sample[3]: 3
This is sample[4]: 4
This is sample[5]: 5
This is sample[6]: 6
This is sample[7]: 7
This is sample[8]: 8
This is sample[9]: 9

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array
size)-1. All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +" : "+ arr[i]);

Example:
Java Program to find Min and Max element in user given array.
import java.util.Scanner;
class MinMax {
Developed by: Rajani, CSE Dept., RGUKT Page 2
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
System.out.println(“Enter Size of the Array: “);
int len=scan.nextInt();
int nums[] = new int[len];
int min,max;
for(int i=0;i<len;i++)
{
System.out.print("Enter"+i+"th element: ");
nums[i]=scan.nextInt();
}
min=max=nums[0];
for(int i=0;i<len;i++){
if(min>nums[i])
min=nums[i];
else
max=nums[i];
}
System.out.println("Min element is: "+min+"\nMax element is: "+max);
}
}
Cloning of arrays

If we use assignment operator to assign an object reference to another reference variable then it will
point to same address location of the old object and no new copy of the object will be created. Due to this
any changes in reference variable will be reflected in original object.
To avoid this problem we are using cloning (this is called deep copy).If we want to create a deep
copy of object X and place it in a new object Y then new copy of any referenced objects fields are created
and these references are placed in object Y. This means any changes made in referenced object fields in
object X or Y will be reflected only in that object and not in the other. In below example, we create a deep
copy of object.

// A Java program to demonstrate array copy using clone()


public class copyarray
{
public static void main(String[] args)
{
int a[] = {1, 8, 3};

// Copy elements of a[] to b[]


int b[] = a.clone();

// Change b[] to verify that b[] is different


// from a[]
b[0]++;

System.out.println("Contents of a[] ");


for (int i=0; i<a.length; i++)
System.out.print(a[i] + "");

Developed by: Rajani, CSE Dept., RGUKT Page 3


System.out.println("\n\nContents of b[] ");
for (int i=0; i<b.length; i++)
System.out.print(b[i] + "");
}
}

Output:
Contents of a[]
183

Contents of b[]
283

Multidimensional arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the reference
of other array. A multidimensional array is created by appending one set of square brackets ([]) per
dimension.
Examples:
int[][] a = new int[3][4]; //a 2D array or matrix
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of type int.

Similarly, you can declare a three-dimensional (3d) array. For example,


String[][][] personalInfo = new String[3][4][2];
Here, personalInfo is a 3d array that can hold maximum of 24 (3*4*2) elements of type String.

class MultidimensionalArray {
public static void main(String[] args) {

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};

System.out.println("Length of row 1: " + a[0].length);


System.out.println("Length of row 2: " + a[1].length);

Developed by: Rajani, CSE Dept., RGUKT Page 4


System.out.println("Length of row 3: " + a[2].length);
}
}
When you run the program, the output will be:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Since each component of a multidimensional array is also an array (a[0], a[1] and a[2] are also arrays),
you can use length attribute to find the length of each rows.

Example: Print all elements of 2d array Using Loop


class MultidimensionalArray {
public static void main(String[] args) {

int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};

for (int i = 0; i < a.length; ++i) {


for(int j = 0; j < a[i].length; ++j) {
System.out.println(a[i][j]);
}
}
}
}
Example: Multiply two Matrices

import java.util.Scanner;

class matrixmultiply

public static void main(String args[])

int r1, c1, r2, c2, sum = 0, i, j, k;

Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of first matrix");

r1 = in.nextInt();

c1 = in.nextInt();

int first[][] = new int[r1][c1];

System.out.println("Enter elements of first matrix");

Developed by: Rajani, CSE Dept., RGUKT Page 5


for (i = 0; i < r1; i++)

for (j = 0; j < c1; j++)

first[i][j] = in.nextInt();

System.out.println("Enter the number of rows and columns of second matrix");

r2 = in.nextInt();

c2 = in.nextInt();

if (c1 != r2)

System.out.println("The matrices can't be multiplied with each other.");

else

int second[][] = new int[r2][c2];

int multiply[][] = new int[r1][c2];

System.out.println("Enter elements of second matrix");

for (i = 0; i < r2; i++)

for (j = 0; j < c2; j++)

second[i][j] = in.nextInt();

for (i = 0; i < r1; i++)

for (j = 0; j < c2; j++)

for (k = 0; k < r2; k++)

sum = sum + first[i][k]*second[k][j];

multiply[i][j] = sum;

sum = 0;

System.out.println("Product of the matrices:");

Developed by: Rajani, CSE Dept., RGUKT Page 6


for (i = 0; i < r1; i++)

for (j = 0; j < c2; j++)

System.out.print(multiply[i][j]+"\t");

System.out.print("\n");

Exercise

1. Java Program to Calculate Average Using Arrays


2. Java Program to Find Largest Element of an Array
3. Java Program to Add Two Matrix Using Multi-dimensional Arrays
4. Java Program to Multiply to Matrix Using Multi-dimensional Arrays
5. Java Program to Find Transpose of a Matrix
6. Java Program to Concatenate Two Arrays
7. Java Program to Check if An Array Contains a Given Value

Developed by: Rajani, CSE Dept., RGUKT Page 7


VECTORS

1. Vector class is in java.util package of java.


2. Vector is dynamic array which can grow automatically according to the required need. Vector
does not require any fix dimension like String array and int array.
3. The Vector class implements a growable array of objects. Like an array, it contains components
that can be accessed using an integer index. However, the size of a Vector can grow or shrink as
needed to accommodate adding and removing items after the Vector has been created.
4. Vectors (the java.util.Vector class) are commonly used instead of arrays, because they expand
automatically when new data is added to them.

To Create a Vector:

Following are the list of constructors provided by the vector class.

1. Create a Vector with default initial size


Vector v = new Vector(); //it creates a vector v with initial capacity 10.
2. Create a Vector with an initial size //it creates a vector v with initial size.
Vector v = new Vector(int initialCapacity);
3. Create a Vector with an initial sizewith incremental value
//it creates a vector v with initial size and incremental value
Vector v = new Vector(int initialCapacity,int incrementalCapacity);

Common Vector Methods

There are many methods in the Vector class and its parent classes.
v is a Vector, i is an int index, o is an Object.

Method Description
v.add(o) adds Object o to Vector v
v.add(i, o) Inserts Object o at index i, shifting elements up as necessary.
v.clear() removes all elements from Vector v
v.contains(o) Returns true if Vector v contains Object o
v.firstElement(i) Returns the first element.
v.get(i) Returns the object at int index i.
v.lastElement(i) Returns the last element.
v.remove(i) Removes the element at position i, and shifts all following elements down.
v.size() Returns the number of elements in Vector v.
v.addAll(objects); Appends all of the elements in the specified Collection to the end of this Vector.
v.addAll(i,objects); Inserts all of the elements in the specified Collection into this Vector at the
specified position.
v.clone(vector name) Returns a copy of this vector.
indexOf(o) Returns the index of the first occurrence of the specified element in this vector,
or -1 if this vector does not contain the element.
lastIndexOf(o) Returns the index of the last occurrence of the specified element in this vector,
or -1 if this vector does not contain the element.

Developed by: Rajani, CSE Dept., RGUKT Page 8


Differences between a Vector and an Array
 A vector is a dynamic array, whose size can be increased, where as an array size can not be
changed.
 Reserve space can be given for vector, where as for arrays can not.
 A vector is a class where as an array is not.
 Vectors can store any type of objects, where as an array can store only homogeneous values.

Advantages of Vector:
- Size of the vector can be changed
- Multiple objects can be stored
- Elements can be deleted from a vector

Disadvantages of Vector:
- A vector is an object, memory consumption is more.

Example:-
import java.util.*;
import java.util.Collections;
import java.util.Vector;
class Vector_demo {
public static void main(String args[])
{
Vector v = new Vector();
v.add(1); //add() method appends the specified element to the end of this vector.
v.add("hello");
System.out.println("Vector is " + v);// Vector is [1, hello]

v.add(1, 2);//add() method inserts the specified element at the specified position in
this Vector.
System.out.println("Vector is " + v); //Vector is [1, 2, hello]

Vector v1 = new Vector();


v1.addAll(v);//addAll() method appends all of the elements in the specified
Collection to the end of this Vector.
System.out.println("Vector v1 is " + v1);

v1.addAll(1,v);//addAll()method inserts all of the elements in the specified


Collection into this Vector at the specified position.
System.out.println("Vector v1 is " + v1);

Vector v_clone = new Vector();


v_clone = (Vector)v.clone();//clone() This method returns a clone of this vector.
System.out.println("Clone of v: " + v_clone);

//contains() method returns true if this vector contains the specified element.
if (v.contains("hello"))
System.out.println("exists"); //exists

Developed by: Rajani, CSE Dept., RGUKT Page 9


//get() method returns the element at the specified position in this Vector.
System.out.println("element at indexx 2 is: " + v.get(2)); //element at indexx 2 is:
hello

//indexOf() method returns the index of the first occurrence of the specified element
in this vector, or -1 if this vector does not contain the element.
System.out.println("index of hello is: " + v.indexOf("hello")); //index of hello is: 2

//lastIndexOf() method returns the index of the last occurrence of the specified
element in this vector, or -1 if this vector does not contain the element.
System.out.println("last occurance of 2 is: " + v.lastIndexOf(2)); //last occurance of
2 is: 1

v.remove(2);//remove() method removes the element in the given index If the


Vector does not contain the element, it is unchanged.
System.out.println("after removal: " + v); //[1,2]

//firstElement() method returns the first component (the item at index 0) of this
vector.
System.out.println("first element of vector is: " + v.firstElement()); //first element of
vector is: 1

//size() method returns the number of components in this vector.


System.out.println(" size of vector: " + v.size()); //size of vector: 2

//lastElement() method returns the last component of the vector.


System.out.println("vector's last componenets: " + v.lastElement()); //vector's last
componenets: 2

v.insertElementAt(100, 1); //insertElementAt() method inserts the specified object


as a component in this vector at the specified index.
System.out.println(" Vector: " + v); //Vector: [1, 100, 2]

v.removeElementAt(1);//removeElement() method does not return anything. It only


removed the element in that index from the vector .
System.out.println("Vector element after removal: " +v); //Vector element after
removal: [1, 2]

Vector<String> vector = new Vector<String>();


//Add elements to Vector
vector.add("Walter");
vector.add("Anna");
vector.add("Hank");
vector.add("Flynn");
vector.add("Tom");
// By Default Vector maintains the insertion order
System.out.println("Vector elements before sorting: ");
for(int i=0; i < vector.size(); i++){

Developed by: Rajani, CSE Dept., RGUKT Page 10


//get(i) method fetches the element from index i
System.out.println(vector.get(i));
}
// Collection.sort() sorts the collection in ascending order
Collections.sort(vector);
//Display Vector elements after sorting using Collection.sort
System.out.println("Vector elements after sorting: :");
for(int i=0; i < vector.size(); i++){
System.out.println(vector.get(i));}
//void clear() This method removes all of the elements from this vector.
v.clear();
System.out.println("after clearing: " + v);//[]
}
}

Developed by: Rajani, CSE Dept., RGUKT Page 11


Java Wrapper Classes

Description

A Wrapper class in Java is the type of class .Each of Java's eight primitive data types has a class
dedicated to it. These are known as wrapper classes because they "wrap" the primitive data type into an
object of that class. The wrapper classes are part of the java.lang package, which is imported by default
into all Java programs.

The following two statements illustrate the difference between a primitive data type and an object of a
wrapper class:

int x = 25;
Integer y = new Integer(33);

The first statement declares an int variable named x and initializes it with the value 25. The second
statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the
object is assigned to the object variable y.

Advantages of Wrapper Class in Java

 They are used to convert the primitive data types into objects (Objects are needed when we need
to pass an argument in the given method).
 The package java.util contains classes which only handles objects, so wrapper class in Java
helps in this case too.
 Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
 In multithreading, we need an object to support synchronization.

Below table lists wrapper classes in Java API with constructor details.

Primitive Wrapper Constructor


Class Argument
boolean Boolean boolean or String
byte Byte byte or String
char Character char
int Integer int or String
float Float float, double or String
double Double double or String
long Long long or String
short Short short or String

Below is wrapper class hierarchy as per Java API

Developed by: Rajani, CSE Dept., RGUKT Page 12


Autoboxing(Primitive to Wrapper): Automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long
to Long, double to Double etc.

Example

public class WrapperExample1{

public static void main(String args[]){

//Converting int into Integer

int a=20;

Integer i=Integer.valueOf(a);//converting int into Integer

Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.print(a+" "+i+" "+j);

}}

Output

20 20 20

Unboxing(Wrapper to Primitive): It is just the reverse process of autoboxing. Automatically converting


an object of a wrapper class to its corresponding primitive type is known as unboxing. For example –
conversion of Integer to int, Long to long, Double to double etc.

Example

public class WrapperExample2{

public static void main(String args[]){

Developed by: Rajani, CSE Dept., RGUKT Page 13


//Converting Integer to int

Integer a=new Integer(3);

int i=a.intValue();//converting Integer to int

int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.print(a+" "+i+" "+j);

}}

Output

333

Java program to demonstrate Wrapping and UnWrapping

class WrappingUnwrapping
{
public static void main(String args[])
{
// byte data type
byte a = 1;

// wrapping around Byte object


Byte byteobj = new Byte(a);

// int data type


int b = 10;

//wrapping around Integer object


Integer intobj = new Integer(b);

// float data type


float c = 18.6f;

// wrapping around Float object


Float floatobj = new Float(c);

// double data type


double d = 250.5;

// Wrapping around Double object


Double doubleobj = new Double(d);

// char data type


char e='a';

// wrapping around Character object


Character charobj=e;

// printing the values from objects


System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Byte object byteobj: " + byteobj);

Developed by: Rajani, CSE Dept., RGUKT Page 14


System.out.println("Integer object intobj: " + intobj);
System.out.println("Float object floatobj: " + floatobj);
System.out.println("Double object doubleobj: " + doubleobj);
System.out.println("Character object charobj: " + charobj);

// objects to data types (retrieving data types from objects)


// unwrapping objects to primitive data types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;

// printing the values from data types


System.out.println("Unwrapped values (printing as data types)");
System.out.println("byte value, bv: " + bv);
System.out.println("int value, iv: " + iv);
System.out.println("float value, fv: " + fv);
System.out.println("double value, dv: " + dv);
System.out.println("char value, cv: " + cv);
}
}

Output:

Values of Wrapper objects (printing as objects)


Byte object byteobj: 1
Integer object intobj: 10
Float object floatobj: 18.6
Double object doubleobj: 250.5
Character object charobj: a
Unwrapped values (printing as data types)
byte value, bv: 1
int value, iv: 10
float value, fv: 18.6
double value, dv: 250.5
char value, cv: a

Developed by: Rajani, CSE Dept., RGUKT Page 15

Você também pode gostar