Sei sulla pagina 1di 10

If else in JAVA

Java supports the usual logical conditions from mathematics:


 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
 Use if to specify a block of code to be executed, if a specified condition is true
 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

In the example below, we test two values to find out if 20 is greater than 18. If the condition
is true, print some text:

Example
if (20 > 18) {
System.out.println("20 is greater than 18");
}

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.

Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
Loops in Java
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly
while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their
syntax and condition checking time.
1. while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given
Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax :
2. while (boolean condition)
3. {
4. loop statements...
5. }
Flowchart:

 While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are
executed otherwise first statement following the loop is executed. For this reason it is also called Entry
control loop
 Once the condition is evaluated to true, the statements in the loop body are executed. Normally the
statements contain an update value for the variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate while loop
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
System.out.println("Value of x:" + x);

// Increment the value of x for


// next iteration
x++;
}
}
}
Output:
Value of x:1
Value of x:2
Value of x:3
Value of x:4
6. for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement
consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to
debug structure of looping.
Syntax:
7. for (initialization condition; testing condition;
8. increment/decrement)
9. {
10. statement(s)
11. }
Flowchart:

1. Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already
declared variable can be used or a variable can be declared, local to loop only.
2. Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also
an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
3. Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
4. Increment/ Decrement: It is used for updating the variable for next iteration.
5. Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate for loop.
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}
Output:
Value of x:2
Value of x:3
Value of x:4
Enhanced For loop
Java also includes another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to
iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to
iterate through the elements in sequential manner without knowing the index of currently processed element.
Also note that the object/variable is immutable when enhanced for loop is used i.e it ensures that the values in the
array can not be modified, so it can be said as read only loop where you can’t update the values as opposite to
other loops where values can be modified.
We recommend using this form of the for statement instead of the general form whenever possible.(as per JAVA
doc.)
Syntax:
for (T element:Collection obj/array)
{
statement(s)
}
Lets take an example to demonstrate how enhanced for loop can be used to simpify the work. Suppose there is an
array of names and we want to print all the names in that array. Let’s see the difference with these two examples
Enhanced for loop simplifies the work as follows-
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate enhanced for loop
public class enhancedforloop
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};

//enhanced for loop


for (String x:array)
{
System.out.println(x);
}

/* for loop for same function


for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}
Output:
Ron
Harry
Hermoine
12. do while: do while loop is similar to while loop with only difference that it checks for condition after executing the
statements, and therefore is an example of Exit Control Loop.
Syntax:
13. do
14. {
15. statements..
16. }
17. while (condition);

Flowchart:

0. do while loop starts with the execution of the statement(s). There is no checking of any condition for the
first time.
1. After the execution of the statements, and update of the variable value, the condition is checked for true or
false value. If it is evaluated to true, next iteration of loop starts.
2. When the condition becomes false, the loop terminates which marks the end of its life cycle.
3. It is important to note that the do-while loop will execute its statements atleast once before any condition is
checked, and therefore is an example of exit control loop.
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate do-while loop
class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}
Output:
Value of x: 21
Pitfalls of Loops
1. Infinite loop: One of the most common mistakes while implementing any sort of looping is that that it may not ever
exit, that is the loop runs for infinite time. This happens when the condition fails for some reason.
Examples:
filter_none
edit
play_arrow
brightness_4
//Java program to illustrate various pitfalls.
public class LooppitfallsDemo
{
public static void main(String[] args)
{

// infinite loop because condition is not apt


// condition should have been i>0.
for (int i = 5; i != 0; i -= 2)
{
System.out.println(i);
}
int x = 5;

// infinite loop because update statement


// is not provided.
while (x == 5)
{
System.out.println("In the loop");
}
}
}
2. Another pitfall is that you might be adding something into you collection object through loop and you can run out of
memory. If you try and execute the below program, after some time, out of memory exception will be thrown.
filter_none
edit
play_arrow
brightness_4
//Java program for out of memory exception.
import java.util.ArrayList;
public class Integer1
{
public static void main(String[] args)
{
ArrayList<Integer> ar = new ArrayList<>();
for (int i = 0; i < Integer.MAX_VALUE; i++)
{
ar.add(i);
}
}
}
Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at article.Integer1.main(Integer1.java:9)

Algorithm 3 Example
Flow Chart
A flowchart is a visual representation of the sequence of steps and decisions needed to perform a process. Each step in the
sequence is noted within a diagram shape. Steps are linked by connecting lines and directional arrows. This allows anyone to view
the flowchart and logically follow the process from beginning to end.

A flowchart is a powerful business tool. With proper design and construction, it communicates the steps in a process very effectively
and efficiently.

Arrays in Java
An array is a group of like-typed variables that are referred to by a common name.Arrays in Java work differently than they do in
C/C++. Following are some important point about Java arrays.
 In Java all arrays are dynamically allocated.(discussed below)
 Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find
length using sizeof.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered and each have an index beginning from 0.
 Java array can be also be used as a static field, a local variable or a method parameter.
 The size of an array must be specified by an int value and not long or short.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable and java.io.Serializable.
Array can contains primitives data types as well as objects of a class depending on the definition of array. In case of primitives data
types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap
segment.

Creating, Initializing, and Accessing an Array


One-Dimensional Arrays :
The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the name. type declares the element type of the array. The element type
determines the data type of each element that comprises the array. Like array of int type, we can also create an array of other
primitive data types like char, float, double..etc or user defined data type(objects of a class).Thus, the element type for the array
determines what type of data the array will hold.
Example:
// both are valid declarations
int intArray[];
or int[] intArray;

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

// an array of references to objects of


// the class MyClass (a class created by
// user)
MyClass myClassArray[];

Object[] ao, // array of Object


Collection[] ca; // array of Collection
// of unknown type
Although the above first declaration establishes the fact that intArray is an array variable, no array actually exists. It simply tells to
the compiler that this(intArray) variable will hold an array of the integer type. To link intArray with an actual, physical array of
integers, you must allocate one using new and assign it to intArray.
Instantiating an Array in Java
When an array is declared, only a reference of array is created. To actually create or give memory to array, you create an array like
this:The general form of new as it applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of
array variable that is linked to the array. That is, to use new to allocate an array, you must specify the type and number of elements
to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
Note :
1. The elements in the array allocated by new will automatically be initialized to zero(for numeric types), false (for
boolean), or null (for reference types).Refer Default array values in Java
2. Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you
must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all
arrays are dynamically allocated.
Array Literal
In a situation, where the size of the array and variables of array are already known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
 The length of this array determines the length of the created array.
 There is no need to write the new int[] part in the latest versions of Java
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array
can be accessed using Java for Loop.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
Implementation:
filter_none
edit
play_arrow
brightness_4
// Java program to illustrate creating an array
// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
}
}
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Potrebbero piacerti anche