• 0

Super basic Java question about while loops and arrays.


Question

I know it probably doesn't make a whole heck of a lot of difference if I'm correct, BUT is

int i = 0;
String[] titles = new String[maxNum]; //maxNum is being passed in, so this can be any (positive integer) value
	while (i < maxNum){
		titles[i] = titleName;
		i++;
	}

the same as

int i = 0;
String[] titles = new String[maxNum]; //maxNum is being passed in, so this can be any (positive integer) value
	while (i < maxNum){
		titles[i++] = titleName;
	}

What I am asking about in particular is if putting the i++ in the brackets as opposed to right after the assignment will make all of the elements of the array be off by one...as in, the first time I run this code, will titles[0] be empty, or will it actually assign 'titleName' to the 0th element?

Thanks!

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

What titles[i++] = titleName; means is

titles[i] = titleName;
i = i + 1;

The most usual way to do that, which you should favor because it improves readability, is a for loop :

for (int i = 0; i < maxNum; i++)
	titles[i] = titleName;

In Java, you have access to an even more simple construct :

for (string title : titles)
	title = titleName;

http://java.sun.com/j2se/1.5.0/docs/guide/...ge/foreach.html

Edited by Dr_Asik
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.