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

Arrays and Strings

An array is a collection of variables of the same type that are ordered and indexed. Java arrays can be one-dimensional or multidimensional. Arrays are declared with square brackets and can be initialized with or without values. Elements in an array are accessed using their index number. Common operations on arrays include iterating through elements with for loops and accessing properties like length. The String class in Java can also be used to represent arrays of characters.

Uploaded by

Darkseid Uxas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Arrays and Strings

An array is a collection of variables of the same type that are ordered and indexed. Java arrays can be one-dimensional or multidimensional. Arrays are declared with square brackets and can be initialized with or without values. Elements in an array are accessed using their index number. Common operations on arrays include iterating through elements with for loops and accessing properties like length. The String class in Java can also be used to represent arrays of characters.

Uploaded by

Darkseid Uxas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Array:

An array is a collection of variables of the same type. For instance, an


array of int is a collection of variables of the type  int. The variables in the
array are ordered and each have an index.
Declaring an Array Variable in Java
A Java array variable is declared just like you would declare a variable of the desired type, except
you add [] after the type. Here is a simple Java array declaration example:

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.

Type array name = {listof values};


int[] ints2 = { 1,2,3,4,5,6,7,8,9,10 }; ----This is called initialization of array.
It is the part inside the curly brackets that is called an array literal.

This style works for arrays of all primitive types, as well as arrays of strings. Here is a
string array example:

String[] strings = {"one", "two", "three"};


Accessing Java Array Elements

• Java Array Index


You can access elements of an array by using indices. Let's consider the
example.

int[] age = new int[5];


The first element of array is age[0], second is age[1] and so on.
If the length of an array is n, the last element will be arrayName[n-1]. Since the
length of age array is 5, the last element of the array is age[4] in the above example.
The default initial value of elements of an array is 0 for numeric types and false for
boolean. We can demonstrate this:

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:

int[] intArray = new int[10];


int arrayLength = intArray.length;

• 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];

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


stringArray[i] = "String no " + i;
}

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


System.out.println( stringArray[i] );
}
You can also iterate an array using the "for-each" loop in Java. Here is how that
looks:

int[] intArray = new int[10];

for( int theInt : intArray ) {


System.out.println(theInt);
}
The for-each loop gives you access to each element in the array, one at a time, but
gives you no information about the index of each element. Additionally, you only
have access to the value. You cannot change the value of the element at that
position. If you need that, use a normal for-loop as shown earlier.
For for-each loop also works with arrays of objects. Here is an example
showing you how to iterate an array of String objects:

String[] stringArray = {"one", "two", "three"};

for(String theString : stringArray) {


System.out.println(theString);
}
Multidimensional Java Arrays:
• You create a multidimensional array in Java by appending one set of
square brackets ([]) per dimension you want to add. Here is an
example that creates a two-dimensional array:

• int[][] intArray = new int[10][20];


Iterating Multidimensional Arrays
When you iterate a multidimensional array in Java you need to iterate
each dimension of the array separately. Here is is how iterating a
multidimensional looks in Java:

int[][] intArrays = new int[10][20];

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


for(int j=0; j < intArrays[i].length; j++){
System.out.println("i: " + i + ", j: " + j);
}
}
class MultidimensionalArray {
public static void main(String[] args) {

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

Declare String Array in Java with Initial Values


It is more common that we wish to declare a String Array with initial
values. For example, this is how we declare an array with initial
contents that have names of fruits:
String[] fruitArray = {"Apple", "Banana", "Orange", "Grapes"};
class example
{
public static void main(String args[])
{
String stringarray[]=new String[3];
stringarray[0]="hi";
stringarray[1]="hello";
stringarray[2]="how";
for(int i=0;i<stringarray.length;i++)
{
System.out.println(stringarray[i]);
}
}
}
Java String Example:

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Char to string conversion:

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:

public class Test {

public static void main(String args[]) {


String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
concat:

public class Test {


public static void main(String args[]) {
String s = "Strings are immutable";
s = s.concat(" all the time");
System.out.println(s);
}
}
copyValueOf
public class Test {

public static void main(String args[]) {


char[] Str1 = {‘G’,’I’,’T’,’A’,’M’};
String Str2 = "";
Str2 = Str2.copyValueOf( Str1 );
System.out.println("Returned String: " + Str2);
}
}
indexOf
import java.io.*;
public class Test {

public static void main(String args[]) {


String Str = new String("Welcome to Tutorialspoint.com");
String SubStr1 = new String("Tutorials");
System.out.println("Found Index :" + Str.indexOf( SubStr1 ));
}
}
String Buffer class:
• Java StringBuffer class is used to create mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is
mutable i.e. it can be changed.
Important Constructors of StringBuffer class
StringBuffer Constructors:
1)StringBuffer(): Creates a StringBuffer with empty content and 16 reserved characters by
default.
StringBuffer sb = new StringBuffer();

2)StringBuffer(int sizeOfBuffer): Creates a StringBuffer with the passed argument as the size of
the empty buffer.

StringBuffer sb = new StringBuffer(20);

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.

StringBuffer sb = new StringBuffer("Hello World!");


class example
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("ece");
sb.append("classses");
System.out.println("ece classes");
sb.insert(1,"hi");
System.out.println("the string is"+sb);
sb.replace(1,3,"class");
System.out.println("the string is"+sb);
sb.delete(3,4);
System.out.println("the string is"+sb);
sb.reverse();
System.out.println("the string is"+sb);
Mutability Difference:

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:

The difference between StringBuffer and StringBuilder is that StringBuffer is


thread-safe. So when the application needs to be run only in a single thread then it is
better to use StringBuilder. StringBuilder is more efficient than StringBuffer.
Situations:

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:

In JDK 5, Java has included a feature that simplifies the creation of


methods that need to take a variable number of arguments. This feature
is called varargs and it is short-form for variable-length arguments

Syntax of varargs :

A variable-length argument is specified by three


periods(…). For Example,

public static void fun(int ... a)


{
// method body
}
class Test1
{
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);
for (int i: a)
System.out.print(i + " ");
System.out.println();
}
public static void main(String args[])
{
fun(100)
fun(1, 2, 3, 4);
fun();
}
Vectors:

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

Creating generic integer ArrayList


ArrayList<Integer> arrli = new ArrayList<Integer>();
import java.io.*;
import java.util.*;

class arraylist
{
public static void main(String[] args)
throws IOException
{
// size of ArrayList
int n = 5;

//declaring ArrayList with initial size n


ArrayList<Integer> arrli = new ArrayList<Integer>(n);
// Appending the new element at the end of the list
for (int i=1; i<=n; i++)
arrli.add(i);

// 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:

Primitive Data Type & Wrapper Class


Java provides several primitive data types. These include int (integer values), char
(character), double (doubles/decimal values), and byte (single-byte values).
Sometimes the primitive data type isn't enough and we may actually have to work
with an integer object.

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.

Java Primitive Data Type Wrapper Class


int Integer
double Double
boolean Boolean
byte Byte
char Character
float Float
long Long
short Short

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;

ArrayList<Integer> arrayList = new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects


arrayList.add(25);

// printing the values from object


System.out.println(arrayList.get(0));
}
}
• Unboxing: It is just the reverse process of autoboxing. Automatically
converting an object of a wrapper class to its corresponding primitive
type is known as unboxing. For example – conversion of Integer to int,
Long to long, Double to double etc.

// Java program to demonstrate Unboxing


import java.util.ArrayList;

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

// unboxing because get method returns an Integer object


int num = arrayList.get(0);

// printing the values from primitive data types


System.out.println(num);
}
}
Output:
24
Basic I/O Streams: Scanner, buffered reader

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

// Print the values to check if input was correctly obtained.


System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
Java Buffered Reader class is used to read the text from a
character-based input stream. It can be used to read data line
by line by readLine() method. It makes the performance fast. It
inherits Readerclass.
import java.io.*;
public class Br
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome"+name);
}
}
Once we have the input data in a String object we can use the various methods available to a String
object to manipulate the data. Since data can get corrupted during an input operation the method
readLine() can alert the user by throwing an exception. There are several ways that Java allows a user
to handle exceptions. For the time being we will add the phrase "throws IOException" and let the
system to do the error handling.

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.

int num = Integer.parseInt ( inputString );

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.

double d = Double.parseDouble ( inputString );


To read from the console we must use a BufferedReader object. But the
BufferedReader class is in the package java.io and has to imported. The following
program snippet shows how to read and write to the console.
import java.io.*;
public class CalcArea
{
public static void main ( String args[] ) throws IOException
{
System.out.print ( "Enter the radius: " );
BufferedReader input = new BufferedReader ( new InputStreamReader
( System.in ) );
String inputString = input.readLine();
double radius = Double.parseDouble ( inputString );
double area = 3.14159 * radius * radius;
System.out.println ( "Area is: " + area );

You might also like