Java : Math with variables
Math on Java
Java can perform math like 4 + 5. It can perform addition, subtraction, multiplication, and division. Java also has it’s own math symbols: +, -, *, /, == (equal to), < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), != (not equal to).
boolean math = 3 + 5 >= 48 / 4
The boolean is false because 3 + 5 = 8. 48 / 4 = 12. 8 is not greater than or equal to 12, so it is false.
The program
package com.lessons;
public class Math{
//This class performs math
//adds two numbers and prints out the sum
public static int add(int x, int y) {
int answer = x + y; // The variable answer is equal to the sum of the two variables x and y
// x and y are the arguments of the method, this means that int x and int y will be used in the method
return answer; //Returns the integer answer
}
public static void main(String[] args) {
int sum = add( 5, 6); //
// The int variable sum is equal to 5 + 6
// In the add method, answer = variable x + variable y, so when sum gets called, x becomes 5 and y becomes 6
// All you do is call the add method and replace int x and int y in the parenthesis with numbers.
System.out.println( sum);
//5 + 6 = 11, so 11 will get printed on the screen
}
}
Leave a comment
You must be logged in to post a comment.