Home
Aptitude
Categories


Home » Java programs » Java list programs

List of Strings example in Java



Here, we are going learn how to create a list of strings, how to add string to the list by talking input from the use, how to print the complete list of strings and how to print the string one by one using for each loop?
Submitted by IncludeHelp, on October 10, 2018

We have to read total number string i.e. "n", create a list of the Strings and input "n" strings, add then to print the all stings of the list in Java.

Declare a list of String implemented by ArrayList:

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

To input the total number of strings and to input string from the user, we are using in which is an object of scanner class.

The statement to read string and add to the list in the loop is:

    str_list.add(in.next());

Program:

import java.util.*;

public class ListExample {
	public static void main (String[] args) {
		//creating a list of integers
		List<String> str_list = new ArrayList<String>();
		int n;
		Scanner in = new Scanner (System.in);
		System.out.print ("Enter total number of strings: ");
		n = in.nextInt ();

		for (int i=0; i<n; i++){
			System.out.print ("Enter name "+(i+1) +": ");
			str_list.add(in.next ()) ;
		}

		//printing updated List
		System.out.println ("string list: " + str_list);
		//printing elements
		System.out.println ("List elements: ");
		for(String str: str_list){
			System.out.println (str); 
		}
	}
};

Output

Enter total number of strings: 5
Enter name 1: Delhi
Enter name 2: Noida
Enter name 3: Mumbai
Enter name 4: Gwalior
Enter name 5: Bhind
string list: [Delhi, Noida, Mumbai, Gwalior, Bhind]
List elements:
Delhi
Noida
Mumbai
Gwalior
Bhind





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.