{
  "$type": "site.standard.document",
  "bskyPostRef": {
    "cid": "bafyreicy7i5upugdxde3inouqug52bjzwncc7og42ncvxgf5clqrrdlfcy",
    "uri": "at://did:plc:25rdn5elo5izoxrmtis34zuk/app.bsky.feed.post/3mpui7w6jiq42"
  },
  "coverImage": {
    "$type": "blob",
    "ref": {
      "$link": "bafkreieyk5ha6qevftaggggkhwwxw2hnmmhy3xtyvjhdkwyvrmq4ymkhq4"
    },
    "mimeType": "image/webp",
    "size": 58090
  },
  "path": "/irza_hashim/java-while-vs-do-while-loops-the-critical-difference-396f",
  "publishedAt": "2026-07-05T01:16:01.000Z",
  "site": "https://dev.to",
  "tags": [
    "java",
    "beginners",
    "tutorial",
    "programming"
  ],
  "textContent": "In Java, both `while` and `do-while` loops repeat a block of code as long as a condition is true. However, there is one critical difference between them: when the condition is checked.\n\nLet's look at how they work using two simple code examples.\n\n##  1. The Java While Loop\n\nA `while` loop checks the condition _before_ executing the code block. If the condition is false at the very beginning, the code inside the loop will never run.\n\n\n\n    int ticketCount = 0;\n\n    while (ticketCount > 0) {\n        System.out.println(\"Watching the movie...\");\n        ticketCount--;\n    }\n\n\n###  Why it works:\n\nBecause `ticketCount` is 0, the condition `ticketCount > 0` is instantly false. The computer skips the loop completely. Nothing prints on the screen.\n\n##  2. The Java Do-While Loop\n\nA `do-while` loop executes the code block _first_ , and then checks the condition at the end. This means the loop will always run **at least once** , even if the condition is completely false.\n\n\n\n    int ticketCount = 0;\n\n    do {\n        System.out.println(\"Trying the ride once...\");\n        ticketCount--;\n    } while (ticketCount > 0);\n\n\n###  Why it works:\n\nThe computer enters the `do` block first and prints the message. Then it checks the condition `ticketCount > 0`. Since it is false, the loop stops.\n\n##  The Output Summary\n\nIf you run both codes, your terminal output will look like this:\n\n\n\n    [While Loop Output]: (Nothing prints)\n\n    [Do-While Loop Output]:\n    Trying the ride once...\n\n\n##  Key Conclusion for Beginners\n\n  * Use a **`while` loop** when you want to check the condition first.\n  * Use a **`do-while` loop** when you need the code to run at least one time, no matter what.\n\n",
  "title": "Java While vs. Do-While Loops: The Critical Difference"
}