Posted by
Zhullyblog
on
- Get link
- X
- Other Apps
The If statement generally is used to test a condition. It is used to check whether a condition is true or false before executing a statement.
For example, you might want to check if x is equal to y , if yes then add x and y or otherwise.
There are other examples like -
You might want to allow user to only register their profile only if they are of certain age. And the example goes on and on.
The if statement isn't just about testing alone, I would say it is needed in every program. The truth is, you can't just let users enter anything they like, there has to be rules and regulations, for example, if you have a form that allows user to enter their username and phones number, the colon for phone must accept only numbers and if the user does not follow up with the rules, an error must be displayed. This is where if statement is in use.
Let's see how it works in Java
Syntax for If statement
if ( expression ) {
//Statement ;
}
Examples
//by Zhullyblog
public class sample{
public static void main(String[] args) {
int num = 10;
//test the statement
if (num > 1){
System.out.println("The number is greater than 1");
}
}
}
Screenshot
Result
If....else statement
The if else statement is used to test and also return result if the condition turns out to be false.
Syntax
if ( expression ){
//Statement ;
}
else {
//Statement;
}
Examples
//by Zhullyblog
public class sample{
public static void main(String[] args) {
int num = 10;
//test the statement
if (num > 1){
System.out.println("The number is greater than 1");
}
else {
System.out.println("The number is less than 1");
}
}
}
Screenshot
Result
Let's move
Introduction to Java programming
How to declare a variable in Java
If, if..else statement in Java
Please share
Comments
Post a Comment