Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Uint-I(Array,String,Vector) (Autosaved)

The document provides an overview of arrays in Java, detailing their properties, types (single-dimensional and multi-dimensional), and methods for declaration, creation, and manipulation. It also discusses the Java Arrays class, which includes various static methods for sorting, searching, and comparing arrays. Additionally, the document covers the String class in Java, highlighting its immutability, constructors, and methods for string manipulation.

Uploaded by

poojalandge1295
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Uint-I(Array,String,Vector) (Autosaved)

The document provides an overview of arrays in Java, detailing their properties, types (single-dimensional and multi-dimensional), and methods for declaration, creation, and manipulation. It also discusses the Java Arrays class, which includes various static methods for sorting, searching, and comparing arrays. Additionally, the document covers the String class in Java, highlighting its immutability, constructors, and methods for string manipulation.

Uploaded by

poojalandge1295
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Java Array

An Array, one of the data structures in Java, is a collection of variables of the same type that are
referenced by a common name. Arrays consist of contiguous memory locations. The first address
of the array belongs to the first element and the last address to the last element of the array.

 Arrays can have data items of simple types such as int or float, or even user-defined data
types like structures and objects.
 Arrays are considered as objects in Java.
 The indexing of the variable in an array starts from 0.
 Like other variables in Java, an array must be defined before it can be used to store
information.
 We can find the length of arrays using the member ‘length’.
 The size of an array must be an int value.
 Object class is a super class of the Array.
 Array implements the two interfaces: Serializable and Cloneable.
The need for an Array:-
Arrays are very useful in cases where many elements of the same data types need to be stored
and processed. It is also useful in real-time projects to collect the same type of objects and send
all the values with a single method call.

Types of Java Arrays


1. Single dimensional arrays/one-dimensional array – comprised of finite homogeneous
elements.

2. Multi-dimensional arrays – comprised of elements, each of which is itself an array.

1. Single Dimensional Arrays

A single-dimensional array in Java is a linear collection of elements of the same data type.

1. Array Declaration
To declare an array in Java, use the following syntax:
type[] arrayName; or type[] arrayName;
 type: The data type of the array elements (e.g., int, String).
 arrayName: The name of the array.
Note: The array is not yet initialized.

2. Create an Array

To create an array, you need to allocate memory for it using the new keyword:
// Creating an array of 5 integers
numbers = new int[5];

3. Access an Element of an Array

We can access array elements using their index, which starts from 0:

// Setting the first element of the array


numbers[0] = 10;

// Accessing the first element


int firstElement = numbers[0];

The first line sets the value of the first element to 10. The second line retrieves the value of the
first element.

4. Change an Array Element

To change an element, assign a new value to a specific index:

// Changing the first element to 20


numbers[0] = 20;

5. Array Length

We can get the length of an array using the length property:

// Getting the length of the array


int length = numbers.length;

Array Properties
 In Java, all arrays are dynamically allocated.

 Arrays may be stored in contiguous memory [consecutive memory locations].

 Since arrays are objects in Java, we can find their length using the object property length.
This is different from C/C++, where we find length using size of.

 A Java array variable can also be declared like other variables with [] after the data type.

 The variables in the array are ordered, and each has an index beginning with 0.

 Java array can also be used as a static field, a local variable, or a method parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a
class, depending on the definition of the array. In the case of primitive data types, the actual
values might be stored in contiguous memory locations (JVM does not guarantee this behavior).
In the case of class objects, the actual objects are stored in a heap segment.

Array Literal in Java

In a situation where the size of the array and variables of the array are already known, array
literals can be used.

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

 The length of this array determines the length of the created array.

 There is no need to write the new int[] part in the latest versions of Java.

Accessing Java Array Elements using for Loop

Now , we have created an Array with or without the values stored in it. Access becomes an
important part to operate over the values mentioned within the array indexes using the points
mentioned below:

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

Let us check the syntax of basic for loop to traverse an array:

// Accessing the elements of the specified array


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

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

// declares an Array of integers.

int[] arr;

// allocating memory for 5 integers.

arr = new int[5];

// initialize the elements of the array

// first to last(fifth) element

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

// accessing the elements of the specified array

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

System.out.println("Element at index "

+ i + " : " + arr[i]);

Output:-

Element at index 0 : 10

Element at index 1 : 20
Element at index 2 : 30

Element at index 3 : 40

Element at index 4 : 50

Passing Array to a Method in Java


We can pass the Java array to the method so that we can reuse the same logic on any
array. When we pass an array to a method in Java, we are essentially passing a reference
to the array. It means that the method will have access to the same array data as the calling
code, and any modifications made to the array within the method will affect the original
array.

class Small {

//creating a method which receives an array as a parameter

static void min(int arr[]){

int min=arr[0];

for(int i=1;i<arr.length;i++)

if(min>arr[i])

min=arr[i];

System.out.println(min);

public static void main(String args[]){

int a[]={33,3,4,5,67,2,76,0,1};//declaring and initializing an array

System.out.println("Minimun Element in array: ");//passing array to method

min(a);

}}

Output:- Minimun Element in array:

0
Memory Representation of single-dimensional
arrays
Single-dimensional arrays are lists of data of the same type and their
elements are stored in a contiguous memory location in their index order. For
instance, an array age of type int with 5 elements is declared as:

int age[ ] = new int[5 ];

Or as,

int[ ] age = new int[5 ];

This array will have age[0] at the first allocated memory location, age[1] at the
next memory location and so on. Since age is an int type array, the size of
each element is 4 bytes. If the starting memory location of array age is 5000,
then it will be represented in the memory location as follows:

Ar
rayIndexOutOfBoundsException
In Java, the ArrayIndexOutOfBoundsException is a runtime exception thrown by the Java
Virtual Machine (JVM) when attempting to access an invalid index of an array. This
exception occurs if the index is negative, equal to the size of the array, or greater than the
size of the array while traversing the array.
Output:-

2. Multi-dimensional arrays

Multi-dimensional arrays are arrays of arrays in which each element of the array holds the
reference of other arrays. We can also call them Jagged Arrays. A multidimensional array in
Java is an array of arrays where each element can be an array itself. It is useful for storing
data in row and column format.

For example, a two-dimensional array myArray [ M ][ N ] is an M by N table with M rows and


N columns containing M N elements.

Syntax of declaring two-dimensional arrays is:


type array-name [ ][ ]= new type[number of rows] [number of columns];
or
type [ ][ ] array-name = new type[number of rows] [number of columns];

Example:-

int myArray [ ] [ ] = new int [5] [12] ; or

int[ ] [ ] myArray = new int[5] [12] ;

The array myArray has 5 elements myArray [0], myArray[1], myArray[3], and myArray[4], each of
which itself is an int array with 12 elements.

The elements of myArray can be referred to as myArray[0][0], myArray[0][1], myArray[0][2],


…….., myArray[0][12], myArray [1][0], ……. and so forth.

class TwoD{

public static void main(String args[]){

int[][] myArray = new int[3][3];

myArray[0][0]=1;

myArray[0][1]=2;

myArray[0][2]=3;

myArray[1][0]=4;

myArray[1][1]=5;

myArray[1][2]=6;

myArray[2][0]=7;

myArray[2][1]=8;

myArray[2][2]=9;

//printing a two-dimensional array

for(int i=0;i<3;i++)

for(int j=0;j<3;j++)

System.out.print(myArray[i][j]+" ");
}

System.out.println();

}}

Output:-

123

456

789

Example of Multiplication Table using 2 d Array:-

public class TwoD {

public static void main(String[] args) {

int rows=11;
int cols=11;
int product[][]=new int[rows][cols];
System.out.println("Multiplication Table");
System.out.println();
int i,j;
for(i=1;i<rows;i++)
{
for(j=1;j<cols;j++)
{
product[i][j]=i*j;
System.out.print("\t "+product[i][j]);
}

System.out.println(" ");
}
}
}
Output:-

Multiplication Table

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

The Arrays Class


The java.util.Arrays class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements. These methods are overloaded for all primitive
types.

 int compare(array1, array2)


This method compares two arrays in lexicographic order. We pass two arrays as parameters to its
methods. It returns 1 if array1 is greater than array2, -1 if array1 is smaller than array2, and a 0 if
both arrays are equal to each other.
 boolean equals(array1, array2)
This method checks whether both the arrays are equal or not and gives the result either as true or
false.
 int binarySearch(array [], value)
With the help of this method, we can find or search a specified value inside an array which is
given as the first argument. As a result, this method returns the index of the element in the array.
The array must be sorted for this search. If the element is not found, it returns a negative value.

 copyOf(originalArray, newLength)
We can copy the specified array to a new array with a specified length. The left spaces are
assigned to default values in the new array.
 sort(originalArray)
Sorts the complete array in ascending order.
 toString (original array):-It returns a string representation of the contents
of this array.
Java String
 Basically, string is a sequence of characters but it’s not a primitive type.

 When we create a string in java, it actually creates an object of type String.

 String is immutable object which means that it cannot be changed once it is created.

 String is the only class where operator overloading is supported in java. We can concat
two strings using + operator. For example "a"+"b"="ab".

 Java provides two useful classes for String manipulation


- StringBuffer and StringBuilder.

 Java String class is defined in java.lang.String package.

example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.

Working with Strings in Java


Strings are a group of characters. In Java, you can work with the character data that is, a
single character or a group of characters (Strings) in 4 different ways:

Character Class

It is a wrapper class whose objects hold single character data.

String Class

It is a class whose instances or objects can hold the unchanging or constant string (immutable
String).

StringBuffer Class

Its instances or objects can hold mutable strings that can be changed or modified.

StringBuilder Class

Java StringBuilder class is similar to the StringBuffer class which holds a sequence of
mutable Strings but is more versatile than StringBuffer class because it provides more
modification features.
How to create a string object?
There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

String s="welcome";

By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
Example: Create a String in Java
String Length
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number
of characters contained in the string object.

Constructors of String Class


Constructor Description
String() creates an empty string.
String(String original) creates a string object from another string
String(byte[] bytes): constructs a new string from the byte array using
system default encoding.
String(byte bytes[], int offset, he offset specifies the index of the first byte to
int length): decode. The length specifies the number of bytes to
decode. This constructor
throws IndexOutOfBoundsException if offset is
negative, length is negative, or offset is greater
than bytes.length - length.
String(char value[]): creates the string object from the character array.
String(char value[], int offset, The offset specifies the index of the first character.
int count): The length specifies the number of characters to
use. This constructor
throws IndexOutOfBoundsException if offset is
negative, length is negative, or offset is greater
than value.length - length.
String(StringBuffer buffer) creates a new string from the contents of the string
buffer. This constructor internally calls
StringBuffer toString() method.
String(StringBuilder buffer): creates a new string from the contents of the string
builder.

Methods of String Class:-


sr.no Syntax Description Method
.
1 stringname.length() return length of string s1.length()
2 char charAt(int index) return a character value at s1.charAt(index)
aspecified position (index)
of string
3 String toUpperCase() convert a string into s1.toUpperCase()
Uppercase
4 String toLowerCase() convert a string into s1.toLowerCase()
Lowercase
5 String replace(char replace all apperence of s1.replace(‘x’,’y’)
‘x’,char ‘y’) ‘x’,’y’
6 Boolean equals(String s2) Returns true if invoking s1.equals(s2)
string is equal to string s2
7 s1.equalsIgnoreCase(s2) return true if invoking string
is equal to string s1.equalsIgnoreCase(s2)
s2,ignoring the case of
characters.
8 String concat(String s2) give concatenation of s1.concat(s2)
s1&s2
9 int compareTo(String return an integer value s1.compareTo(s2)
s1,String s2) -ve if s1<s2
+ve if s1>s2
0 if s1=s2
10 String trim() remove whitespaces at s1.trim()
beginning and end of
string(it does not affect
whitespaces in the middle
of the string)
11 String substring(int n) gives substring starting s1. substring(n)
from nth index
12 String substring(int n,int gives substring starting s1.ubstring(n,m)
m) from nth index upto mth -1
13 int indexOf(char ‘x’) gives the position of 1st s1.indexOf(‘x’)
occurrence of ‘x’ in string
s1
14 int indexOf(char ‘x’,int n) gives the position of ‘x’ that s1.indexOf(‘x’,n)
occur after nth position in
string s1
Example:-
class Main {

public static void main(String[] args) {

String s1="Welcome to Java Programming";//string created using literals

String s2=new String("SY ALML Students");//string created using new keyword

String s3=" Java Programming.. ";

System.out.println("String s1 length:- "+s1.length());

System.out.println("String s2 length:- "+s2.length());

System.out.println("String s1== s2:- "+s1.equals(s2));

System.out.println("String s1== s2(ignoreCase):- "+s1.equalsIgnoreCase(s2));

System.out.println("s1+s2:- "+s1.concat(s2));

System.out.println("CharAt position 4th:- "+s1.charAt(14));

System.out.println("Substring of s1 is:- "+s1.substring(6));

System.out.println("Index of char 'r' in string s1 is:- "+s1.indexOf('r'));

System.out.println("Index of char 'r' after nth position in string s1 is:-


"+s1.indexOf('r',7));

System.out.println("String s1 Compare to s3:- "+s1.compareTo(s3));

System.out.println("Char java replace by python:- "+s3.replace("java","python"));

System.out.println("String s1 in Lowercase:- "+s1.toLowerCase());

System.out.println("String s2 in Uppercase:- "+s2.toUpperCase());

System.out.println("String s3 trim whitespaces:- "+s3.trim());

Output:-

String s1 length:- 27

String s2 length:- 16
String s1== s2:- false

String s1== s2(ignoreCase):- false

s1+s2:- Welcome to Java ProgrammingSY ALML Students

CharAt position 4th:- a

Substring of s1 is:- e to Java Programming

Index of char 'r' in string s1 is:- 17

Index of char 'r' after nth position in string s1 is:- 17

String s1 Compare to s3:- 55

Char java replace by python:- Java Programming..

String s1 in Lowercase:- welcome to java programming

String s2 in Uppercase:- SY ALML STUDENTS

String s3 trim whitespaces:- Java Programming..

String Buffer Class:-


 StringBuffer in Java is used to create modifiable strings i.e. it doesn’t have a fixed length
like the String class in Java.
 The StringBuffer class has growable and writable character sequences. It is thread safe
i.e. multiple threads cannot simultaneously access the same method.
 The StringBuffer class in java is used for storing the mutable sequence of different
datatypes which means we can update the sequence of the StringBuffer class very easily
and efficiently without creating a new sequence in memory.
 Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.

Create a string using StringBuffer:

StringBuffer strBuff = new StringBuffer("dwa");


Method of String Buffer Class:-

srno Syntax Description Method


1
2
3
4
5
6
7
8
9
10

Vector:
What is Vector in Java?
 Vector is a data structure that is used to store a collection of elements. Elements can be
of all primitive types like int, float, Object, etc. Vectors are dynamic in nature and
accordingly, grow or shrink as per the requirement.
 Vector Class in Java is found in the java.util package.
 Vector class is a child class of the AbstractList class and implements the List interface.
Therefore we can use all the methods of the List interface.
 Vectors are known to give ConcurrentModificationException when accessed
concurrently at the time of modification.
 When a Vector is created, it has a certain capacity to store elements that can be defined
initially. This capacity is dynamic in nature and can be increased or decreased.
 By definition, Vectors are synchronized, which implies that at a time, only one thread is
able to access the code while other threads have to wait. Due to this, Vectors are slower
in performance as they acquire a lock on a thread.

List of constructors provided by the vector class.

Sr.n Constructor Description Example


o
1 Vector( ) This constructor creates a Vector v = new
default vector, which has an Vector();
initial size of 10.
2 Vector(int size) This constructor accepts an Vector v = new
or argument that equals to the Vector(50);
Vector(int Capacity) required size, and creates a
vector whose initial capacity is
specified by size.
3 Vector(int size, int This constructor creates a Vector v = new
incr) vector whose initial capacity is Vector(100,30);
specified by size and whose
increment is specified by incr.
The increment specifies the
number of elements to allocate
each time that a vector is
resized upward.
4 Vector(Collection c) This constructor creates a Vector v = new
vector that contains the Vector(myCollection);
elements of collection c.

Apart from the methods inherited from its parent classes, Vector
defines the following methods –

Srno Syntax Description Method


1 Vector add(Object item) add item to vector list.add(item)
2 Vector addElement(Object add the item into vector list.addElement(item)
item) at the end.
3 int size() Give the number of object in list.size()
vector
4 String elementAt(int n) Gives the name of the nth index list.elementAt(n)
object
5 Vector removeElement(Object Removes the specified item list.removeElement(item)
item) from vector list.
6 Vector removeElementAt(int Removes the item stored in the list.removeElementAt(n)
n) nth position
7 Vector removeAllElements () Remove all element in vector list.removeAllElements()
list
8 int capacity() Returns the current capacity of list.capacity();
vector.
9 Vector firstElement() Returns the first element of list.firstElement();
vector
10 Vector lastElement() Returns the last element of list.lastElement();
vector
11 Vector insertElementAt(Object Insert item in to vector at nth list.insertElementAt(item,n);
item,int n) index.
12 void clear() This method removes all of the list.clear();
elements from this vector.
13 Boolean contains(Object item) This method returns true if this list.contains(item)
vector contains the specified
element.
14 void copyInto(String array[]) This method copies the items list.copyInto(array)
of this vector into the specified
array.
15 void ensureCapacity() This method increases list.ensureCapacity()
the capacity of this
vector, if necessary, to
ensure that it can hold at
least the number of items
specified by the minimum
capacity argument.

You might also like