Learning the operators of the Java programming language is a good place to start.
An operator is a function that has a special symbol and is invoked by using that symbol with an expression.
There are several operators in Java that we using to code.
* Arithmetic Operators
perform addition(+), subtraction(-), multiplication(*), and division(/).
There's a good chance you'll recognize them by their counterparts in basic
mathematics. The only symbol that might look new to you is "%", which divides
one operand by another and returns the remainder as its result.
Example Program for Arithmetic Operators:
class ArithmeticOperators {
public static void main (String[] args){
int result = 1 + 2; // result is now 3
System.out.println(result);
result = result - 1; // result is now 2
System.out.println(result);
result = result * 2; // result is now 4
System.out.println(result);
result = result / 2; // result is now 2
System.out.println(result);
result = result + 8; // result is now 10
result = result % 7; // result is now 3
System.out.println(result);
}
}
* Assignment Operator
Used to assign a variable with a value. You can also combine the arithmetic
operators with the simple assignment operator to create compound assignments.
For example, x+=1; and x=x+1; both increment the value of x by 1.
Example Program for Assignment Operators:
class AssignmentOperator {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.
* Logical (Boolean) Operators
Used to perform standard logical operations on Boolean values
&&
Logical-AND
||
Logical-OR
!
Logical-NOT
* Relational Operators
Relational operators determine if one operand is greater than, less than,
equal to, or not equal to another operand. The majority of these operators
will probably look familiar to you as well. Keep in mind that you must use
"==", not "=", when testing if two primitive values are equal.
== equal to Ex: 2==3 =False
!= not equal to Ex: 2!=3 =True
> greater than Ex: 2>3 =False
>= greater than or equal to EX: 2>=3 =False
< less than Ex: 2<3 =True
<= less than or equal to Ex: 2<=3 =True
* Conditional Operators
Act as a shorthand for if-then-else
Conditional Operator ?:
This Operator has the form:
(condition)?(value if true):(value if false)
The condition is evaluated, and if it is true value if true is returned,
otherwise value if false is returned.
Example :
If a=10 and b=2 were integers, the following would return 10.
(a>b)?a:b
Conditional Operator is a short hand operator for "if-then-else"
Sunday, July 26, 2009
Java Operators
Subscribe to:
Posts (Atom)
