For Enquiry: 93450 45466

String Arrays In Java


 
In this blog, we will dive deep into understanding string arrays in java with this table of content…
String Arrays in Java
Declaring A String Array In Java
Initializing String Array In Java
Size Of A String Array
Iterating In A String Array
Searching Through A String Array
Sorting A String Array
Converting String Array To A String
Converting String Array To A List
Converting String Array To A Set
Converting List To A String Array
So let us start with understanding What are String Arrays In Java.

String Arrays in Java

We know that arrays in java are lists or collections of elements, strings in java behave similarly to arrays. They are character arrays and immutable, that is their size cannot be changed once defined. The characters are stored at contiguous memory locations just like arrays. Different operations such as searching for a character, sorting the string, splitting the string, or converting a string array as string iterating through characters, etc, can be performed on string arrays.

The main method public static void main(String[] args) ย of core java takes string arrays as arguments.

Let us see how to implement string arrays in java. Make sure you have java installed for implementation.

Declaring String Array in Java

String array can be declared in 2 ways,
By mentioning the size of the string array
Without mentioning the size of the string array
// example program for declaring string Arrays in Java

import java.util.*;

class Main {

public static void main(String[] args) {

String[] strArr_1; // declaring without size

String[] strArr_2 = new String[2]; // declaring with size

}

}

If you print the array elements, you will get a null value for the size number of times, which is once for the first string array and twice for the second string array.

After learning how to declare String Arrays in Java, let us now learn how to Initialise String Arrays in Java.

Initialising String Array in Java

A string array can be initialised in 2ways;
Inline string initialisation
Initialisation after declaration
Example program for string array initialisation
// example program for initialising string arrays in java

import java.util.*;

class Main {

public static void main(String[] args) {

// inline initialization

String[] strArr_1 = new String[] { "A", "E", "I", "O", "U" };

String[] strArr_2 = { "A", "E", "I", "O", "U" };

 

// initialization after declaration

String[] strArr_4 = new String[5];

strArr_4[0] = "A";

strArr_4[1] = "E";

strArr_4[2] = "I";

strArr_4[3] = "O";

strArr_4[4] = "U";

}

}
After learning how to initialise String Arrays in Java, let us now learn how to access String Arrays in Java.

Accessing characters from the string array

Just like elements can be accessed from an array using an index, characters can also be accessed with the index or position of the character in the string array.

Here is an example program for accessing characters from a string array

// example program for accessing characters from the string array

import java.util.*;

class Main {

public static void main(String[] args) {

// inline initialization

String[] strArr_1 = new String[] { "A", "E", "I", "O", "U" };

String[] strArr_2 = { "A", "E", "I", "O", "U" };

System.out.println(strArr_1[0]); // first char from strArr_1

System.out.println(strArr_2[3]); // fourth char from strArr_2

System.out.println(strArr_1[4]);// last char from strArr_1

}

}
Output for the above program

A

O

U

Here the strArr[0] is the first element in the array and strArr[4] is the last element in the array, which is also one less than the size of the array because the indexing starts at zero.

If you try to access strArr[5] or at any other index which is not present in the string array, it will throw at you an exception error of java.lang.ArrayIndexOutOfBoundsException

Check out this Complete Java Online Course by FITA Academy. FITA provides a complete Java course including core java and advanced java J2EE, and SOA training, where you will be building real-time applications using Servlets, Hibernate Framework, and Spring with Aspect Oriented Programming (AOP) architecture, Struts through JDBC bundled with, placement support, and certification at an affordable price with an active placement cell,by expert software developers with over 10 years of experience in the field to make you an industry required certified java developer.

After learning how to access String Arrays in Java, let us now learn how to find the size of String Arrays in Java.

Size of String Array

The size of the string array is the number of elements or characters in the array, irrespective of the index of the last element. Well, the size or the length of an array or string array can be found using the length variable in java. For Example

// example program for finding the size of the string Array

import java.util.*;

class Main {

public static void main(String[] args) {

// Initializing string arrays

String[] strArr_1 = new String[] { "A", "E", "I", "O", "U" };

String[] strArr_2 = { "F","I","T","A"};

 

// printing length of the string using length variable

System.out.println(strArr_1.length);

System.out.println(strArr_2.length);

}

}
Output for the above program
5

4
After learning how to find the size of the String Arrays in Java, let us now learn how to traverse through String Array in Java.

Traversing String Array

We can iterate through the string array and get each element at a time using a for loop, or for each loop.
Using for loop
// example program for traversing through the string Array using for loop

import java.util.*;

class Main {

public static void main(String[] args) {

String[] strarr_1 = { "F", "I", "T", "A" };

String[] strarr_2 = { "FITA", "Academy" };

 

//iterating through all the characters in the array using for loop

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

System.out.println(strarr_1[i]);

}

System.out.println();

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

System.out.print(strarr_2[i]+" ");

}

}

}
Output for the above program

F

I

T

A

 

FITA Academy
Using the for-each loop
// example program for finding the size of the string Array using for each loop

import java.util.*;

class Main {

public static void main(String[] args) {

String[] strArr_1 = { "F", "I", "T", "A" };

String[] strArr_2 =new String[] { "FITA", "Academy" };

 

// iterating through all the characters in the array using foreach

for (String str : strArr_1) {

System.out.print(str+" ");

}

System.out.println();

for (String str : strArr_2) {

System.out.print(str+" ");

}

}

}
Output for the above program
F I T A

FITA Academy
After learning how to traverse through String Arrays in Java, let us now learn how to search for a value from String Array in Java.

Searching for a value in String Array

We can search for a value in a string by looping over each element and comparing it with the value, this method will return the index of the first found match in the array, For example,

// example program for searching for a value from the string Array

import java.util.*;

 

public class Main {

public static void main(String[] args) {

String[] strArr = { "F", "I", "T", "A", "a", "c", "a", "d", "emy" };

Scanner scn = new Scanner(System.in);

boolean found = false;

int index = 0;

System.out.print("Find the index of ");

String str = scn.nextLine();

len = strArr.length

int pos = 0;

for (int pos; len> pos; pos++) {

if (str.equals(strArr[pos])) {

index = pos;

found = true;

break;

}

}

if (found)

System.out.print( " foundโ€+str + in the string array at the index:"+ index);

else

System.out.print("Could not find " + str + "in the string array, str");

scn.close();

}

}
Output for the above program
Find the index of A

A found at the index: 3

 

Find the index of a

a found at the index: 4
After learning how to search for a value from theย  String Arrays in Java, let us now learn how to convert String Array to a String in Java.

Converting string array to a string

The toString() method can be used on arrays to convert string array to string. Here is an example program
// example program for converting string Array to a string using toString method

import java.util.*;

public class Main {

public static void main(String[] args) {

String[] strArr = { "F", "I", "T", "A", "a", "c", "a", "d", "emy" };

String theString = Arrays.toString(strArr);

System.out.println(theString);

}

}
Output for the above program
[F, I, T, A, a, c, a, d, emy]
or using the StringBuilder class, we can pass a custom delimiter, For instance,
// example program for converting string Array to a string using StringBuilder class

import java.util.*;

public class Main {

public static void main(String[] args) {

String[] strArr = { "F", "I", "T", "A", "a", "c", "a", "d", "emy" };

String delimiter = " ";

StringBuilder sb = new StringBuilder();

for (String ch : strArr) {

if (sb.length() > 0) {

sb.append(delimiter);

}

sb.append(ch);

}

String theString = sb.toString();

System.out.println(theString);

 

}

}
Output for the above program
F I T A a c a d emy
After learning how to convert String Array to a String in Java, let us now learn how to sort a String Array in Java.

Sorting an array

We can arrange the string array alphabetically using the sort() method on the array.
// example program for sorting the string Array

import java.util.*;

 

public class Main {

public static void main(String[] args) {

String[] strArr = { "F", "I", "T", "A", "a", "c", "a", "d", "emy" };

System.out.println("Initial string array: " + Arrays.toString(strArr));

Arrays.sort(strArr);

System.out.println("sorted string array: " + Arrays.toString(strArr));

 

}

}
Output for the above program

Initial string array: [F, I, T, A, a, c, a, d, emy]

string array after sorting: [A, F, I, T, a, a, c, d, emy]
After learning how to sort a String Array in Java, let us now learn how to convert a String Array to a List in Java.

Converting A String Array To A List

Unlike arrays, a list is mutable, and its size can be changed. We can change the array to list using the asList() method. Here is an example for converting a string to list

// example program for converting string arrays to a list using asList method

import java.util.*;

public class Main {

public static void main(String[] args) {

String[] strArr = { "F", "I", "T","A" };

List<String> strLst = Arrays.asList(strArr);

System.out.print(strLst); // outputs [F,I,T,A]

}

}
Now to add more elements to the list, we will need to convert string array to an array list using ArrayList.Hereโ€™s how you would add elements to list,

// example program for finding the size of the string Array using ArrayList

import java.util.*;

 

public class Main {

public static void main(String[] args) {

String[] strArr = { "F", "I", "T","A" };

List<String> fxdLst = Arrays.asList(strArr);

List<String> strLst = new ArrayList<String>(fxdLst);

strLst.add("Academy");

System.out.print(strLst);

}

}
Output for the above program
[F, I, T, A, Academy]
After learning how to convert String Array to a List in Java, let us now learn how to convert a String Array to a set in Java.

Converting String Array To A Set

A set is a data structure and an unordered collection of elements just like an array or list, except that it cannot contain duplicate elements. Letโ€™s convert our previous array to a set using the HashSet class. Example program to demonstrate string set

// example program for converting string Array to a set

import java.util.*;

 

public class Main {

public static void main(String[] args) {

String[] strArr = { "F", "I", "T", "A","a","c","a","d","emy" };

List<String> strLst = Arrays.asList(strArr);

Set<String> strSt = new HashSet<String>(strLst);

System.out.println("Size of list: " + strLst.size());

System.out.println("Size of the set is: " + strSt.size());

System.out.print(strSt);

}

}
Output for the above program
The size of the original list is: 9

The size of the set is: 8

[emy, A, a, c, T, d, F, I]
After learning how to convert String Array to a set in Java, let us now learn how to convert List to a String Array in Java.

Converting List To A String Array

We have covered most of the operations on string arrays and now for the final one, we will convert a list to the string using the toArray() method. Here is how with an example,
// example program for converting List to a String Array

import java.util.*;

 

public class Main {

public static void main(String[] args) {

//String[] strArr = { "F", "I", "T", "A", "a", "c", "a", "d", "emy" };

List<String> strLst = new ArrayList<String>();

strLst.add("F");

strLst.add("I");

strLst.add("T");

strLst.add("A");

strLst.add("Academy");

String[] strArr = strLst.toArray(new String[] {});

for (String ch : strArr) {

System.out.println(ch+" ");

}

}

}
Output for the above program
F

I

T

A

Academy

There are many more string methods available, and I would recommend you to practice these problems on strings in java.

This was all about strings, arrays, and string arrays in java along with practice programs. To get in-depth knowledge of core Java and advanced java, J2EEย  SOA training along with its various applications and real-time projects using Servlets, Spring with Aspect-Oriented Programming (AOP) architecture, Hibernate Framework, and Struts through JDBC you can enroll in Certified Java Training in Chennai or Certified Java Training in Bangalore by FITA or a virtual class for this course,at an affordable price, bundled with real-time projects, certification, support, and career guidance assistance and an active placement cell, to make you an industry required certified java developer.

FITAโ€™s courses training is delivered by professional experts who have worked in the software development and testing industry for a minimum of 10+ years, and have experience of working with different software frameworks and software testing designs.

ย 





Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai, Bangalore & Online

  93450 45466

Coimbatore

 95978 88270

Pondicherry

93635 21112

Madurai

97900 94102

Tirupur

99401 22502

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


FITA Academy Branches

Chennai

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office
& Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy - Pallikaranai
335A, 13th Main Rd,
Ram Nagar South Extn,
Pallikaranai, Chennai,
Tamil Nadu 600100

    :   93450 45466

Bangalore

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

Coimbatore

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

Other Locations

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

FITA Academy - Tiruppur
61D, Poongodi Towers 2nd floor,
Periyar Colony Bus Stop,
Tirupur - 641 652

    :   9940122502

Read More Read less
  • Are You Located in Any of these Areas

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!