Arrays and Strings
Arrays and Strings
int[] intArray;
You actually have a choice about where to place the square brackets [] when you declare an array in
Java. The first location you have already seen. That is behind the name of the data type (e.g.
String[]). The second location is after the variable name. The following Java array declarations are
actually all valid:
int[] intArray;
int intArray[];
String[] stringArray;
String stringArray[];
• Java Array Literals
The Java programming language contains a shortcut for instantiating arrays of primitive
types and strings. If you already know what values to insert into the array, you can use an
array literal. Here is how how an array literal looks in Java code.
This style works for arrays of all primitive types, as well as arrays of strings. Here is a
string array example:
class ArrayExample {
public static void main(String[] args) {
int[] age = new int[5];
System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
}
}
• Array Length
You can access the length of an array via its length field. Here is an
example:
• Iterating Arrays
You can loop through all the elements of an array using the Java for
loop. Here is an example of iterating an array with a for loop in Java:
Example for iterating arrays:
String[] stringArray = new String[10];
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);
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
class example
{
public static void main(String args[])
{
int[][] arrInt = { { 1, 2 }, { 3, 4, 5 } };
for (int i = 0; i < arrInt.length; i++)
{
for (int j = 0; j < arrInt[i].length; j++)
{
System.out.print(arrInt[i][j] + " ");
}
System.out.println("");
}
}
}
Strings:
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:
char[] ch={‘w‘,’e’,’l’,’c’,’o’,’m’,’e’};
String s=new String(ch);
is same as:
String s=“welcome";
String arrays:
• Just like any other type of array, we can use the square brackets to
declare an array of String. There are two ways of doing this. The first
one is to use the square bracket after the variable name,
for example: String myArray[];
The other way of declaring String Array in Java is to place the square
brackets after the data type. For example:
String[] myArray;
The two declaration above will have the same effect.
String[] myArray= new String[3];
myArray[0] = "Cat";
myArray[1] = "Dog";
myArray[2] = "Elephant";
class example
{
public static void main(String args[])
{
char ch[]={'h',‘i'};
String s=new String(ch);
System.out.println(s);
}
}
Some basic examples for string metods:
CharAt:
2)StringBuffer(int sizeOfBuffer): Creates a StringBuffer with the passed argument as the size of
the empty buffer.
3)StringBuffer(String string): Creates a StringBuffer with the passed String as the initial content
of the buffer. 16 contingent memory characters are pre-allocated, not including the buffer, for
modification purposes.
String is immutable, if you try to alter their values, another object gets created,
whereas StringBuffer and StringBuilder are mutable so they can change their
values.
Thread-Safety Difference:
If your string is not going to change use a String class because a String
object is immutable.
If your string can change (example: lots of logic and operations in the
construction of the string) and will only be accessed from a single thread,
using a StringBuilder is good enough.
If your string can change, and will be accessed from multiple threads, use
a StringBuffer because StringBuffer is synchronous so you have thread-
safety.
Variable Arguments (Varargs) in Java:
Syntax of varargs :
• Eg Program:
import java.util.*;
Class languageVector
{
public static void main(String args[])
{
Vector list=new Vector();
Int length=args.length;
for(int i=0;i<length;i++)
{
list.addElement(args[i]);
}
list.insertElementAt(“COBOL”,2);
Int size=list.size();
String listArray=new String[size];
list.copyInto(listArray);
System.out.println(“List of languages”);
for(int i=0;i<size;i++)
{
System.out.println(listArray[i]);
}
}
}
ArrayList:
• ArrayList is a part of collection framework and is present in java.util
package. It provides us dynamic arrays in Java.
• ArrayList inherits AbstractList class and implements List interface.
• ArrayList is initialized by a size, however the size can increase if
collection grows or shrunk if objects are removed from the collection.
• Java ArrayList allows us to randomly access the list.
• ArrayList can not be used for primitive types, like int, char, etc. We
need a wrapper class for such cases (see this for details).
• ArrayList in Java can be seen as similar to vector in C++.
Constructors in Java ArrayList:
• ArrayList(): This constructor is used to build an empty array list
• ArrayList(Collection c): This constructor is used to build an array list
initialized with the elements from collection c
• ArrayList(int capacity): This constructor is used to build an array list
with initial capacity being specified.
class arraylist
{
public static void main(String[] args)
throws IOException
{
// size of ArrayList
int n = 5;
// Printing elements
System.out.println(arrli);
// Remove element at index 3
arrli.remove(3);
// Displaying ArrayList after deletion
System.out.println(arrli);
// Printing elements one by one
for (int i=0; i<arrli.size(); i++)
System.out.print(arrli.get(i)+" ");
}
}
Wrapper classes:
Let's first look at the wrapper classes. First, we'll list the Java primitive data type
and then we'll explain its wrapper class.
Notice that all wrapper classes start with a capital letter, such as Integer,
while the primitive data types are lowercase, such as int.
• Need of Wrapper Classes
• They convert primitive data types into objects. Objects are needed if
we wish to modify the arguments passed into a method (because
primitive types are passed by value).
• The classes in java.util package handles only objects and hence
wrapper classes help in this case also.
• Data structures in the Collection framework, such as ArrayList and
Vector, store only objects (reference types) and not primitive types.
• An object is needed to support synchronization in multithreading.
Autoboxing and Unboxing
Autoboxing: 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:
/ Java program to demonstrate Autoboxing
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
// Autoboxing- primitive to Character object conversion
Character a = ch;
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
// unboxing - Character object to primitive conversion
char a = ch;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(24);
Scanner class:
• Scanner is a class in java.util package used for obtaining the input of the primitive types like
int, double etc. and strings. It is the easiest way to read input in a Java program, though not
very efficient if you want an input method for scenarios where time is a constraint like in
competitive programming.
• To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream. We may pass an object of class File if we want to
read input from a file.
• To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can use nextShort()
• To read strings, we use nextLine().
• To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) funtion returns the first character in that
string.
import java.util.Scanner;
public class ScannerDemo1
{
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();
Reading an integer: One way to read an integer is to read the input as a String and then use the
method parseInt() of the wrapper class Integer to convert the String to an integer.
Reading a real number: There is a wrapper class java.lang.Double that can take the input as a String
and a method parseDouble() to convert the String to a real number.