This question already has answers here:
Closed 10 years ago.
Possible Duplicates:
Loop counter in Java API
Which of these pieces of code is faster in Java?
for(int i = 100000; i > 0; i--) {}
for(int i = 1; i < 100001; i++) {}
Which one is faster?I read that first for loop is faster.is it true?Then how it become faster than other?please help.
There is no way to tell which of the two is faster.
If all you provide is a snippet of Java code, all we have to go on is the Java Language Specification. Since the Java Language Specification never mentions any timing aspects there's no way to answer the question.
It is similar to asking your math teacher, "Which is faster to compute, 17+17 or 17*17?" Your math teacher will just stare at you and at best respond with something like, "are you using pen and paper or a pocket calculator?"
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I had recently a discussion about the use of non-counter related conditions in for-loops in Java:
for(int i = 0; o.getC() < 10; i++)
o.addC(i);
Does anyone know if there are any "official" conventions for for-conditions like this? In my opinion it's easier to read compared to an equivalent while-loop because all loop-parameters are together in the first line:
int i = 0;
while(o.getC() < 10) {
i++;
o.addC(i);
}
Or even worse:
int i = 0;
while(o.getC() < 10)
o.addC(++i);
for loops are used in pretty much every situation over equivalent while solution. Arrays, lists, standard data structures.
On the other hand while is commonly used with streams and for infinitely long iterations..
Most developers will expect a for statement to consist of three things:
Initialization of a variable
Termination condition based on the variable
Increment on the variable
If you change your code to contain unexpected things it will get harder to read and thus harder to maintain.
Furthermore, I think the while loop makes your intention clearer: do something while o.getC() is less then 10. This "something" happens to be: add an incrementing number.
Long story short: use a while loop for "non-counter related conditions".
A nice thing about for loops is there is a shortcut method. So if you want to do all of the items in an array you can just do the following:
(double number : arrayName)
where double is the type, number is the name you are giving each element (it doesn't matter really what you call it, you will refer to each value there as "number" in this case). And arrayName is the name of the array you are referring to.
If you want to reach each element/object this is the fastest way.
How about:
for(int i = 0; i < MAX_ITERATIONS; i++)
{
o.addC(i);
if (o.getC() >= 10)
return o; // or break
}
This prevents an infinite loop if addC is not really doing what you expect.
This question already has answers here:
Does Java 8 provide a good way to repeat a value or function?
(6 answers)
Closed 7 years ago.
Maybe a normal for loop is still the right way but I wanted to see if there is a more succinct way to do it in java 8.
for (int i = 0; i < LIMIT; i++) {
// Code
}
Is there a more java 8 way to do this. I don't actually need i just need to repeat something x number of times.
Thanks,
Nathan
The best way I can see on how to do this would be something like IntStream.range(0, LIMIT).forEach($ -> code).
One of the reasons to use IntStream is to add parallel-ism, assuming you understand the impact of this.
IntStream.range(0, LIMIT).parallel().forEach($ -> {
// some thing thread safe.
});
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
I came across a code snippet online that used a notation that from what I gather seems to do a comparison and then returns back possible multiple outputs. I am still confused about it, even after research. Can someone re-write the code snippet to an equivalent, more basic version so that I can make sure I am understanding what I am seeing?
int mPart = i < mParts.length ? Integer.parseInt(mParts[i]) : 0;
Thanks in advance!
This is ternary IF operator. This line is equal to
int mPart;
if(i < mParts.length) {
mPart = Integer.parseInt(mParts[i]);
} else {
mPart = 0;
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it better to use the variable 'i' or a meaningful name such as 'loopCount' or 'studentsCount' etc?
e.g.
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 5; j++)
{
System.out.println(i + j);
} // End of j loop
} // End of i loop
VS
for (int outerLoop = 0; outerLoop < 10; outerLoop++)
{
for (int innerLoop = 0; innerLoop < 5; innerLoop++)
{
System.out.println(outerLoop + innerLoop);
} // End of innerLoop
} // End of outerLoop
By better; the main considerations would be readability / conventions.
Related question Loop iterator naming convention
EDIT:
I have tagged this a java, but answers for other languages are welcome.
Firstly, using Integer here is very expensive because Integer is immutable. Thus each time you do an increment it unboxes the previous Integer, do an increment and creates another Integer to hold the new value. You need to use int.
Secondly, whether to have a readable name really up to the semantics of the int. If it's just a control variable over a pre-determined number of loops I think i is fine; but if it has specific meaning then you are free to give it a better meaningful name.
Code is communication: what do you want the reader of this code (who might be you months or years from now) to think when he sees it? To me, using "i" and "j" in a loop says "do this thing 10 times; the variable is just a convention and means nothing", while using a more descriptive variable like "studentID" says "this number actually refers to something specific" I'd use the former if I want to de-emphasize the variable itself, and the latter if I want to highlight it.
I have seen many loops that started out small and grew very large with other loops added inside and around them and it all became a confusing mess of i j k x y z. Name your references with the shortest name that expresses your intent, so another dev will know what you were going for.
Traditionally i and j are used for this type of thing, but there's certainly nothing wrong with giving them a meaningful name to aid in readability. If I were reading another persons code, I would rather prefer outer/innerloop to i and j.
Use i and j if you want. People reading your code will probably decode these to be the names of loop variables, and if they can't, then shame on them.
(( if you use long names for loop variables in a language where long names will hinder performance, then I'll slap you ))
In the looping you can use i , j (not meaningful name) and the program will compile and run.
But in the big project if you use i, j , this is only know you. Other person who is your leader difficult to understand your code. That why you should make habit even there are not big project.
Thank you
i and j origin in mathematical conventions for matrices, as a form of abstraction. I use it mainly in an math/numeric algorithm context.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have a program that I am writing and I have it completed but I keep receiving an error in a counter that I am using. The purpose of the program is to build a plate stacker and I have finished that but need to write a counter based on the particular colors used (how many green plates...etc.). As I know several classmates use this site to cheat, I will not post the code in whole but only the fragments I feel are necessary. Below is an example of a statement that I am using to attempt to get a count of the beige plates in the text file. The statement is in a while loop with the other colors having the same coding. I also have initialized the counter (int beige = 0;) prior to this and outside of the while loop:
if(line == "beige")
{
beige++;
}
I have a System.out following these statements to display the count but it always comes up as 0 so I believe the problem is in this particular fragment. If I need to send additional coding I will but I believe it is something to do with this or the placement of it in the while loop.
First, you are comparing the string in a wrong way. Use .equals method.
if (line.equals("beige"))
beige++;
Second, you can use HashMap for this kind of problem where you keep updating the value(count) for key(color) and it will save you a lot of if conditions if say there are a hundred different colors!