Array,String and Vector
Array,String and Vector
An array is a container that can hold multiple values of the same data type. One
array object can’t hold values of different data types. In other words, we can say the
array is a collection of similar types of elements that have a contiguous memory
location.
• An array can hold the value of the same data type. It never allows
keeping values of a different datatype. If you are declaring an array of
int type it means it can hold only its values. It can’t take a value of
String type etc.
• An array is stored in a contiguous memory allocation. All the values are
stored in order and each value is placed on an index that starts from 0.
• You can declare an Array as local if you are declaring it in the method.
• The size of the array is specified only by int value. You can’t use any
other data type to specify the size of the array.
• Like other classes, Array also extends its superclass Object.
• Every array type implements the
interfaces Cloneable and java.io.Serializable.
• An array can store primitive data types and Non-primitive data types.
Before using the array, we must declare it. Like normal variables, we must provide
the data type of array and the name of an array. Data type means the type of
elements that we want to store in the Array. So, we must specify the data type of
array according to our needs. We also need to specify the name of an array so that
we can use it later by name.
datatype[] arrayName;
Or
datatype arrayName[];
Or
datatype []arrayName;
Example:
int[] number;
Or
int number[];
Or
int []number;
For the creation of an array, a new keyword is used with a data type of array. You
must specify the size of the array. The size should be an integer value or a variable
that contains an integer value. How many elements you can store in an array directly
depends upon the size of an array.
Example:
number = new int[10]; // allocating memory to array
To initialize the Array we have to put the values at each index of the array. In the
above section, we have created an Array with the size of 10. So now we will see how
we can add values in Array.
Output: 11 22 33 44 55 66 77 88 99 100
You can also construct an array by initializing the array at declaration time. If you are
initializing the array it is another way to construct an array.
dataType arrayName[] = {value1, value2, …valueN}
Some points about Initialization:
• If you choose the datatype of an array as int then values should be int
type. It means a type of value is totally dependent on the datatype of
an array.
• Value1 will be stored at 0 indexes, value2 in 1 index, and so on.
• The size of the array depends upon how many values you are
providing at the time of initialization.
int number[] = {11, 22, 33 44, 55, 66, 77, 88, 99, 100}
It’s created an array of int types as you see we are initializing it during declaration.
Example of an Array
1. To access any element from the array you must use an array name
with a subscript and the subscript takes an index. Remember one thing
here, an index should be always in an integer value.
2. An array index value always starts from 0 and ends with the array’s
length-1. So, when you are accessing an array you must take the
length of an array. If you are trying to access an element, then the
index value should be less than the length of an array.
3. All the elements can access via loops in Java.
You can access an array’s element with the name of the array variable, followed by
brackets([]). You must specify an integer value in brackets([]) called the index of an
array.
Example:
class AccessOfArray
{
public static void main(String[] args)
{
int[] number= {11, 22, 33, 44, 55, 66, 77, 88, 99, 100};
int length = number.length; // get size of array
for (int i = 0; i < length; i++)
{
System.out.println("Index of element = " + i +" & Element is = " +number[i]);
}
}
}
Like the one–dimension array, in two dimensional we provide the data type of
array and name of the array for the declaration. Data type means which type of
elements we want to store in the Array. In the two-dimensional array, we use the two
subscripts for the declaration of the array. First subscript is used for ROW and the
second for COLUMN.
datatype[][] arrayName; Or
datatype arrayName[][]; Or
datatype [][]arrayName;
Example:
int[][] number; Or
int number[][]; Or
int [][]number;
Here int is datatype and number is the name of the two-dimensional array. Two
subscripts [][] are used to define a two-dimensional array.
Like a one-dimensional array, for the creation of a two-dimensional array, the new
keyword is used with the data type of array. There are two subscripts for the size of
an array, which is the size of the matrix
You can see in the example, the first and second subscript size is 3 which means it
will create a 3X3 matrix.
You can provide value to an array at declaration time. Here is the syntax of the
initialization of a two-dimensional array it differs from the one-dimensional array.
dataType arrayName[][] = {
{value1, value2, …valueN},
{value1, value2, …valueN},
{value1, value2, …valueN},
};
Example:
int[][] number = { {11, 22, 33}, {44, 55, 66}, {77, 88, 99}};
In this example here, we are initializing a two-dimensional array. This array is holding
the 9 elements of type int.
Column 1 Column 2 Column 3
class ArrayExample
{
public static void main(String args[])
{
//declaration two dimensional array with initialization
int number [][]={ {11,22,33}, {44,55,66}, {77,88,99} };
//print the value of two dimensional array
for(int i = 0; i < 3; i++)
{
for(int j=0;j<3;j++)
{
System.out.println(" Element is = "+ number [i][j]+" ");
}
System.out.println();
}
}
}
Example 2:
The string is a class in java that is used to create the object of String type. The
object of the String class always contains a string(a group of characters). Suppose
you want to store your name in a variable then you can create an object of String
class and assign the name to the object.
To create a string
There are two ways to create the string by using the String class. We can create an
object of String by string literal and new keyword. Whenever we create a string, it
always stores in String constant pool. Let us see how we can create an object of
String in both ways.
String s;
String name;
String obj;
String s;
String name;
String obj;
s = "Hi";
name = "JavaGoal";
obj = "Hello"
s = new String("Hi");
name = new String("JavaGoal");
obj = new String("Hello");
Example:
String S2 = "RockStar";
2. indexOf() Method is used to get index of the first occurrence of a criteria specified
Example
str_Sample.indexOf('s', 3));
//Give index position for the given substring and start index
str_Sample.indexOf("is", 5));
3. Java String charAt() method returns the character at the definite index from a
string. In this Java method, the string index value starts from 0 and goes up to string
Example:
public class CharAtDemo {
public static void main(String args[]) {
String s1 = "This is String CharAt Method";
//returns the char value at the 0 index
System.out.println("Character at 0 position is: " + s1.charAt(0));
//returns the char value at the 5th index
System.out.println("Character at 5th position is: " + s1.charAt(5));
//returns the char value at the 22nd index
System.out.println("Character at 22nd position is: " + s1.charAt(22));
//returns the char value at the 23th index
char result = s1.charAt(-1);
System.out.println("Character at 23th position is: " + result);
}
}
}
}
}
}
Example:
//Convert to UpperCase
System.out.println(S1.toUpperCase());
Besides those mentioned above, there are various string methods present in Java.
Here are some of those methods:
Methods Description
str.append("Hello");
System.out.println("Value after append: "+str);
}
}
Important constructors
Example:
class ExampleOfStringBuffer
{
public static void main(String args[])
{
// creating a StringBuffer with specified string
StringBuffer name = new StringBuffer("Ravi");
name.append("kant"); // Appending string in string buffer
System.out.println("Name of Student = "+ name);
}
}
2. insert() method: This method is used to insert the given text in the string at a
given position. StringBuffer class has various forms of this method we will
discuss it later.
Example:
class ExampleOfStringBuffer
{
public static void main(String args[])
{
// creating a StringBuffer with specified string
StringBuffer name = new StringBuffer("Ravi");
// inserting string in string buffer
name.insert(4, "kant");
System.out.println("Name of Student = "+ name);
}
}
String StringBuffer
Vector is a class create array type memory block and allow to store any object(any
types of values).vector class use util package and provide various function to create
or manipulate vector onbject.
Int arr[]=new int(5);
Vector v=new Vector(5);
• The property of having a dynamic size is very much useful as it avoids the
memory wastage in case we do not know the size of the data structure at the
time of declaration.
• When we want to change the size of our data structure in the middle of a
program, vectors can prove to be very useful.
We can access the data members simply by using the index of the element, just like
we access the elements in Arrays.
Example- If we want to access the third element in a vector v, we simply refer to it as
v[3].
Vectors Constructors
Listed below are the multiple variations of vector constructors available to use:
• Methods in Vector
Example:
import java.util.*;
public class Main{
public static void main (String[] args) {
Vector v = new Vector(); // It creates a default vector
v.add(1); // Adds 1 at the end of the list
v.add("Java"); // Adds "Java" at the end of the list
v.add("is"); // Adds "is" at the end of the list
v.add("Fun"); // Adds "Fun" at the end of the list
2. Void add (int Index, E element) – It adds the given element at the specified
index in the vector
Example
import java.util.*;
public class Main{
public static void main (String[] args) {
Example:
import java.util.*;
public class Main{
public static void main (String[] args) {
Example:
import java.util.*;
public class Main{
public static void main (String[] args) {
Example:
import java.util.*;
public class Main{
public static void main (String[] args) {
}
6. Object get(int index) – It returns the element at the given position in the
vector
Example:
import java.util.*;
public class Main{
public static void main (String[] args) {
import java.util.*;
public class Main{
public static void main (String[] args) {
Vector v = new Vector(); // It creates a default vector
v.add(1); // Adds 1 at the end of the list
v.add("Java"); // Adds "Java" at the end of the list
v.add("is"); // Adds "is" at the end of the list
v.add("Fun"); // Adds "Fun" at the end of the list
import java.util.*;
public class Main{
public static void main (String[] args) {
import java.util.*;
public class Main{
public static void main(String[] args) {
//Create vectors v1, v2,v3 and v4
Vector v1 = new Vector(); //a vector with default constructor
Vector v2 = new Vector(20); // a vector of given Size
//initialize vector v2 with values
v2.add(10);
v2.add(20);
v2.add(30);
Vector v3 = new Vector(30, 10); // a vector of given Size and Increment
// create a vector v4 with given collection
List<String> aList = new ArrayList<>();
aList.add("one");
aList.add("two");
Vector v4 = new Vector(aList);
//print contents of each vector
System.out.println("Vector v1 Contents:" + v1);
System.out.println("Vector v2 Contents:" + v2);
System.out.println("Vector v3 Contents:" + v3);
System.out.println("Vector v4 Contents:" + v4);
}
}
Vector Array
Vector is dynamic and its size grows and shrinks as Arrays are static and its size
elements are added or removed. remains fixed once declared.
Vectors can store only objects. Arrays can store primitive types as
well as objects.
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
known as boxing.
Example:
class BoxingExample1{
public static void main(String args[])
{
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
}
}
Example:
class UnboxingExample1
{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
For example, if we run a HelloWorld class that contains main method and we provide
argument to it during runtime, then the syntax would be like.
Example
In this example, we created a class HelloWorld and during running the program we
are providing command-line argument.
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}