Am I missing something?

Doesn't this hypothetical code

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
} else {
    dataColLinker.set(rowIndex, value);
}

mean the same thing as this?

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
}
dataColLinker.set(rowIndex, value);

or this?

if (rowIndex >= dataColLinker.size()) {
    do {
        dataColLinker.add(value);
    } while(rowIndex >= dataColLinker.size());
} else {
    dataColLinker.set(rowIndex, value);
}

(The latter makes more sense ... I guess). Either way, it is obvious that you can rewrite the loop so that the "else test" is not repeated inside the loop ... as I have just done.


FWIW, this is most likely a case of premature optimization. That is, you are probably wasting your time optimizing code that doesn't need to be optimized:

  • For all you know, the JIT compiler's optimizer may have already moved the code around so that the "else" part is no longer in the loop.

  • Even if it hasn't, the chances are that the particular thing you are trying to optimize is not a significant bottleneck ... even if it might be executed 600,000 times.

My advice is to forget this problem for now. Get the program working. When it is working, decide if it runs fast enough. If it doesn't then profile it, and use the profiler output to decide where it is worth spending your time optimizing.

Answer from Stephen C on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_while_loop.asp
Java While Loop
How Tos Add Two Numbers Swap Two ... Loop Loop Through an Enum ... assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String ...
Top answer
1 of 7
21

Am I missing something?

Doesn't this hypothetical code

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
} else {
    dataColLinker.set(rowIndex, value);
}

mean the same thing as this?

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
}
dataColLinker.set(rowIndex, value);

or this?

if (rowIndex >= dataColLinker.size()) {
    do {
        dataColLinker.add(value);
    } while(rowIndex >= dataColLinker.size());
} else {
    dataColLinker.set(rowIndex, value);
}

(The latter makes more sense ... I guess). Either way, it is obvious that you can rewrite the loop so that the "else test" is not repeated inside the loop ... as I have just done.


FWIW, this is most likely a case of premature optimization. That is, you are probably wasting your time optimizing code that doesn't need to be optimized:

  • For all you know, the JIT compiler's optimizer may have already moved the code around so that the "else" part is no longer in the loop.

  • Even if it hasn't, the chances are that the particular thing you are trying to optimize is not a significant bottleneck ... even if it might be executed 600,000 times.

My advice is to forget this problem for now. Get the program working. When it is working, decide if it runs fast enough. If it doesn't then profile it, and use the profiler output to decide where it is worth spending your time optimizing.

2 of 7
2

I don't see why there is a encapsulation of a while...

Use

//Use the appropriate start and end...
for(int rowIndex = 0, e = 65536; i < e; ++i){        
    if(rowIndex >= dataColLinker.size()) {
         dataColLinker.add(value);
     } else {
        dataColLinker.set(rowIndex, value);
     }    
}
Discussions

java - While-loop(if else statement) - Stack Overflow
I want my program to input 9 numbers. If I input a number that is less than zero or greater than nine, it should loop back and will ask you again to input another number. The image attached is my p... More on stackoverflow.com
🌐 stackoverflow.com
Help with a While Loop (Java)
Notice that you never change the value of truInput1 in the body of the while loop. Also notice that this truInput1 != 'R' || truInput1 != 'Q' is always true. Every character is either not equal to R or not equal to Q. More on reddit.com
🌐 r/learnprogramming
4
5
October 16, 2022
[Java] Use if/else statement nested in a while loop?
Yes, you can nest if/else inside a while loop, if that's what you're asking. ... I was having some trouble computing them for while, but I've finally figured it out :) Thanks! I had a fundamental problem wrong with the condition statement and so I thought it wasn't possible to do this at first. ... To add to this response, in Java ... More on reddit.com
🌐 r/learnprogramming
7
1
October 22, 2015
While loops can have an else statement!
You're almost right! The code under the else will be executed only when the while loop is not "broke out of". In the following code, if you change the variable guess to the value 10. The else clause will be executed. l = [4,5,6,7,8,9] count = 0 guess = 5 while count < len(l): if l[count] == guess: break count += 1 else: # if guess == 5 this will not be executed print("guess not found") print(count) More on reddit.com
🌐 r/learnpython
4
9
January 31, 2024
🌐
BeginnersBook
beginnersbook.com › 2015 › 03 › while-loop-in-java-with-examples
While loop in Java with examples
In this program, we are printing the integer number in reverse order starting from 10 (as i is initialized as 10). Inside the body of while loop, we are decrementing the value of i using i--. So on every next iteration of while loop, the value of i is less by 1, the loop checks whether the value of i >1, if yes it executes the codes else the loop ends.
🌐
Quora
quora.com › Can-I-nest-an-if-else-inside-of-a-while-loop-in-Java
Can I nest an if/else inside of a while loop in Java? - Quora
What if I nest while loops in C? Should we nest two while loops inside an outer while loop? What type of error can we get? Can I nest a for-loop inside if else which is already in a for loop? ... Yes. In Java you can nest an if/else inside a while loop (and vice‑versa).
🌐
W3Schools
w3schools.com › java › java_while_loop_do.asp
Java Do/While Loop
How Tos Add Two Numbers Swap Two ... Loop Loop Through an Enum ... assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-while-loop-with-examples
Java while Loop - GeeksforGeeks
Control enters the while loop. The condition is tested. If true, execute the body of the loop. If false, exit the loop. After executing the body, update the loop variable. Repeat from step-2 until the condition is false. Below are the examples of Java while loop that demonstrates repeating actions and performing calculations.
Published   March 13, 2026
🌐
UC Berkeley
inst.eecs.berkeley.edu › ~cs61bl › r › › cur › loops-conditionals › if-else-while.html
If, Else, While
Here's an example: ... The while statement is used to repeat a given sequence of statements. It consists of the word while, followed by a continuation test in parentheses, followed by a sequence of statements to repeat, enclosed in braces. The statement sequence is called the loop body.
🌐
Reddit
reddit.com › r/learnprogramming › help with a while loop (java)
r/learnprogramming on Reddit: Help with a While Loop (Java)
October 16, 2022 -

**SOLVED**
Thanks lurgi!

Hello, and thank you for your time. I am a student rather new to Java, and programming as a whole.

I am trying to make it so that after the 'else' statement, the loop checks the condition for the 'while' booleans again. I have been at this for around two hours, to no avail. Did I write the entirety of the code incorrectly? Thank you again for your time.

String choice1 = input.nextLine();

choice1 = choice1.toUpperCase();

char truInput1 = choice1.charAt(0);

while (truInput1 != 'R' || truInput1 != 'Q') {

if (truInput1 == 'R') {

System.out.println("placeholder1");

}

else if (truInput1 == 'Q') {

System.out.println("exit placeholder");

System.exit(0);

}

else {

System.out.println("incorrect placeholder");

choice1 = input.nextLine();

choice1 = choice1.toUpperCase();

}

}

Top answer
1 of 2
4
Notice that you never change the value of truInput1 in the body of the while loop. Also notice that this truInput1 != 'R' || truInput1 != 'Q' is always true. Every character is either not equal to R or not equal to Q.
2 of 2
1
I see what your saying, think about all possible cases. Case 1: truInput1 is ‘R’. In this situation, if the truInput1 is ‘R’, then the second part of the OR logic, that truInput1 is not ‘Q’ is true. Thus, since OR is existential, the entire while loop condition is true. Then you print “placeholder1” to the console. Case 2: truInput1 is ‘Q’. In this situation, if truInput1 is ‘Q’, then it’s not ‘R’, so the first part of the OR is true, and the while loop condition is true. When you enter into it, the second branch (else if) will be True since truInput is ‘Q’ and the program will end. Case 3: truInput is neither ‘R’ nor ‘Q’. Since the truInput1 is not ‘R’ and also not ‘Q’, both parts of the while loop condition will be true, and the OR will be true. So then you enter the loop, you check to see if truInput1 is ‘R’ or ‘Q’ again, which it isn’t, and then you execute the else. And....we’ve arrived at the problem! The problem is in that third case, where the truInput1 is not ‘R’ nor ‘Q’, when the else branch executes see you only updating “choice1” - notice this does NOT have to do with the condition on the while loop. In the while loop you are comparing against truInput1. So try changing your else to else { System.out.println(“incorrect..”); choice1 = input.nextLine(); choice1 = choice1.toUpperCase(); // this was the missing piece truInput1 = choice1.charAt(0); } Another thing on second thought is to examine what happens in case 1 again. Suppose the input provided is ‘R’, then that if statement executes, printing it to the console, but truInput1 is NOT updated again! Idk if that’s what you want, but if not, you will need to gather the input again & reset truInput1 for that case as well. Hopefully that helps
🌐
Oracle
docs.oracle.com › javase › tutorial › java › nutsandbolts › while.html
The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count < 11); } }
🌐
Programiz
programiz.com › java-programming › do-while-loop
Java while and do...while Loop
Java if...else Statement · In computer programming, loops are used to repeat a block of code. For example, if you want to show a message 100 times, then you can use a loop. It's just a simple example; you can achieve much more with loops. In the previous tutorial, you learned about Java for loop. Here, you are going to learn about while and do...while loops.
🌐
Steemit
steemit.com › programming › @robertlyon › java-programming-for-beginners-lesson-6-while-do-while-loops
Java programming for beginners - Lesson 6 - While/Do While Loops — Steemit
November 28, 2017 - This variable holds the value true. The condition for a while loop must be true for the loop to execute. If the condition is equal to false then the program will skip the loop and continue on with the program. The block of code inside the loop contains an if/else statement.
🌐
Sololearn
sololearn.com › en › Discuss › 1968732 › does-while-loop-can-use-as-if-else-statement
Does while loop can use as if else statement?
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
Reddit
reddit.com › r/learnpython › while loops can have an else statement!
r/learnpython on Reddit: While loops can have an else statement!
January 31, 2024 -

Maybe I'm the only one who didn't know this, but you can put an else statement after a while loop which will be used if the while loop is never entered. I found this out on the Leetcode problem of the day for today when I tried putting an else after my while loop, mostly expecting an error but typing because it's what I wanted the code to do, and it ran! The code I used is below. I know there are more optimal solutions, but I'm happy with what I learned today.

class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
    n = len(temperatures)
    answers = [0] * n
    stack = []
    for i in range(n):
        while len(stack) > 0 and temperatures[i] > stack[-1][1]:
            answers[stack[-1][0]] = i - stack[-1][0]
            stack.pop()
        else:
            stack.append([i, temperatures[i]])
        if len(stack) == 0:
            stack.append([i, temperatures[i]])
    return answers

🌐
Career Karma
careerkarma.com › blog › java › while loop java
While Loop Java: A Complete Guide | Career Karma
December 1, 2023 - The while and do...while loops in Java are used to execute a block of code as long as a specific condition is met. These loops are similar to conditional if statements, which are blocks of code that only execute if a specific condition evaluates ...
🌐
DataCamp
datacamp.com › doc › java › java-while-loop
Java While Loop
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The while loop in Java is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The loop continues to execute as long as the ...
🌐
Coderanch
coderanch.com › t › 682648 › java › Java-loop
Java loop with if else [Solved] (Beginning Java forum at Coderanch)
Loop does work, perhaps not in the way you want it to work. Think for a moment, when you enter else part and start loop, do you ever give user a chance to re-enter password? By the way, your indentation is off.