top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Quick reference to Java Loop Control

+1 vote
269 views

Need of Loops

A computer program is a set of statements , which are usually executed sequentially. However, in certain situations it is necessary to repeat certain steps to meet a specified condition.

For example, if the user wants to write a program that calculates and display the sum of the first 10 numbers 1,2,3,...,10.

On way to calculate the same is as follows:

1+2=3

3+3+=6

6+4=10

10+5=15

……

and so on.

This Technique is suitable for relatively small calculations. However, if the program requires adding the first 200 numbers, it would b tedious to add up all the numbers from 1 to 200 using the above mentioned technique. In such situations, iterations or loops come to our rescue.

Definition and Types

A loop comprises a statement or a block of statements that are executed repeatedly untill a particular condition evaluates to true or false.

Loop enable programmers to develop concise programs, which otherwise would require thousands of program statements.

The loop statements supported by java programming language are:

  • While

  • Do-while

  • For

While Statement

The while statement in java is used to execute a statement or a block of statements while a particular condition is true. The condition is checked before the statement are executed. The condition for the while statement can be any expression which returns a boolean value.

Syntax:

while (expression)

{

//one or more statements

}

Rules

 The following points should be notes when using the while statement.

  • The values of the variables used in the expression must be set at some point before the while loop is reached. This process is called the initialization of variables and has to be performed once before the execution of the loop.

  • The body of the loop has an expression that changes the value of the variable that is a part of the loop’s expression. A variable is said to be incremented if its value increases in the body of the loop and is said to be decremented if its value decreases.

Do-while Statement

The do-while statement check the condition at the end of the loop rather than at the beginning to ensure that the loop is executed at least once. The condition of the do-while statement usually comprises of an expression that evaluates the boolean value.

Syntax:

do

{

Statement(s);

} while (expression);

For statement

The for statement is similar to the while statements in its function. The statements within the body of the loop are executed as long as the condition is true. Here too, the condition is checked before the statements are executed.

Syntax:

for(initialization; condition; Increment/decrement)

{

//one or more statements

}

Nested Loop

The placing of a loop in the body of another loop is called nesting. For example, a while statement can be enclosed within a do-while statement and a for statement can be enclosed within a while statement. When you nest two loops, the outer loop controls the number of times the inner loop is executed. For each iteration of the outer loop the inner loop will execute all its iterations. There can be any number of combinations between the three loops. While all types of loop statements may be nested, the most commonly nested loops are formed by for statements.

Syntax

for (initialization; condition; Increment/decrement)

{

for (initialization; condition; Increment/decrement)

{

//statements;

}

}

Here is a difference between while/for and do-while loops:

While/for

Do-while

Loop is pre-tested. The condition is checked before the statements within the loop are executed

Loop is post-tested. The condition is checked after the statements within the loop are executed.

The loop does not get executed if the condition is not satisfied at the beginning.

The loop gets executed at least once even if the condition is not satisfied at the beginning.


For more watch this tutorial video:

posted Jun 28, 2017 by Kalpana Jain

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

                                                                                                         

Uses of JSON

JSON is widely preferred to serialize and send data over a network, for instance, between a web application and a web server. Serialization transforms data structures to a format that is appropriate for transferring over a network or for storing in a memory buffer or file for later retrieval.

JSON, as a data-interchange format, it also used to facilitate communication between incompatible platform. For instance, it becomes possible for a Java application on UNIX to send information to visual Basic application running on windows by using JSON.

When XML was introduced during the late 90s, it was a boon for several business mangers due to its intuitive HTML -like look . On the other hand, developers knew that parsing XML is not simple.

JSON is also preferred for developing JavaScript based applications, such as web sites and browser extensions. Even Application Programming Interfaces (APIs) and web services uses JSON to send public data.

History of JSON

JSON was introduced to fulfil the requirement of real-time, stateful exchange of data between a server and client but without plugins such as java applets. While Douglas Crockford originally specified this new format, the term was first coined at the state software company started by co-founders namely, Rebert F, Chip Morningstar, and Crockford.

The co-founders decided to develop a system that can harness the normal browser potential as well as offer an abstraction layer for designing stateful applications for the web. These applications should maintain a persistent connection with the server by having two Hypertext Transfer Protocol (HTTP) connections open. These connections should be recyclable prior to the typical timeout of the browser, in case of no further exchange of data. One of the co-founders Morningstar developed the notion for such a state application framework.

Features of JSON

  • Standard Structure: The JSON format has a standard structure, making it easier for developers to write code.
  • Simplicity: The representation of data in JSON format is simple, which makes it simpler for a developer to comprehend the code. Even parsing becomes easy, regardless of the program language in use. The compact and simple JSON format allows quick transfer of data across platforms for reaching a variety of users across the globe.
  • Open: JSON is similar to XML in terms of openness. It is publicly available and is not at the core of corporate/political tussles for standardization. One can easily take advantage of open structure for adding other elements when needed and adapt the system to hold new industry-specific terms. If these terms are in XML format, one can automatically convert them to JSON, as migrating is straightforward.
  • simplicity: The representation of data in JSON format is simple, which makes it simpler for a developer to comprehend the code. Even parsing becomes easy, regardless of the program language in use. The compact and simple JSON format allows quick transfer of data across platforms for reaching a variety of users across the globe.
  • Open: JSON is similar to XML in terms of openness. It is publicly available and is not at the core of corporate/political tussles for standardization. One can easily take advantage of open structure for adding other elements when needed and adapt the system to hold new industry-specific terms.
  • Self-describing: JSON is self-describing, which means it is possible to describe one’s own field names and their specific values. This enables applications to manipulate JSON data.
  • Lightweight: Data in JSON format does not much storage space. It is also easier to obtain and load such data quickly as well asynchronously without reloading the page. This makes AJAX applications efficient in terms of performance.
  • Clean Data: With a standardized structure, JSON is less susceptible to errors. The application obtaining JSON data is aware of how to get the data and what to expect, which is different from using HTML. Such a structure also helps the developer in offering robust cross-browser solutions, which is useful considering the advent of different browser on mobile devices.
  • Efficiency: While using JSON data structure, the previous outputted data list is created or cloned on the client side. This means that only the changed information is transferred to client on every request. The small optimization is likely to boost both performance and usability of web applications, considering the swift increase in internet connections.
  • Extensibility: JSON allows storing only standard data such as numbers and text. On the other hand, XML allows storing any data type. While this is a benefit of using XML, it is also a con or a drawback, as it makes reading a bit more difficult.
  • Internationalization: JSON implements the Unicode norm due to which generic tools can easily manipulate its structured data. Thus, this structured data is easy to distribute to a wide range of platforms as well as users.

JSON vs. XML

Characteristic

JSON

XML

Data Types

Offers scalar data types and articulates structured data in the form of objects and arrays.

Does not offer any idea of data types due to which replying on XML Schema is essential for specifying information about the data types.

Array Support

Provides native support

Expresses arrays by conventions. For instance, XML employs an outer placeholder element that forms that content in an array as inner elements.

Object Support

Provides native support

Expresses objects by conventions, usually by combining attributes and elements.

Null support

Recognizes the value natively

Mandates the use of xsi:nil on elements in an instance document along with the import of the related namespace.

Comments

Does not support

Provides native support (via APIs).

Namespaces

Does not support namespaces and that naming collisions do not occur, as objects are nested or the object member name has a prefix.

Accepts namespaces to prevent name collisions and safely extend the prevalent XML standards.

Formatting

Is simple and offers more direct data mapping.

Is complex and needs more effort for mapping application types to elements.

Size

Has very short syntax, which gives formatted text wherein most space is taken up by the represented data.

Has lengthy documents, particularly in case of element-centric formatting.

Parsing in JavaScript

Needs no additional application for parsing (JavaScript’s eval() function works well).

Implements XML DOM and requires extra code for mapping text to JavaScript objects.

Parsing

Has JSONPath for selecting specific sections of the data structure but is not widely used.

Has XPath specification for doing the same in an XML document and is widely used.

Styling

Has no special specification

Has XSLT specification for styling an XML document

Security

Is less secure, as the browser has no JSON parser

Is more secure.

 

Let us now see how XML and JSON format appears while storing the details of three students. These details are stored in a text-based format for later retrieval.

Code snippet 1: shows the XML code.

<students>

<student>

<name>Pankaj</name> <age>24</age> <city> Bangalore </city>

</student>

<student>

<name>Bob</name> <age>22</age> <city> Washington </city>

</student>

<student>

<name>Michal</name> <age>27</age> <city> Denver</city>

</student>

</students>

Code snippet 2:  Shows the JSON code.

{“students”: [

{“name”: “Pankaj”, “age”: “24”, “city”: “Bangalore”},

{“name”: “Bob”, “age”: “22”, “city”: “Washington”},

{“name”: “Michal”, “age”: “27”, “city”: “Denver”}

] }

Note: It is clear that JSON is more lightweight as well as compact than XML. 

READ MORE
...