Taking N number of inputs from user

How to take input from user untill user enters a negative number in java. while loop for taking infinite inputs from user.

Taking N number of Inputs from User

Hello everyone here i am going to discuss how to take input from user or external input until a user enters negative number.


  • The first problem with this is we exactly don’t know how many inputs user is going to enter.
  • So we are unable to decide what should be the size of array to store those numbers.


  • We will take input untill user enters zero, so we will be using “While Loop” for checking the condition.
  • Also as we are not sure about number of elements, we will use “ArrayList” instead of array. Because the size of array is fixed but arraylist size is not fixed it can grow dynamically.
  • Initial capacity of array list is 10 elements, once it reaches maximum capacity the arraylist size will be increased automatically by current size * 3 /2 .
  • As we are using while loop it terminates whenever user enters a negative number.


import java.util.*;

class demo {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		ArrayList array1=new ArrayList();
		System.out.println("enter array elements");
		boolean flag=true;
		while(flag) {
			int a=sc.nextInt();
			if(a>0) {
			else {

Similar Posts

Xoriant off campus coding question and solution

Beginner’s friendly top 5 array questions in java

3 Ways to Find Prime Number

Leave a Comment

Your email address will not be published. Required fields are marked *