Skip to main content

Java Keywords (Part XXIV): native

Java keyword list abstract continue for new switch assert default goto * package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const * float native super while Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers. This is the last chapter of the Java Keyword series. This is probably the keyword I have used the least. In my 20 year career as a software developer, I have used this keyword once, and that was to make some addition to legacy code. The keyword native is a method modifier . Basically, it is a keyword that can only be applied to methods. According to the Java Language Specification (JLS), A method that is native is implemented i...

Java Keywords (Part VII): Loops


The Java keyword list has 21 keywords grayed out. That puts us at 42% of keywords covered by these series of articles. Amazingly, that's almost enough knowledge to built simple applications. I suggest that if you have not read any of the articles in Java Keyword series, go back read them before proceeding further. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page.

This article will cover the keywords used for looping: for, do, and while, as well as the keywords used to change the flow of loops: break and continue.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

Although the list above is arranged in alphabetical order, I will go through them in a different order.

Loop Operations

In my years teaching Java programming in college, I don't recall a topic that that got students more exciting than Loops. This is because up to that point, basic programs were not as exciting. You can only do "Hello World!" so many times before it becomes boring. But I wasn't surprised because this topic had the same effect when I was a student. Loops allow you to simplify your code by enclosing within them units of code that you wish to repeat for a determinate period (or number) of times. As mentioned in the introduction, there are three loop structures in Java: the for loop, the while loop, and the do/while loop.

The main purpose of loop structures is to simplify code. Suppose a block of code is to be executed 100 times. It makes little sense to copy an paste the same code 100 times sequentially. Suppose you want to write code that will read you a line of text as long as there are lines to read in a book. Since you may not know how many lines of text a particular book may have, it will be nearly impossible to copy and paste this read operation. Also, two books may not have the same number of lines. Therefore, the number of iterations will vary depending of which book you wish to read. Those scenarios are basically impossible to code without loop operations.

Classic for loop

The basic structure of the classic for loop is as follows:

for (initialization condition; loop termination condition; loop count update) {
  // Execute whatever is inside this block the loop
  // until the termination condition is met
}
When using the classic version of this loop:
  1. The initialization condition initializes the loop. It executes once, when the first iteration of the loop starts.
  2. When the termination condition evaluates to false, the loop terminates and the rest of the program resumes.
  3. The loop count variable is updated after at the end of each iteration. This expression can increment or decrement the counter loop value.
  4. Typically, the loop is executed the number of times determined by the loop termination condition.
It is imperative that the termination condition takes in consideration how the loop counter variable is modified to break when the count reaches a certain value. Otherwise, an infinite loop condition could occur. For example, if we desire to loop 10 times, if we start the loop with a counter loop variable of 1, our break condition (to stop after the tenth iteration) must be counter variable > 10 or counter variable >= 11.

You could also write a loop that

while loop

A while loop is a structure similar to the for-loop. However, the looping condition is evaluated prior entering the loop. Because of that, the code inside the loop will be executed zero or more times. In order to enter the loop, the Boolean expressions that determines the looping condition must evaluate to true. Assuming that the looping condition is met, the code inside the loop will be executed. The looping condition reevaluated at the beginning of each iteration. The caveat of this type of loop is that the programmer must add code to force a change the value of this Boolean expression to false. Otherwise, the loop will run endlessly. For now, assume that endless looping is an undesirable condition. The general form of a while loop is as follows:

while (looping condition is true) {
  // Execute whatever is inside this block the loop
  // until the looping condition is no longer true
}
There is no performance advantage of the while-loop over the for-loop or vice versa. Therefore, it is (mostly) a matter of preference which of the two to use in any given case.

do-while loop

A do-while loop is a structure similar to the while loop, except that the code inside the loop will be executed at least once and the looping condition is evaluated at the end of each loop. As the case with the while-loop, the caveat of this type of loop is that the programmer must add code to force a change the value of this Boolean expression to false. Otherwise, the loop will run endlessly. For now, assume that endless looping is an undesirable condition. The general form of a while loop is as follows:

do {
  // Execute whatever is inside this block the loop
  // until the looping condition is no longer true
} while (looping condition is true); // Not ending with semi-colon is a syntax error
There is no performance advantage of the do-while loop over the for-loop or vice versa. Therefore, it is (mostly) a matter of preference which of the two to use in any given case. But, there are times where it makes more sense to use a do-while over a while. However, since it is a matter of preference based on performance, most developers use the while loop over the do-while, making sure that the looping condition to be met so that the while loop is executed at least once. In my opinion, this is not necessary since there is already a looping structure that allows for a loop to be executed 1-or-many times. So, why not use it?

Next up, Part VIII: Skipping Loop Iterations and Escaping Loops

Comments

  1. I find loops most useful for traversing arrays, vectors and other data structures used to contain a sequence of elements. Regarding Java, it is useful to quickly traverse an array of elements with 2 or 3 lines of code - using a for loop from 0 -> array.length. Performing array operations inside of a for loop make it so you don't exceed the array bounds and leak memory or crash the program.

    Although nested-loops can get overwhelming very quickly so it is best to make comments to label the purpose of the loop.

    ReplyDelete
    Replies
    1. Now with Lambda Expressions, you can do even more powerful traversing; especially when your data structures are large. At some point (hopefully soon) I will write about Lambda Expressions. If you haven't explore them, I suggest you do and also stay tuned.

      Delete
  2. Loop is found particularly strong in programming. We have many ways to customize loop. For example, we can use the break statement to stop a for loop, use the continue statement to stop a single for lop but keep doing the remaining loops. Moreover, manipulations with array is strongly associative with loops.

    ReplyDelete
  3. Loops are a huge part of coding, it is the sort of the back bone of programming. Even though there are number of loops like do, while , and do-while they fundamentally the same. One just loop as it is, one loops with exceptions and etc. Array manipulation is done with loops also.

    ReplyDelete

Post a Comment

Popular posts from this blog

Implementing Interfaces with Java Records

If you have not read my article on Java records and do not know about this topic, please read my blog titled " Customizing Java Records " first and then come back to this one. Now that you know how to customize Java records, implementing an interface using Java records should be very easy to understand. If you don't know about interfaces in Java, you can read more on my article about interfaces. The recipe for implementing an interface is simply an expansion of what you learned in my previous blog on how to customize a Java record. Following our Rectangle example, let's create an interface with the same two methods we used before. public interface Shape { double area(); double perimeter(); } Now, let's further customize the previous example by doing two things: Add implements Shape at the end of the record declaration (after the record constructor), and Add @Override to the existing methods to ensure these methods com...

Customizing Java Records

If you have not read my article on Java records and do not know about this topic, please read my blog titled " Java Keywords Addendum: The Java Record " first and then come back to this one. What is a customization of a record? A customization of a record is simply the addition of code inside the body of the class. Before proceeding further, let's recap important aspects of a Java Record: Java records are immutable Because of item 1 above, you cannot add new fields unless defined in the record constructor Java records already override: Object#equals(Object) and Object#hashCode() , and then override Object#toString() You could redefine overridden methods as part of your customization if you would like. For example, if you want a fancier implementation of the Object#toString() method, you could do so. Let's look at our first customization example. Using the example from my previous blog, public record Student(...

Object-Oriented Programming Basics: What is in a Class?

EDITORIAL NOTE : This article was published briefly back in 2016 and quickly set back to draft because I wasn't happy with its contents. It is a shame that it was taking me three years to revisit this topic and work on a new and improved version. At least, I'm hoping it will be to the liking you the reader. Keep in mind that the opening paragraph will still read as if I just wrote it for my (former) students at Texas Wesleyan. I started working on lecture on the topic of Object-Oriented (OO) Programming by gathering some material, old and new, when I realized this might be good and simple post for my second attempt at blogging. To be completely honest, in the 8 hours I spent collecting information and preparing material for this week's lecture, I realized I still made some of the mistakes I am about to blog about. I am actually hoping I can write a series of postings regarding Object-Oriented Programming (OOP). But to do so, I must start from the very beginning. ...