Martrinex Learning Center
HOME CONTENTS
 
This website is underconstruction.
Author: Martin Sykes
Challenge: I have challenged myself to 1 article per day, and framework improvements! Enjoy
Challenge end: unknown

IF STATEMENT

A fundamental part of programming is check one variable against another and running some code depending on the outcome, this is usually done with the if statement.
In real life we make thousands of decisions based on if something equals do something about it eg: IF(wallet==empty) GOTO cash machine, or get a loan :-) IF statements always have to return true or false, and can compare multiple things.

Notice:
You may want to run my example codes, to do so create a new Java project named "examples", create a class named "examples" with static main as shown in tutorial hello world. Now you can simply paste the code from this site inside of
Code: public static void main(String[] args){
}
and run it!
Small example:
Code:
int intNum=0;
if(intNum==0){

intNum=5;
} else{

intNum=4;
}
System.out.println(intNum);
What did java just write to the console?
Answer: 5
Jave set intNum to equal 0
Checked if intNum was 0
It was so it ran intNum=5, ignoring the else code
The output was of course 5.
Why not change "int intNum=1;" and see what the output is?

I have seen people programming for years and only using IF statements to check 1 thing at a time and to never run any code if the condition isn't true (ie: else), so will try and go into more details:
The 3 checks:
1. 'IF' runs code if something is true.
2. 'ELSE' runs code if something is false.
3. 'ELSEIF' does another check if 1st thing is false.
Conditions:
'==' Most common checks if something IS something else.
'!=' Checks if something IS NOT something else.
'>' Checks if num1 is MORE THAN num2
'<' Checks if num1 is LESS THAN num2
'>=' Checks if num1 is MORE THAN OR EQUAL TO num2
'<=' Checks if num1 is LESS THAN OR EQUAL TO num2
Operators:
'&&' AND checks if condition1 AND condition2 are true
'||' OR checks if condition1 OR condition2 is true
Create checks:
All statements go in brackets, the bracket returns true or false for example IF(1==2) the brack (1==2) would = false.. because 1 is not 2 obviously.... You can have multiple brackets insite other brackets
Examples:
Else If:
Code:
// As a small sample say we wanted to add 1 to a low number, without using var=var+1
// The reason why I use this dumb example is people usually make this mistake:
int num=1;
if(num==1){

num=2;
}
if(num==2){

num=3;
}
if(num==3){

num=4;
}
System.out.println("Wrong:"+num);
/* so num was 1 and we wanted to add 1, the answers 2 right?
run it... it says 1+1=4 why?
the code ran down line by line, checking if num=x and adding 1, since it did not know otherwise it checked num with the new number and not the original incrementing 1 on every IF statement!
*/

// when making large programs mix-ups like this can happen, so maybe you should take a little time and experiment with else if...
num=1;
if(num==1){

num=2;
} else if(num==2){

num=3;
} else if(num==3){

num=4;
}
System.out.println("Correct:"+num);
Different ways:
Code:
int num=5;


/*Check if num is between 3 and 7 (we know its 5 but the computer does not...) num is a integer (whole number so all 3 samples are correct.*/

if (num > 3 && num < 7) System.out.println("it is between");

if (num >= 4 && num <= 6) System.out.println("it is between");

if (num==4 || num==5 || num==6) System.out.println("it is between");

Question: If num is a float (fraction) only one of the above statements would be correct, but which one?
[click for answer]
Comparing Strings:
Code:
/* The designers of Java definatly had something against strings, apparently checking one string against another like all the other languages (if string1=="const") was too difficult for them... consequently it does not work!

Introducing:
int answer = string1.compareTo(string2)
place the first string instead of string1 and the second instead of string2, java then treats the two as binary and subtracts them from one another in english if they are the same the answer would be 0, so how to put this in an if statement?
*/

String name="mr joe foo";
if(name.compareTo("mrs joe foo")==0){

System.out.println("hello mrs joe foo");
}
Double if:
Code:
// say you wanted to check someones forename and surname
String forename="martin";
String surname="sykes";
// you could do
if(forename=="martin"){

if(surname=="sykes"){

System.out.println("Hello website owner");
}
}
// or you could use the && operator
if(forename=="martin" && surname=="sykes"){

System.out.println("Easier to read and less code... but BOTH are correct");
}
Using brackets:
Code:
// say you wanted to check for 2 members of the same family
// martin sykes or steven sykes
String forename="martin";
String surname="foo";
// if martin or steven and surname = sykes
if(forename.compateTo("martin")==0 || forename.compareTo("steven")==0 && surname.compareTo("sykes")==0){

System.out.println("but martin foo is not martin sykes?");
}
// you'll notice it thought martin foo was martin sykes
// java read it as if forename=martin do code, or if forename=steven and surname=sykes do code...
// simply place brackets around the 'or' section to get that to read first instead
if((forename.compateTo("martin")==0 || forename.compareTo("steven")==0) && surname.compareTo("sykes")==0){

System.out.println("Now it works!!!");
}

Excersize

Start a new java project, called HelloWorld4 with a main class named HelloWorld4 and static main, you should know the deal by now....
Copy and paste this code into your new project: (note this is helloworld3 code)
Code:
import java.io.*;
public class HelloWorld4 /* note: changed from 3 to 4 */ {

public static void main(String[] args) throws IOException {

/* Expanding the HelloWorld Sample */

// Original Hello World Using a variable
String strHelloWorld="Hello World";
System.out.println(strHelloWorld);

// Joining multiple names and displaying
// try replacing with your names!
String strTitle = "";
String strForeName = "";
String strSurName = "";
String strFullName = ""; //<-- set this automaticaly

/* NEW STUFF */
InputStreamReader isr = new InputStreamReader( System.in );
BufferedReader stdin = new BufferedReader( isr );

System.out.println("Enter your title: (Mr/Mrs/Dr)");
strTitle=stdin.readLine();
System.out.println("Enter your forename:");
strForeName=stdin.readLine();
System.out.println("Enter your surname:");
strSurName=stdin.readLine();
/* OLD STUFF */

// join names
strFullName = strTitle+" "+strForeName+" "+strSurName;
/* The '+' symbol joins strings and adds numbers! To join a number use ""+ more later */
// show result
System.out.println("Hello: "+strFullName);
}
}
Task:
We are of course going to add IF statements to the code above to check the user input for two things:
1. for your name to say 'hello new java programmer'
2. for someone you don't like to say 'name go away you are not welcome.'
To keep things easier put your code after strFullName = '' and compare your names with strFullName, that way you only have to worry about 1 variable instead of 3, eg: if(strFullName=="mr forename surname"){ /* code */ }"
Answer:
[click for answer]

Add Comment

Help the web master by commenting on the tutorials, thankyou.
Name:
Email: (this will not be shown)
Comment:
  Send email to admin, don't post.

 

Comments

Nobody has commented on this article.
Be the first, the webmaster needs comments good or bad to improve this site.



Copyright (c) 2008, Martin Sykes.
Learning Center is a branch of Martrinex Systems, Martrinex.net
Do not copy any materials from this site without permission from the auther.
Martrinex Learning Center[X]
  Introduction Beginner Intermediate

Important useful well commented source codes
Please read the import tutorial to know how to use them.

Source