Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
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]);
}
Example 2 :-
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.
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.
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.
class MultidimensionalArray {
public static void main(String[] args) {
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
import java.util.Scanner;
class matrixmultiply
r1 = in.nextInt();
c1 = in.nextInt();
first[i][j] = in.nextInt();
r2 = in.nextInt();
c2 = in.nextInt();
if (c1 != r2)
else
second[i][j] = in.nextInt();
multiply[i][j] = sum;
sum = 0;
System.out.print(multiply[i][j]+"\t");
System.out.print("\n");
Exercise
To Create a Vector:
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.
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]
//contains() method returns true if this vector contains the specified element.
if (v.contains("hello"))
System.out.println("exists"); //exists
//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
//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
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.
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.
Example
int a=20;
}}
Output
20 20 20
Example
}}
Output
333
class WrappingUnwrapping
{
public static void main(String args[])
{
// byte data type
byte a = 1;
Output: