0% found this document useful (0 votes)
1 views

Array,String and Vector

An array in Java is a container that holds multiple values of the same data type, stored in contiguous memory locations, and can be either one-dimensional or two-dimensional. One-dimensional arrays use a single subscript for indexing, while two-dimensional arrays use two subscripts, resembling a matrix. Strings in Java are immutable sequences of characters, created using string literals or the new keyword, and are part of the java.lang package.

Uploaded by

Who Am i
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Array,String and Vector

An array in Java is a container that holds multiple values of the same data type, stored in contiguous memory locations, and can be either one-dimensional or two-dimensional. One-dimensional arrays use a single subscript for indexing, while two-dimensional arrays use two subscripts, resembling a matrix. Strings in Java are immutable sequences of characters, created using string literals or the new keyword, and are part of the java.lang package.

Uploaded by

Who Am i
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Array in java

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.

Types of Array in java

1. One-dimensional array in java or a single-dimensional array


2. Two-dimensional array in java or 2d array in java

• One-dimensional array in java

One Dimensional Array always uses only one subscript([]). A one-dimensional


array in java behaves like a list of variables. You can access the variables of an
array by using an index in square brackets preceded by the name of that array.
The index value should be an integer.
Steps:
• Declaration of Array
• Construction of Array
• Initialization of Array

Declaration of One-dimensional array in java

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;

• the datatype can be a primitive data type(int, char, Double, byte,


etc.)or Non-primitive data (Objects).
• the arrayName is the name of an array
• [] is called a subscript.

Example:
int[] number;
Or
int number[];
Or
int []number;

Construction of One-dimensional array in java

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.

arrayName = new DataType[size];

Example:
number = new int[10]; // allocating memory to array

Memory Representation after Construction


The index of an array starts from 0 and ends with length-1. The first element of an
array is number[0], the second is number[1], and so on. If the length of an array is n,
the last element will be arrayName[length-1]. Since the length of the number array is
10, the last element of the array is number[9].

Initialization of One-dimensional array in java

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.

public class MyExample


{
public static void main(String[] args)
{
// Declaration of Array
int[] number;
// Construction of Array with given size
// Here we are giving size 10 it mean it can hold 10 values of int type
number = new int[10];
// Initialization of Array
number[0] = 11;
number[1] = 22;
number[2] = 33;
number[3] = 44;
number[4] = 55;
number[5] = 66;
number[6] = 77;
number[7] = 88;
number[8] = 99;
number[9] = 100;
for(int i = 0; i < number.length; i++)
System.out.print(number[i] + " ");
}
}

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.

Memory Representation after Initialization

Example of an Array

public class MyExample


{
public static void main(String[] args)
{ // Creating a int Array with with values
int[] number = new int[] { 11, 22, 33, 44, 55, 66, 77, 88, 99};
System.out.println("Print int Array:");
for(int i = 0; i < number.length; i++)
{
System.out.println("Values on index "+ i + ": " + number[i]);
} // Creating a String Array with with values
String[] names = new String[] { "Java", "Goal", "Learning", "Website", "for",
"Java", "Concepts"}
System.out.println("Print String Array:");
for(int i = 0; i < names.length; i++)
{
System.out.println("Values on index "+ i + ": " + names[i]);
}
}
}

Accessing array elements in java

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]);
}
}
}

• Two-dimensional array in java

A two-dimensional array(2-D) is the simplest form of a multidimensional array. A


two-dimensional array is an array of arrays because they store in tabular form. Like
a single-dimensional array, we must declare the two-dimensional array
variable. We must specify the array name followed by two square brackets
called subscript([][]).
A two-dimensional array is stored in the tabular form of the row-column matrix. The
two-dimensional array uses two subscripts([][]) where the first index behaves like a
row and the second index column. The size of the matrix depends upon the size of
subscripts.
Steps:
• Declaration of Array
• Construction of Array
• Initialization of Array

Declaration of two-dimensional array Java

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.

Construction of two-dimensional array Java

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

arrayName = new DataType[size][size];


Example:
number = new int[3][3]; // allocating memory to array

Memory Representation after Construction

You can see in the example, the first and second subscript size is 3 which means it
will create a 3X3 matrix.

Column 1 Column 2 Column 3

Row 1 number[0][0] number[0][1] number[0][2]

Row 2 number[1][0] number[1][1] number[1][2]

Row 3 number[2][0] number[2][1] number[2][2]

The first element of array is number[0][0], second is number[0][1] and so on.


Initialization of two-dimensional array Java

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}};

Memory Representation after Initialization

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

Row 1 number[0][0]=11 number[0][1]=22 number[0][2]=33

Row 2 number[1][0]=44 number[1][1]=55 number[1][2]=66

Row 3 number[2][0]=77 number[2][1]=88 number[2][2]=99


A two-dimensional array is an array of array. You can see the structure of the array:

In Java two – dimensional arrays are arrays of arrays, so arrayName[x][y] is an array


x(size) of rows in arrays and y(size) of columns in the array.
An example of a two-dimensional array to access value from array.
Example 1:

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();
}
}
}

An example of a two-dimensional array. In which we will declare and initialize the


array.

Example 2:

public class ExampleOfTwoDimentionalArray


{
public static void main(String[] args)
{
// Creation of Array with initilization
int[][] number = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
String[][] names = {
{"Priya", "Neha", "Seema"},
{"Riya","Meena", "Rita"},
{"Priti", "Nita", "Sita"},
};
// Accessing of Array
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(number[i][j]);
System.out.println(names[i][j]);
}
}
}
}
String in Java
A String is a sequence of characters or group of characters. In Java, a string is a
sequence of characters. For example, "hello" is a string containing a sequence of
characters 'h', 'e', 'l', 'l', and 'o'.
Java string class exists in java.lang package and implementing three interfaces
that are Serializable, Comparable, and CharSequence.

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.

• Properties of Java String


1. As we know string is a group of characters, but a java String always be an object
and it can’t be a primitive type.
2. Whenever we want to create a string(Group of characters), we need to an object
of type String.
3. To create a string the sequence of characters enclosed within double quotes “ ”
4. In java String class is the final class, so we can’t extend it.
5. The objects of String are immutable which means a constant and cannot be
changed once created. If we try to change it, the JVM creates a new string object in
the background. We will discuss in detail how the string is immutable.

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.

• Creation of string by string literal


The most common way to create a string is by the string literal. In this case, a string
literal is enclosed with double quotes. Whenever we create a string by java string
literal the JVM creates an object of String. Let us see how we create a string by use
of a
string literal:
String: To create an object by string literal we use the String class.
referenceVariable: is the name of a variable that holds the object of String.
“string”: In simple terms, it is a group of characters, but it is considered an object of
the String class.
Example:
String nameOfStudent = “Ravi”;
String s = "Hi";
String obj1 = "Hello";
String obj = "123";

• Creation of string object by use of new keyword in java


We can create a String by use of new keyword in java. String class has
many constructors that take the characters in different forms and create the string.
We will discuss how we can create String by use of the constructor.

String: To create an object we use the String class.


nameOfObj: nameOfObj is the name of a variable that holds the object of String.
new: It is an operator that is used to call the constructor of the String class.
string(“groupOfCharacters”): It is a constructor that accepts the string
Example:

String name = new String();


String name = new String("Hi");
String obj = new String("123");
String obj1 = new String("Java Goal");

• Declaring string in java


syntax:

String s;
String name;
String obj;

• String initialization in Java


Example

String s;
String name;
String obj;
s = "Hi";
name = "JavaGoal";
obj = "Hello"
s = new String("Hi");
name = new String("JavaGoal");
obj = new String("Hello");

• String Methods in Java


1 string Length Method This method returns the length of a string in Java.

Example:

public class Sample_String {

public static void main(String[] args) {

//declare the String as an object S1 S2

String S1 = "Hello Java String Method";

String S2 = "RockStar";

//length() method of String returns the length of a String S1.

int length = S1.length();

System.out.println("Length of a String is: " + length);

//8 Length of a String RockStar

System.out.println("Length of a String is: " + S2.length());

2. indexOf() Method is used to get index of the first occurrence of a criteria specified

in the parameters of the IndexOf method.

Example

public class Sample_String {

public static void main(String args[]) {

String str_Sample = "This is Index of Example";


//Character at position

System.out.println("Index of character 'x': " + str_Sample.indexOf('x'));

//Character at position after given index value

System.out.println("Index of character 's' after 3 index: " +

str_Sample.indexOf('s', 3));

//Give index position for the given substring

System.out.println("Index of substring 'is': " + str_Sample.indexOf("is"));

//Give index position for the given substring and start index

System.out.println("Index of substring 'is' form 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

length minus 1 (n-1).

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);
}
}

4. compareTo() is used for comparing two strings lexicographically. Each character


of both strings are converted into a Unicode value. However, if both the strings are
equal, then this method returns 0 else it only result either negative or positive value.
Example:
public class Sample_String {
public static void main(String[] args) {

String str_Sample = "a";


System.out.println("Compare To 'a' b is : " + str_Sample.compareTo("b"));
str_Sample = "b";
System.out.println("Compare To 'b' a is : " + str_Sample.compareTo("a"));
str_Sample = "b";
System.out.println("Compare To 'b' b is : " + str_Sample.compareTo("b"));
}

5. Java String replace() method replaces every occurrence of a given character


with a new character and returns a new string. The Java replace() string method
allows the replacement of a sequence of character values.
Example:
public class Demo {
public static void main(String args[]) {
String S1 = new String("the quick fox jumped");
System.out.println("Original String is ': " + S1);
System.out.println("String after replacing 'fox' with 'dog': " + S1.replace("fox",
"dog"));
System.out.println("String after replacing all 't' with 'a': " + S1.replace('t', 'a'));

}
}

6. tolowercase() method converts every character of the particular string into


the lower case by using the rules of the default locale.
Example:
public class Demo {
public static void main(String args[]) {
String S1 = new String("UPPERCASE CONVERTED TO LOWERCASE");
//Convert to LowerCase
System.out.println(S1.toLowerCase());

}
}

7. toUppercase() method is used to convert all the characters in a given string to


upper case.

Example:

public class Demo {

public static void main(String args[]) {


String S1 = new String("lowercase converted to uppercase");

//Convert to UpperCase

System.out.println(S1.toUpperCase());

• Methods of Java String

Besides those mentioned above, there are various string methods present in Java.
Here are some of those methods:
Methods Description

join() join the given strings using the delimiter

replaces the specified old character with the


replace()
specified new character

replaces all substrings matching the regex


replaceAll()
pattern

replaceFirst() replace the first matching substring

returns the character present in the specified


charAt()
location

getBytes() converts the string to an array of bytes

returns the position of the specified character in


indexOf()
the string

compareTo() compares two strings in the dictionary order

compareToIgnoreCase() compares two strings ignoring case differences

trim() removes any leading and trailing whitespaces

format() returns a formatted string


split() breaks the string into an array of strings

toLowerCase() converts the string to lowercase

toUpperCase() converts the string to uppercase

returns the string representation of the specified


valueOf()
argument

toCharArray() converts the string to a char array

• String Buffer in java


In java String class is used to create the immutable string in java. We can perform
different operations on the string by using methods.
The string created by the String class is always immutable in java and We have
learned the methods on the immutable string
The StringBuffer class provides a way to create a string in java.
StringBuffer class exists in java.lang package. Serializable, Comparable, and
CharSequence are three interfaces that are implemented by the StringBuffer class.

to create a string by String Buffer

public class StringBufferExample


{
public static void main(String args[])
{
StringBuffer str = new StringBuffer();
System.out.println("Is it blank string: "+ (str.length() == 0));

str.append("Hello");
System.out.println("Value after append: "+str);
}
}

Important constructors

6. StringBuffer(): This constructor creates an empty string with an initial


capacity of 16.
2. StringBuffer(String str): This constructor creates a string buffer object
with some specified value.
3. StringBuffer(int capacity): This constructor creates an empty buffer with a
specified capacity.
• Important methods of String Buffer
1. append() method: This method is used to append the given text in a string.

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);
}
}

3. replace(startIndex, endIndex, string) method: This method is used to


replace the string by given text. The replace() replaces the given string from
the specified startIndex and endIndex.
Example:
class ExampleOfStringBuffer
{
public static void main(String args[])
{
// creating a StringBuffer with specified string
StringBuffer name = new StringBuffer("Ravi kant");
name.replace(5, 7, "OK");
System.out.println("Name of Student = "+ name);
}
}

• Difference between String and StringBuffer in java

String StringBuffer

When we create a String by


using of String class, it creates
The StringBuffer class creates an
an immutable string. It means
object of mutable string. It means we
we can’t change/modify it. If we
1. can change/modify it and JVM doesn’t
modify the string, JVM creates a
create a new object of string. You can
new object of the string. You can
read the mutable string in java.
read why string is immutable
in java.

The String class is slower


than StringBuffer. The It is faster than the String class. The
performance of the String class performance is faster than String.
2.
is slow than StringBuffer. Let’s Let’s see the example of
see the example of performance comparison.
performance comparison.

String consumes more memory StringBuffer consumes less memory


in heap memory because when than the string class because when
a user modifies any string it a user modifies any object of
3.
creates a new object of string. StringBuffer it doesn’t create a new
That degrades our performance object which improves the
and increases memory. performance also.

We can compare two strings by StringBuffer class doesn’t override


use of the equals() the equals method. If we compare
method because the string the string we need to convert it into
4. class overrides the equals() the Object of String class by use of
method. The equals() the toString() method. After
method returns a boolean conversion, we use the equal()
value. method.

The object of the String The object of the StringBuffer


class has a fixed length. The class is growable. When we modify
5. length of the string is initialized the string the length of an object
at the time of string creation. automatically grows.

The object of a String can be


The object of StringBuffer is stored
6. stored in String constant
in heap memory.
pool or heap memory.
Vectors in Java

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);

Advantages of Vector in Java

• 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.

Access Elements in Vector

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:

1. Vector(int initialCapacity, int Increment) – Constructs a vector with given


initialCapacity and its Increment in size.
2. Vector(int initialCapacity) – Constructs an empty vector with given
initialCapacity. In this case, Increment is zero.
3. Vector() – Constructs a default vector of capacity 10.
4. Vector(Collection c) – Constructs a vector with a given collection, the order
of the elements is same as returned by the collection’s iterator.

• Methods in Vector

1. Boolean add(Object o) – It appends an element at the end of the 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

System.out.println("The vector is " + v);


}
}

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) {

Vector v = new Vector(); // It creates a default vector

v.add(0,1); // Adds 1 at the index 0


v.add(1,"Java"); // Adds "Java" at the index 1
v.add(2,"is"); // Adds "is" at the index 2
v.add(3,"Fun"); // Adds "Fun" at the index 3
v.add(4,"!!!"); // Adds "Fun" at the index 4
System.out.println("The vector is " + v);
}
}

3. Boolean Remove(object o) – It removes remove the element at the given


index in the 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

System.out.println("Vector before removal " + v );


v.remove(1);
System.out.println("Vector after removal " + v );
}

4. Boolean removeElement(Object obj) – It deletes the element by its name


obj (not by index number)

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

System.out.println("Vector before removal " + v );


v.removeElement("Java");
System.out.println("Vector after removal " + v );
}

5. Int Capacity() – It returns the capacity of the 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(0,1); // Adds 1 at the index 0


v.add(1,"Java"); // Adds "Java" at the index 1
v.add(2,"is"); // Adds "is" at the index 2
v.add(3,"Fun"); // Adds "Fun" at the index 3

System.out.println("The vector capacity is " + v.capacity());


}

}
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) {

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

System.out.println("The element at index 1 is " + v.get(1));


}
}
7. Object firstElement() – It returns the first element
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

System.out.println("The first element is " + v.firstElement());


}

8. Object lastElement() – It returns the last element


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
System.out.println("The last element is " + v.lastElement());
}
}
• Vector Implementation
The following Java program demonstrates the usage of all the constructor
methods described above.

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);
}
}

Differences between a Vector and an Array.

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.

It provides a size() method to determine the size. Provides length property to


determine the length.
No concept dimensions but can be created as a Arrays support dimensions.
vector of vectors, normally called 2d vector.

Vector is synchronized. The array is not synchronized.


Vector is slower than the array. Array is faster.
Vector Array
Reserves additional storage when capacity is Does not reserve any additional
incremented. storage.
Ensures type safety by supporting generics. No generic support.

Java Wrapper Class


Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as
objects.The table below shows the primitive type and the equivalent wrapper class:
Primitive Data Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

char Character

Convert Primitive Type to Wrapper Objects


The automatic conversion of primitive data types into its equivalent Wrapper type is

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);
}
}

Wrapper Objects into Primitive Types


The automatic conversion of wrapper class type into corresponding primitive
type, is known as Unboxing.

Example:

class UnboxingExample1
{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;

System.out.println(a);
}
}

Java Command line argument


• The command line argument is the argument that passed to a program during
runtime. It is the way to pass argument to the main method in Java. These
arguments store into the String type args parameter which is main method
parameter.
• To access these arguments, you can simply traverse the args parameter in
the loop or use direct index value because args is an array of type String.
• Command Line Arguments can be used to specify configuration information
while launching your application.
• There is no restriction on the number of java command line arguments.You
can specify any number of arguments
• Information is passed as Strings.
• They are captured into the String args of your main method

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.

java HelloWorld arg1 arg2 ...

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]);
}
}
}

Garbage Collection in Java


• Garbage Collection in Java is a process by which the programs perform
memory management automatically.
• The Garbage Collector(GC) finds the unused objects and deletes them to
reclaim the memory.
• In Java, dynamic memory allocation of objects is achieved using the new
operator that uses some memory and the memory remains allocated until
there are references for the use of the object.
• When there are no references to an object, it is assumed to be no longer
needed, and the memory, occupied by the object can be reclaimed.
• There is no explicit need to destroy an object as Java handles the de-
allocation automatically.
• The technique that accomplishes this is known as Garbage Collection.
Programs that do not de-allocate memory can eventually crash when there is
no memory left in the system to allocate. These programs are said to
have memory leaks.
• Garbage collection in Java happens automatically during the lifetime of the
program, eliminating the need to de-allocate memory and thereby avoiding
memory leaks.
• All objects are created in Heap Section of memory.

You might also like