user3200111
user3200111

Reputation: 3

Array initialized with 0's

I created an array int []array = new int[10];

and didn't put any elements in it.

After when i tried to display the array using:

for (int counter = 0; counter < array.length; counter++) {

    System.out.print(array[counter] + " ");

}

The output is just: 0 0 0 0 0 0 0 0 0

I want it just with spaces. When i filed the array with a char space ' ' and output the array, i get 32 32 32 32 32 32 32 32 32

Any help?

Upvotes: 0

Views: 145

Answers (5)

Salih Erikci
Salih Erikci

Reputation: 5087

Default value for int is already 0. You don't need to initialize for it to be 0. But if you want spaces you should create a char array and initialize each element to ' '.

Ex

char[] myArray = new char[10]

for(int i = 0; i < myArray.length; i++) 
{ myArray[i] = ' '; }

Upvotes: 0

Jon Lin
Jon Lin

Reputation: 143896

int is a primitive, its default value is 0. When you try to store a char (another primitive) as an int, the space = 32.

Upvotes: 3

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

By declaring the array as int[], you're telling the compiler that you want the array's contents to be treated as integers. Numbers. You can't then go and expect it to deal with things that are not numbers, such as space characters. If you want to store characters in an array, you should declare it as char[].

Even if you declare the array as char[], it's not going to contain spaces by default. You'll still need to put the spaces in explicitly.

Upvotes: 1

keshlam
keshlam

Reputation: 8058

Normal Java behavior. If you don't supply an initializer, or set the array's contents, they will be initialized to 0.

It sounds like you wanted

int[] array = new int[]{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};

or

int[] array = new int[]{32,32,32,32,32,32,32,32,32,32};

Upvotes: 0

Henry
Henry

Reputation: 43738

If you want to have characters in the array you should use a char[] instead of an int[]. But still, you need to initialize it with blanks, the default initialization puts 0 into the array elements.

Upvotes: 0

Related Questions