Posts

Showing posts with the label Java if else

Java If else

In this blog post, I will be explaining how the if else statement works in Java. What is if-else The if-else statement is used to check for a condition. If the condition specified after the “if” keyword is true, the code following the if keyword is executed. If the code following the if keyword is false, the code following the else keyword is executed. Syntax if(condition){//some code here}else{ // this part is optional//some code here} Code Sample 1 Consider the following code snippet: int a = 20;int b = 15;if(a > b){System.out.println("a is greater than b");}else {System.out.println("a is less than b");} Variables called a and b are declared and initialized to 20 and 15 respectively The if keyword is followed by a condition i.e. a > b Since a > b is true, the code within the if block is executed If a > b was false, the code within the else block would have been executed   When this above code is executed, it will print the followi...

How to find the largest number in an array

The following code demonstrates how to find the largest number in an array:   package demo;public class LargestNumberDemo {public static void main(String[] args) {Integer[] intArr = {45,21,88,210,550,1,34};int max = 0;for(int num:intArr){if(num > max)max = num;}System.out.println("Biggest number is "+max);}}   So the for loop iterates through the array. Initially, the variable max is set to 0. Each number is compared with ‘max’ and if it is greater than max, then it is assigned to ‘max’. This process is repeated till all the elements in the array are exhausted.   This will print the following output: Biggest number is 550   You can use this code to find the largest number from any Collection type like Set or List.