Datatypes Operators Control Statements
Datatypes Operators Control Statements
Datatypes Operators Control Statements
Java programming language is a language in which all the variables must be declared first and then to be used. That means to specify the name and the type of the variable. This specifies that Java is a strongly-typed programming language. Like int pedal = 1; This shows that there exists a field named 'pedal' that holds a data as a numerical value '1'. The values contained by the variables determines its data type and to perform the operations on it. There are seven more primitive data types which are supported by Java language programming in addition to int. A primitive data type is a data type which is predefined in Java. Following are the eight primitive data types: int It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647. This data type is used for integer values. However for wider range of values use long. byte The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). We can save memory in large arrays using byte. We can also use byte instead of int to increase the limit of the code. short The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is used to save memory in large arrays. long The long data type is a 64-bit signed two's complement integer. It ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range of values. float The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float (instead of double) to save memory in large arrays. We do not use this data type for the exact values such as currency. For that we have to use java.math.BigDecimal class. double This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data type is generally the default choice for decimal values. boolean The boolean data type is 1-bit and has only two values: true and false. We use this data type for conditional statements. true and false are not the same as True and False. They are defined constants of the language. char The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535. They are not same as ints, shorts etc. The following table shows the default values for the data types: Keyword byte short int long Description Size/Format Byte-length integer 8-bit two's complement Short integer 16-bit two's complement Integer 32-bit two's complement Long integer 64-bit two's complement Single-precision floating float 32-bit IEEE point Double-precision floating double 64-bit IEEE point char A single character 16-bit Unicode character A boolean value (true or boolean true or false false) When we declare a field it is not always essential that we initialize it too. The compiler sets a default value to the fields which are not initialized which might be zero or null. However this is not recommended. By literal we mean any number, text, or other information that represents a value. This means what you type is what you get. We will use literals in addition to variables in Java statement. While writing a source code as a character sequence, we can specify any value as a literal such as an integer. This character sequence will specify the syntax based on the value's type. This will give a literal as a result. For instance int month = 10; In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly represents the integer value. In Java programming language there are some special type of literals that represent numbers, characters, strings and boolean values. Lets have a closer look on each of the following. Integer Literals Integer literals is a sequence of digits and a suffix as L. To represent the type as long integer we use L as a suffix. We can specify the integers either in decimal, hexadecimal or octal format. To indicate a decimal format put the left most digit as
nonzero. Similarly put the characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal format. Also we can indicate the octal format by a zero digit followed by the digits 0 to 7. Lets tweak the table below. Decimal integer literal of type long integer Hexadecimal integer literal 0x4a of type integer Octal integer literal of type 057L long integer 659L Character Literals We can specify a character literal as a single printable character in a pair of single quote characters such as 'a', '#', and '3'. You must be knowing about the ASCII character set. The ASCII character set includes 128 characters including letters, numerals, punctuations etc. There are few character literals which are not readily printable through a keyboard. The table below shows the codes that can represent these special characters. The letter d such as in the octal, hex etc represents a number. Escape \n \t \b \r \f \\ \' \" \d \xd \ud Meaning New line Tab Backspace Carriage return Formfeed Backslash Single quotation mark Double quotation mark Octal Hexadecimal Unicode character
It is very interesting to know that if we want to specify a single quote, a backslash, or a nonprintable character as a character literal use an escape sequence. An escape sequence uses a special syntax to represents a character. The syntax begins with a single backslash character. Lets see the table below in which the character literals use Unicode escape sequence to represent printable and nonprintable characters both.
Capital letter A 6.5E+32 (or Double-precision Digit 0 6.5E32) floating-point literal Double quote " Double-precision Punctuation ; 7D floating-point literal Space .01f Floating-point literal Horizontal Tab
Boolean Literals The values true and false are also treated as literals in Java programming. When we assign a value to a boolean variable, we can only use these two values. Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the values true and false to represent a Boolean value. Like boolean chosen = true; Remember that the literal true is not represented by the quotation marks around it. The Java compiler will take it as a string of characters, if its in quotation marks. Floating-point literals Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001. Java has two kinds of floating-point numbers: float and double. The default type when you write a floating-point literal is double. Type Size name bytes bits float 4 32 double 8 64 Range approximate +/- 3.4 * 1038 +/- 1.8 * 10308 Precision in decimal digits 6-7 15
A floating-point literal can be denoted as a decimal point, a fraction part, an exponent (represented by E or e) and as an integer. We also add a suffix to the floating point literal as D, d, F or f. The type of a floating-point literal defaults to double-precision floating-point. The following floating-point literals represent double-precision floating-point and floating-point values. String Literals The string of characters is represented as String literals in Java. In Java a string is not a basic data type, rather it is an object. These strings are not stored in arrays as in C language. There are few methods provided in Java to combine strings, modify strings and to know whether to strings have the same value. We represent string literals as String myString = "How are you?"; The above example shows how to represent a string. It consists of a series of characters inside double quotation marks. Lets see some more examples of string literals:
// the empty string // a string containing " // a string containing 16 characters // actually a string-valued constant expression, // formed from two string literals
Strings can include the character escape codes as well, as shown here: String example = "Your Name, \"Sumit\""; System.out.println("Thankingyou,\nRichards\n"); Null Literals The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables. For instance s = null; An this example an object is referenced by s. We reduce the number of references to an object by assigning null to s. Now, as in this example the object is no longer referenced so it will be available for the garbage collection i.e. the compiler will destroy it and the free memory will be allocated to the other object. Well, we will later learn about garbage collection.
Lets have a close look over the structure of Array. Array contains the values which are implicitly referenced through the index values. So to access the stored values in an array we use indexes. Suppose an array contains "n" integers. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "n1" indexed value. Presume an array that contains 12 elements as shown in the figure. Each element is holding a distinct value. Here the first element is refrenced by a[0] i.e. the first index value. We have filled the 12 distinct values in the array each referenced as: a[0]=1 a[1]=2 ... a[n-1]=n ... a[11]=12 The figure below shows the structure of an Array more precisely.
Array Declaration As we declare a variable in Java, An Array variable is declared the same way. Array variable has a type and a valid Java identifier i.e. the array's type and the array's name. By type we mean the type of elements contained in an array. To represent the variable as an Array, we use [] notation. These two brackets are used to hold the array of a variable. By array's name, we mean that we can give any name to the array, however it should follow the predefined conventions. Below are the examples which show how to declare an array :int[] array_name; //declares an array of integers String[] names; int[][] matrix; //this is an array of arrays
It is essential to assign memory to an array when we declare it. Memory is assigned to set the size of the declared array. for example:
int[] array_name = new int[5];
Array Initialization After declaring an array variable, memory is allocated to it. The "new" operator is used for the allocation of memory to the array object. The correct way to use the "new" operator is String names[]; names = new String[10]; Here, the new operator is followed by the type of variable and the number of elements to be allocated. In this example [] operator has been used to place the number of elements to be allocated. Lets see a simple example of an array,
public class Sum { public static void main(String[] args) { int[] x = new int [101]; for (int i = 0; i<x.length; i++ ) x[i] = i; int sum = 0; for(int i = 0; i<x.length; i++) sum += x[i]; System.out.println(sum); } }
In this example, a variable 'x' is declared which has a type array of int, that is, int[]. The variable x is initialized to reference a newly created array object. The expression 'int[] = new int[50]' specifies that the array should have 50 components. To know the length of the Array, we use field length, as shown. Output for the given program: C:\tamana>javac Sum.java
C:\tamana>java Sum 5050 C:\tamana> Array Usage We have already discussed that to refer an element within an array, we use the [] operator. The [] operator takes an "int" operand and returns the element at that index. We also know that the array indices start with zero, so the first element will be held by the 0 index. For Example :int month = months[4]; //get the 5th month (May) Most of the times it is not known in the program that which elements are of interest in an array. To find the elements of interest in the program, it is required that the program must run a loop through the array. For this purpose "for" loop is used to examine each element in an array. For example :String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"}; //use the length attribute to get the number //of elements in an array for (int i = 0; i < months.length; i++ ) { System.out.println("month: " + month[i]);
Here, we have taken an array of months which is, String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"}; Now, we run a for loop to print each element individually starting from the month "Jan". for (int i = 0; i < months.length; i++ ) In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes upto the last position which is length-1, i < months.length; indicates the length of the array and i++ is used for the increment in the value of i which is i = i+1. Multi-dimensional arrays So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed via n subscript expressions. For example, in a language that supports it, the element of the twodimensional array x is denoted by x[i,j]. The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of arrays. In Java, a two-dimensional array ' x' is an array of one-dimensional array : For instance :int[][] x = new int[3][5];
The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to select the element from that array. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "length-1" indexed value. There is no array assignment operator. Two-dimensional arrays Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int[]. Similarly we can have int[][], which represents an "array of arrays of ints". Such an array is said to be a twodimensional array. The command int[][] A = new int[3][4] declares a variable, A, of type int[][], and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays. To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called a Nested loop. That means we can run another loop in a loop. Notice in the following example how the rows are handled as separate objects.
Code: Java int[][] a2 = new int[10][5]; // print array in rectangular form for (int r=0; r<a2.length; r++) { for (int c=0; c<a2[r].length; c++) { System.out.print(" " + a2[r][c]); } System.out.println(""); }
In this example, "int[][] a2 = new int[10][5];" notation shows a two-dimensional array. It declares a variable a2 of type int[][],and it initializes that variable to refer to a newly created object. The notation int[10][5] indicates that there are 10 arrays of ints in the array a2, and that there are 5 ints in each of those arrays. Copying Arrays After learning all about arrays, there is still one interesting thing left to learn i.e. copying arrays. It means to copy data from one array to another. The precise way to copy data from one array to another is
public static void arraycopy(Object source, int srcIndex, Object dest, int destIndex,int length)
Thus apply system's arraycopy method for copying arrays.The parameters being used are :src the source array
start position (first cell to copy) in the source array the destination array start position in the destination array the number of array elements to be copied
The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to copy some elements from the copyFrom array to the copyTo array.
public class ArrayCopyDemo{ public static void main(String[] args){ char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'}; char[] copyTo = new char[5]; System.arraycopy(copyFrom, 2, copyTo, 0, 5); System.out.println(new String (copyTo)); } }
In this example the array method call begins the copy of elements from element number 2. Thus the copy begins at the array element 'c'. Now, the arraycopy method takes the copie element and puts it into the destination array. The destination array begins at the first element (element 0) which is the destination array copyTo. The copyTo copies 5 elements : 'c', 'd', 'e', 'f', 'g'. This method will take "cdefg" out of "abcdefghij", like this :
Operators
Operators are symbols that performs some operations on one or more than one operands. Once we declare and initialize variables, we can use operators to perform certain tasks like addition, subtraction etc. Simple Assignment Operator = Simple assignment operator
Arithmetic Operators + * / % Additive operator (also used for String concatenation) Subtraction operator Multiplication operator Division operator Remainder operator
Unary Operators + Unary plus operator; indicates positive value (numbers are positive without this, however)
Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 ! Logical compliment operator; inverts the value of a boolean
Equality and Relational Operators == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to
Conditional Operators && || ?: Conditional-AND Conditional-OR Ternary (shorthand for if-then-else statement)
Bitwise and Bit Shift Operators ~ << >> >>> & ^ | Unary bitwise complement Signed left shift Signed right sift Unsigned right shift Bitwise AND Bitwise exclusive OR Bitwise inclusive OR
These operators follow some precedence to apply. The table below shows the list of operators that follow the precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. However, Operators on the same line have equal precedence. The rule to deal with equal precedence operators is that all binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. Operators postfix unary Precedence expr++,, expr-++expr, --expr, +expr,
multiplicative additive shift relational equality bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical OR ternary assignment
-expr ~ ! */% +<< >> >>> < > , <= , >= instanceof == , != & ^ | && || ?: = , +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>, >=
if (a > 1) System.out.println("Greater than 1"); if (a < 1) System.out.println("Less than 1"); In the above example if we declare int a = 1, the statements will show some of the valid boolean expressions to the if statement. We are talking about if statements here so we can't forget the else statement here. The if statement is incomplete without the else statement. The general form of the statement is: if (condition) statement1; else statement2; The above format shows that an else statement will be executed whenever an if statement evaluates to false. For instance, if (a>1){ System.out.println("greater than 1"); } else{ System.out.println("smaller than 1"); } Lets have a look at a slightly different example as shown below:
class compare{ public static void main(String[] args){ int a = 20; int b = 40; if (a<b){ System.out.println("a is smaller"); } else{ System.out.println("b is smaller"); } } }
The above example shows that we have taken two numbers and we have to find the smallest amongst them. We have applied a condition that if a<b, print 'a is smaller' else print 'b is smaller'. The following is the output which we will get in the command prompt. C:\javac>javac compare.java C:\javac>java compare a is smaller The switch statement
Sometimes it becomes cumbersome to write lengthy programs using if and if-else statements. To avoid this we can use Switch statements in Java. The switch statement is used to select multiple alternative execution paths. This means it allows any number of possible execution paths. However, this execution depends on the value of a variable or expression. The switch statement in Java is the best way to test a single expression against a series of possible values and executing the code. Here is the general form of switch statement: switch (expression){ case 1: code block1 case 2: code block2 . . . default: code default; } The expression to the switch must be of a type byte, short, char, or int. Then there is a code block following the switch statement that comprises of multiple case statements and an optional default statement. The execution of the switch statement takes place by comparing the value of the expression with each of the constants. The comparison of the values of the expression with each of the constants occurs after the case statements. Otherwise, the statements after the default statement will be executed. Now, to terminate a statement following a switch statement use break statement within the code block. However, its an optional statement. The break statement is used to make the computer jump to the end of the switch statement. Remember, if we won't use break statement the computer will go ahead to execute the statements associated with the next case after executing the first statement. Here is an example which will help you to understand more easily: switch (P { // assume P is an integer variable case 1: System.out.println("The number is 1."); break; case 2: case 4: case 8: System.out.println("The number is 2, 4, or 8."); System.out.println("(That's a power of 2!)"); break; case 3: case 6: case 9: System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)"); break; case 5: System.out.println("The number is 5."); break; default: System.out.println("The number is 7,"); System.out.println(" or is outside the range 1 to 9."); } For example the following program Switch, declares an int named week whose value represents a day out of the week. The program displays the name of the day, based on the value of week, using the switch statement.
class Switch{ public static void main(String[] args){ int week = 5; switch (week){ case 1: System.out.println("monday"); break; case 2: System.out.println("tuesday"); break; case 3: System.out.println("wednesday"); break; case 4: System.out.println("thursday"); break; case 5: System.out.println("friday"); break; case 6: System.out.println("saturday"); break; case 7: System.out.println("sunday"); break; default: System.out.println("Invalid week");break; } } }
In this case, "friday" is printed to standard output. C:\javac>javac Switch.java C:\javac>java Switch friday One other point to note here is that the body of a switch statement is known as a switch block. The appropriate case gets executed when the switch statement evaluates its expression. Iteration The concept of Iteration has made our life much more easier. Repetition of similar tasks is what Iteration is and that too without making any errors. Until now we have learnt how to use selection statements to perform repetition. Now lets have a quick look at the iteration statements which have the ability to loop through a set of values to solve real-world problems. The for Statement
In the world of Java programming, the for loop has made the life much more easier. It is used to execute a block of code continuously to accomplish a particular condition. For statement consists of tree parts i.e. initialization, condition, and iteration. initialization : It is an expression that sets the value of the loop control variable. It executes only once. condition : This must be a boolean expression. It tests the loop control variable against a target value and hence works as a loop terminator. iteration : It is an expression that increments or decrements the loop control variable. Here is the form of the for loop: for(initialization; condition; iteration){ //body of the loop } For example, a sample for loop may appear as follows: int i; for (i=0; i<10; i++) System.out.println("i = " +i); In the above example, we have initialized the for loop by assigning the '0' value to i. The test expression, i < 100, indicates that the loop should continue as long as i is less than 100. Finally, the increment statement increments the value of i by one. The statement following the for loop will be executed as long as the test expression is true as follows: System.out.println("i = " + i); Well, we can add more things inside a loop. To do so we can use curly braces to indicate the scope of the for loop. Like, int i; for (i=0; i<10; i++) { MyMethod(i); System.out.println("i = " + i); } There is a simpler way to declare and initialize the variable used in the loop. For example, in the following code, the variable i is declared directly within the for loop: for (int i=0; i<100; i++) System.out.println("i = " +i); Lets see a simple example which will help you to understand for loop very easily. In this example we will print 'Hello World' ten times using for loop.
class printDemo{ public static void main(String[] args){ for (int i = 0; i<10; i++){ System.out.println("Hello World!"); } } }
Here is the output: C:\javac>javac printDemo.java C:\javac>java printDemo Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! After learning how to use a for loop, I would like to introduce another form of for loop to be used for iteration through collection and arrays. This form has enhanced the working of for loop. This is the more compact way to use a for loop. Here we will take an array of 10 numbers. int[] numbers = {1,2,3,4,5,6,7,8,9,10}; The following program, arrayDemo,displays the usage of for loop through arrays. It shows the variable item that holds the the current value from the array.
class arrayDemo{ public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } } }
Here is the output of the program C:\javac>javac arrayDemo.java C:\javac>java arrayDemo Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10 We would like to suggest to use this form of for loop if possible.
The while and do-while Statements Lets try to find out what a while statement does. In a simpler language, the while statement continually executes a block of statements while a particular condition is true. To write a while statement use the following form: while (expression) { statement(s) } Lets see the flow of the execution of the while statement in steps: 1. Firstly, It evaluates the condition in parentheses, yielding true or false. 2. Secondly, It continues to execute the next statement if the condition is false and exit the while statement. 3. Lastly, If the condition is true it executes each of the statements between the brackets and then go back to step 1. For example:
// This is the Hello program in Java class Bonjour{ public static void main (String args[]){ System.out.print("Bonjour "); // Say Hello int i = 0; // Declare and initialize loop counter while (i < args.length){ // Test and Loop System.out.print(args[i]); System.out.print(" "); i = i + 1; // Increment Loop Counter } System.out.println(); // Finish the line } }
In the above example, firstly the condition will be checked in the parentheses, while (i<args.length). If it comes out to be true then it will continue the execution till the last line and will go back to the loop again. However, if its false it will continue the next statement and will exit the while loop. The output is as follows: C:\javac>javac Bonjour.java C:\javac>java Bonjour Bonjour The while statement works as to for loop because the third step loops back to the top. Remember, the statement inside the loop will not execute if the condition is false. The statement inside the loop is called the body of the loop. The value of the variable
should be changed in the loop so that the condition becomes false and the loop terminates. Have a look at do-while statement now. Here is the syntax: do { statement(s) } while (expression); Lets tweak an example of do-while loop.
class DoWhileDemo{ public static void main (String args[]) { int i = 0; do{ System.out.print("Bonjour"); // Say Bonjour System.out.println(" "); i = i + 1; // Increment LoopCounter }while (i < 5); } }
In the above example, it will enter the loop without checking the condition first and checks the condition after the execution of the statements. That is it will execute the statement once and then it will evaluate the result according to the condition. The output is as follows: C:\javac>javac DoWhileDemo.java C:\javac>java DoWhileDemo Bonjour Bonjour Bonjour Bonjour Bonjour You must have noticed the difference between the while and do-while loop. That is the do-while loop evaluates its expression at the bottom of the loop. Hence, the statement in the do-while loop will be executed once. Jumping Sometimes we use Jumping Statements in Java. Using for, while and do-while loops is not always the right idea to use because they are cumbersome to read. Using jumping statements like break and continue it is easier to jump out of loops to control other areas of program flow. The break Statement We use break statement to terminate the loop once the condition gets satisfied. Lets see a simple example using break statement.
class BreakDemo{
public static void main(String[] args) { for (int i = 0; i < 5; i++) { System.out.println(i); if (i==3) { break ; } } }
In the above example, we want to print 5 numbers from 0 to 1 at first using for loop as shown. Then we put a condition that 'if i = = 3', the loop should be terminated. To terminate the loop after satisfying the condition we use break. It gives the following output: C:\javac>javac BreakDemo.java C:\javac>java BreakDemo 0 1 2 3 The break statement has two forms: labeled and unlabeled. You saw the labeled form in the above example i.e. a labeled break terminates an outer statement. However, an unlabeled break statement terminates the innermost loop like switch, for, while, or dowhile statement. Now observe the example of unlabeled form below. We have used two loops here two print '*'. In this example, if we haven't use break statement thus the loop will continue and it will give the output as shown below.
class BreaklabDemo1 { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.print("\n"); for (int j = 0; j<=i; j++) { System.out.print("*"); if (j==5) { // break; } } }
* ** *** **** ***** ****** ******* ******** ********* ********** C:\javac> However in the following example we have used break statement. In this the inner for loop i.e. "for (int j=0; j<=i; j++)" will be executed first and gets terminated there n then. Then the outer for loop will be executed i.e. "for (int i=0; i<10; i++)". And it will give the output as shown below.
class BreaklabDemo{ public static void main(String[] args){ for (int i = 0; i < 10; i++) { System.out.print("\n "); for (int j = 0; j<=i; j++){ System.out.print("*"); if (j==5) break; } } } }
Output: C:\javac>javac BreaklabDemo.java C:\javac>java BreaklabDemo * ** *** **** ***** ****** ****** ****** ****** ****** C:\javac> The continue statement The continue statement is used in many programming languages such as C, C++, java etc.
Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.
// Demonstrate continue. class Continue { public static void main(String args[]) { for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0) continue; System.out.println(""); } } }