Tuesday, March 30, 2010
The while Loop
The C# while Loop :
Essentially, the while loop repeats a set of tasks until a specified condition is met. The while loop syntax is defined follows:
while (''condition'')
{
// C# statements go here
}
where condition is an expression that will return either true or false and the // C# statements go here comment represents the C# code to be executed while the condition expression is true. For example:
int myCount = 0;
while ( myCount <>
{
myCount++;
}
In the above example, the while expression will evaluate whether the myCount variable is less than 100. If it is already greater than 100 the code in the braces is skipped and the loop exits without performing any tasks.
If, on the other hand, myCount is not greater than 100 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of myCount. This process repeats until the value of myCount is greater than 100, at which point the loop exits.
The Switch ...case Construct
In this lesson we are going to learn about a conditional statement called the switch statement. Usually if and if else [color=#3333FF]statements are taught before switch statements. Although these are very useful, I find the switch to be easier and more fun to use.
The program written below is very similar to the previous program where the user is asked to enter their name, however now the program will look for four distinct string values and ti will generate output according to the string entered. Here are the things to observe when reading and replicating this program.
1.) 2 string variables are declared (greeting and fullName)
2.) A value is assigned using our Console.ReadLine() method. (Point where we insert the value.)
3.) the value of the variable greeting depends on the value entered for the variable fullName
4.) The program is case sensitive. Basically this is because different case letters have different values. So a lower case t will not evaluate the same as an upper case T. So ulitmately what does this mean. Well let's if you entered george bush as opposed to George Bush, you would get the default greeting because the program would not recognize your lower case entry of george bush as George Bush. If it does not make sense, run the program and change the case. You will see what I mean.
5.) Lastly, the default option is included in the case statement for the instances where neither of the output meets any of the criteria of the case statement.
CODE:
using System;
namespace ConsoleApplication
{
///
/// Testing out the case Statement
///
class switchStatement
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main(string[] args)
{
string fullName, greeting;
Console.Write("Please enter your name: ");
fullName = Console.ReadLine();
switch (fullName)
{
case "YOUR NAME HERE":
greeting = "You are the best!!";
break;
case "Bill Gates":
greeting = "You are super wealthy!";
break;
case "George Bush":
greeting = "hmmm????";
break;
case "Kenneth Lay":
greeting = "How is Court Going?";
break;
default:
greeting = "I'm sorry I did not recognize you!";
break;
}//end switch statement
Console.WriteLine();
Console.WriteLine(greeting);
Console.WriteLine();
Console.WriteLine("Press [ENTER] to Exit");
Console.ReadLine();
}//end Main
}//end class "switchStatement
}//end namespace
As I might have mentioned on my previous post I am using Visual Studio. I believe the Express version is out on the web for free. However you might need to install NetFramework before you proceed to install VS.
Also, just like the previous program, an adobe file will be attached with the source code. variables and comments are all color coded.
The if ...else Construct
Copy
bool flagCheck = true;
if (flagCheck == true)
{
Console.WriteLine("The flag is set to true.");
}
else
{
Console.WriteLine("The flag is set to false.");
}
Remarks:
If the expression in the parenthesis is evaluated to be true, then the Console.WriteLine("The boolean flag is set to ture."); statement is executed. After executing the if statement, control is transferred to the next statement. The else is not executed in this example.
If you wish to execute more than one statement, multiple statements can be conditionally executed by including them into blocks using {} as in the example above.
The statement(s) to be executed upon testing the condition can be of any kind, including another if statement nested into the original if statement. In nested if statements, the else clause belongs to the last if that does not have a corresponding else.
For example:
if (x > 10)
if (y > 20)
Console.Write("Statement_1");
else
Console.Write("Statement_2");
In this example, Statement_2 will be displayed if the condition (y > 20) evaluates to false. However, if you want to associate Statement_2 with the condition (x >10), use braces:
if (x > 10)
{
if (y > 20)
Console.Write("Statement_1");
}
else
Console.Write("Statement_2");
Example 1:
In this example, you enter a character from the keyboard and the program checks if the input character is an alphabetic character. If so, it checks if it is lowercase or uppercase. In each case, the proper message is displayed.
// statements_if_else.cs
// if-else example
using System;
class IfTest
{
static void Main()
{
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
{
Console.WriteLine("The character is lowercase.");
}
else
{
Console.WriteLine("The character is uppercase.");
}
}
else
{
Console.WriteLine("Not an alphabetic character.");
}
}
}
Input:
2
Sample Output:
Enter a character: 2
The character is not an alphabetic character.
Additional sample might look as follows:
Run #2:
Run #3:
It is also possible to extend the if statement to handle multiple conditions using the following else-if arrangement:
This example checks if the input character is lowercase, uppercase, or a number. Otherwise, it is not an alphanumeric character. The program makes use of the else-if ladder.
// statements_if_else2.cs
// else-if
using System;
public class IfTest
{
static void Main()
{
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsUpper(c))
{
Console.WriteLine("Character is uppercase.");
}
else if (Char.IsLower(c))
{
Console.WriteLine("Character is lowercase.");
}
else if (Char.IsDigit(c))
{
Console.WriteLine("Character is a number.");
}
else
{
Console.WriteLine("Character is not alphanumeric.");
}
}
}
Input
E
Sample Output
Copy
Enter a character: E
The character is uppercase.
Additional sample runs might look as follows:
Run #2
Copy
Enter a character: e
The character is lowercase.
Run #3:
Copy
Enter a character: 4
The character is a number.
Run #4:
Copy
Enter a character: $
The character is not alphanumeric.
Logical Operators in C#
Operator | Description |
== | equal to |
> | greater then |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
! | not |
!= | not equal to |
&& | logical AND |
|| | logical OR |
Logical Operators:
& Bitwise AND
The & operator compares two values with a bitwise AND function. You use the & operator with two operands, like this:
Evaluate a & b
Each of the operands a and b is converted to a binary number, and each of their bits is compared; that is, bit 1 of a is compared with bit 1 of b, and so on. When two corresponding bits are both 1, bitwise AND combines them to produce 1. When one or both of the corresponding bits are 0, bitwise AND combines them to produce 0.
For example, if you enter
Evaluate 25 & 77
25 and 77 are combined with a bitwise AND, and the result is 9.
~ Bitwise NOT
In a logical expression, the ~ operator computes the binary negative of a number. The binary negative is calculated by converting a character's 0 bits to 1 bits and its 1 bits to
0 bits.
For example, to find the binary negative of 5, you could enter
Evaluate ~5
The result of this command is -6.
| Bitwise OR
The | operator compares two values with a bitwise OR function. You use the | operator with two operands, like this:
Evaluate a | b
Each of the operands a and b is converted to a binary number, and each of their bits
is compared; that is, bit 1 of a is compared with bit 1 of b, and so on. When two corresponding bits are both 0, bitwise OR combines them to produce 0. When either of the corresponding bits is 1, bitwise OR combines them to produce 1.
For example, if you enter
Evaluate 25 | 77
25 and 77 are combined with a bitwise OR, and the result is 93.
^ Bitwise XOR
The ^ operator compares two values with a bitwise XOR (that is, a bitwise exclusive OR) function. You use the ^ operator with two operands, like this:
Evaluate a ^ b
Each of the operands a and b is converted to a binary number, and each of their bits is compared; that is, bit 1 of a is compared with bit 1 of b, and so on. When one of the bits--but not both--is 1, bitwise XOR combines them to produce 1. When both bits are 0 or when both bits are 1, bitwise XOR combines them to produce 0.
For example, if you enter
Evaluate 25 ^ 77
25 and 77 are combined with a bitwise XOR, and the result is 84.
+= Increment a variable
The += character is used only with the Evaluate command and adds the value on the right side of the expression to the variable on the left side. For example, in the command
Evaluate myVar += 2
the value of {myVar} is increased by 2. In the Evaluate command, you do not need to place the variable name inside braces because the command does not extract the value of the variable. For more information, see the { } Enclose a variable entry.
-= Decrement a variable
The -= character is used only with the Evaluate command and subtracts the value on the right side of the expression from the variable on the left side. For example, the command
Evaluate myVar -= 2
decreases the value of {myVar} by 2. In the Evaluate command, you do not need to place the variable name inside braces because the command does not extract the value of the variable. For more information, see the { } Enclose a variable entry.
== Equal to (strings, numbers, and variables)
The character == means "equals" when it compares text strings, arithmetic values, or variables that contain text strings or arithmetic values. If the value of the expressions are equal, the command returns 1, meaning true; if the expressions are not equal, the command returns 0, meaning false.
The command
Evaluate (3 * 4 * 27) == (6 * 9 * 3 * 2)
computes the values of each side and returns the value 1, for true. Note that arithmetic expressions use integer arithmetic. For example, the expression 5 2 yields 2, not 2.5.
The command
Evaluate {a} == 0
checks whether the current value of the variable {a} is 0 and returns 1 or 0.
When used with a text string, the match is case sensitive; for example,
Evaluate "theWorld" == "theworld"
returns 0.
=~ Equivalent to (patterns)
The =~ operator is used with the Evaluate command to evaluate whether a text string, or a variable that contains a text string, matches a regular expression. You must place the left operand within double quotation marks and the right operand within forward slashes. For example, the following command evaluates the strings yes and no, finds that they are not the same, and displays a 0, meaning false:
Evaluate "yes" =~ /no/
You can also use the =~ character with variables, as in
Evaluate "{a}" =~ /{b}/
which compares the current values of the variables {a} and {b}. If {a} and {b} have the same value, Evaluate returns 1, meaning true. If {a} and {b} do not have the same value, Evaluate returns 0, meaning false. The command
Evaluate "{a}" =~ /$[0-9a-f]+/
checks whether the variable {a} contains a hexadecimal number. If {a} does, Evaluate returns 1. If {a} does not contain a hexadecimal number, Evaluate returns 0.
> Greater than
In arithmetic expressions, the > character means "greater than." You can use the > character to compare the values of numbers or variables. For example, the command
Evaluate 5 > 10
evaluates whether 5 is greater than 10 and then displays 0, meaning false, in the active window. Likewise, the command
Evaluate {a} > {b}
evaluates the current values of {a} and {b} and then displays 0 (false) or 1 (true) in the active window. If you enter the commands
Set a 4
Set b 3
Evaluate {a} > {b}
Evaluate displays 1 in the active window.
>= Greater than or equal to
The >= character means "greater than or equal to" and has the same meaning as the ≥ character.
≥ Greater than or equal to [Option-.]
The ≥ character means "greater than or equal to" and has the same meaning as the >= character.
You can use the ≥ character to compare the values of numbers or variables. For example, the command
Evaluate 15 ≥ 10
evaluates whether 15 is greater than or equal to 10 and then displays 1 (true) in the active window. Likewise, the command
Evaluate {a} ≥ {b}
compares the current values of the variables {a} and {b}, and displays either 0 (false) or 1 (true) in the active window. If you enter the commands
Set a 100
Set b 88
Evaluate {a} ≥ {b}
Evaluate displays 1 in the active window.
<>
In arithmetic expressions, the < character means "less than." You can use the < character to compare the values of numbers or variables. For example, the command
Evaluate 5 < 10
evaluates whether 5 is less than 10, and then displays 1, meaning true, in the active window. Likewise, the command
Evaluate {a} < {b}
evaluates the current values of the variables {a} and {b} and displays either 0 (false) or 1 (true) in the active window. If you enter the commands
Set a 7
Set b 77
Evaluate {a} < {b}
Evaluate displays 1 in the active window.
<= Less than or equal to
The <= character means "less than or equal to" and has the same meaning as the ≤ character.
≤ Less than or equal to [Option-,]
The ≤ character means "less than or equal to" and has the same meaning as the <= character.
You can use the ≤ character to compare the values of numbers or variables. For example, the command
Evaluate 15 ≤ 10
evaluates whether 15 is less than or equal to 10 and then displays 0, which means false, in the active window. Likewise, the command
Evaluate {a} ≤ {b}
compares the current values of the variables {a} and {b} and displays either 0 or 1 in the active window. If you enter the commands
Set a 88
Set b 100
Evaluate {a} ≤ {b}
Evaluate displays 1 in the active window.
&& Logical AND
The && operator means logical AND and has the same meaning as the AND operator.
AND Logical AND
The AND operator means logical AND and has the same meaning as the && operator.
Logical AND is based on the principle that if both sides of an expression are true (that is, not equal to 0), then the expression is true. If either side or both sides of the expression are false (that is, equal to 0), the expression is false.
For example, the command
Evaluate 2 AND 3
returns 1, or true. But the command
Evaluate 2 AND 0
returns 0. You can use the AND operator to check whether the value of a variable is 0. For example, if you enter
Evaluate {Status} AND {Value}
Evaluate returns 0 if either variable is currently set to 0.
! Logical NOT
In arithmetic expressions, the ! operator means logical NOT and has the same meaning as the ¬ operator and the NOT operator.
¬ Logical NOT [Option-L]
In arithmetic expressions, the ¬ operator means logical NOT and has the same meaning as the ! operator and the NOT operator.
The ¬ operator is also used in selection expressions (see the ¬ Not in the following list entry).
NOT Logical NOT
In arithmetic expressions, the NOT operator means logical NOT and has the same meaning as the ¬ and ! operators. Logical NOT evaluates whether a number or variable has a value of 0. If the character or variable has a value of 0, the result of the command is 1, which means true. If the character or variable has a value other than 0, the result of the command is 0, which means false.
For example, the command
Evaluate NOT 100
displays 0 in the active window. But the command
Evaluate NOT 0
displays 1.
|| Logical OR
The || operator means logical OR and has the same meaning as the OR operator.
OR Logical OR
The OR operator means logical OR and has the same meaning as the || operator.
Logical OR is based on the principle that if either side of a statement is true (that is, not equal to 0), the statement is true. If both sides of a statement are false (that is, equal to 0), then the statement is false.
For example, the command
Evaluate 2 OR 0
returns 1, or true. However, the command
Evaluate 0 OR 0
returns 0, or false. You can use the OR operator to check whether the value of a variable is 0. For example, if you enter
Evaluate {checking} OR {savings}
Evaluate returns 0 only if the current values of both {checking} and {savings} are 0. If either {checking} or {savings} has a positive or negative value, Evaluate returns 1.
!= Not equal to (strings, numbers, and variables)
The != operator means "not equal to" and is used between two numbers or variables in an expression. The != operator has the same meaning as the <> and ≠ operators.
<> Not equal to
The <> operator means "not equal to" and is used between two numbers or variables in an expression. The <> operator has the same meaning as the ≠ and the != operators.
≠ Not equal to [Option-=]
The ≠ operator means "not equal to" and is used between two numbers or variables in an expression. The operator has the same meaning as the != and the <> operators.
If the two sides of the expression are not equal, the command returns 1, meaning true. If the two sides are equal, the command returns 0, meaning false.
For example, the command
Evaluate 2 ≠ 5
is 1, or true. If you enter a command like
Evaluate {a} ≠ {b}
the command checks the current values of the variables {a} and {b}, determines whether they are not equal, and returns 1 for true, or 0 for false.
!~ Not equivalent to (patterns)
The !~ character is used with the Evaluate command to evaluate whether a text string or a variable that contains a text string matches a regular expression. When you use the !~ character between two operands, you must place the left operand within double quotation marks and the right operand within forward slashes. For example, the following command evaluates the strings yes and no, finds that they are not the same, and displays a 1, meaning true:
Evaluate "yes" !~ /no/
You can also use the !~ character with variables, as in
Evaluate "{a}" !~ /{b}/
This example compares the current values of the variables {a} and {b}. If {a} and {b} have the same value, Evaluate returns 0, meaning false. If {a} and {b} do not have the same value, Evaluate returns 1, meaning true. The command
Evaluate "{a}" !~ /$[0-9a-f]+/
returns 1 (for true) if the variable {a} does not contain a hexadecimal number.
<< Shift left
The << operator performs a shift left function on a number. A shift left function shifts a value's bits n characters to the left. The bits that are shifted out through the high-order bit are lost. For example, if you enter
Evaluate 3 << 1
the bit pattern in the number 3 is shifted left by one place. In other words, the bit pattern
... 0000 0011 #the value 3
becomes
... 0000 0110 #the value 6
Shifting left one place actually has the effect of multiplying a value by 2.
>> Shift right
The >> operator performs a shift right function on a number. A shift right function shifts a value's bits n characters to the right. The bits moved out of the low-order bit are lost, and the bits shifted in to the high-order bits on the left have a value of 0. For example, if you enter
Evaluate 3 >> 1
the bit pattern
... 0000 0011
becomes
... 0000 0001
which has a value of 1. The right shift is a logical right shift, because bits with a value of 0 are moved into the high-order bits.
Comparison Operators
Example | Name | Result |
---|---|---|
$a == $b | Equal | TRUE if $a is equal to $b. |
$a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type. (PHP 4 only) |
$a != $b | Not equal | TRUE if $a is not equal to $b. |
$a <> $b | Not equal | TRUE if $a is not equal to $b. |
$a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type. (PHP 4 only) |
$a < $b | Less than | TRUE if $a is strictly less than $b. |
$a > $b | Greater than | TRUE if $a is strictly greater than $b. |
$a <= $b | Less than or equal to | TRUE if $a is less than or equal to $b. |
$a >= $b | Greater than or equal to | TRUE if $a is greater than or equal to $b. |
Another conditional operator is the "?:" (or ternary) operator, which operates as in C and many other languages.
(expr1) ? (expr2) : (expr3);Comparison with Various Types:
This expression evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Type of Operand 1 | Type of Operand 2 | Result |
---|---|---|
null or string | string | Convert NULL to "", numerical or lexical comparison |
bool or null | anything | Convert to bool , FALSE < TRUE |
object | object | Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation |
string , resource or number | string , resource or number | Translate strings and resources to numbers, usual math |
array | array | Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example) |
array | anything | array is always greater |
object | anything | object is always greater |
Example #1 Transcription of standard array comparison
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
if (count($op1) <> count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) { return -1; } elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>
Ternary Operator:
Another conditional operator is the "?:" (or ternary) operator.
Example #2 Assigning a default value
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.
Example #3 Non-obvious Ternary Behaviour
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
Comparison operators test whether two expressions are the same. Comparison operators can be used on all expressions except expressions of the text, ntext, or image data types. The following table lists the Transact-SQL comparison operators.
Operator | Meaning |
---|---|
Equal to | |
Greater than | |
Less than | |
Greater than or equal to | |
Less than or equal to | |
Not equal to | |
Not equal to (not ISO standard) | |
Not less than (not ISO standard) | |
Not greater than (not ISO standard) |
Unary Operators
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
The following program, UnaryDemo, tests the unary operators:
class UnaryDemo {
public static void main(String[] args){
int result = +1; // result is now 1
System.out.println(result);
result--; // result is now 0
System.out.println(result);
result++; // result is now 1
System.out.println(result);
result = -result; // result is now -1
System.out.println(result);
boolean success = false;
System.out.println(success); // false
System.out.println(!success); // true
}
}
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i); // 4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
The unary operators requires only one operand to perform different kind of operations such as increasing/decreasing a value, negating an expression, or inverting a boolean value. These operators can not be used with final variables. There are different types of unary operators mentioned in the table given below:
Symbol | Name of the Operator | Operation | Example |
+ | Unary plus operator | indicates positive value (however, numbers are positive without this) | int number = +1; |
- | Unary minus operator | negates an expression | number = - number; |
++ | Increment operator | increments a value by 1 | number = ++ number; |
-- | Decrement operator | decrements a value by 1 | number = -- number; |
! | Logical compliment operator | inverts a boolean value |
I. Unary Plus (+) Operator:
Unary plus operator (+) indicates positive value. This (+) operator is used to perform a type conversion operation on an operand. The type of the operand must be an arithmetic data type i.e. if a value of the integer operand is negative then that value can be produced as a positively applying unary plus (+) operator. For example, lets see the expressions shown as:
int x = 0;
int y = (-25);
x = (+y);
In this expression, a negative value is assigned to the variable "y". After applying unary plus (+) operator on the operand "y", the value becomes 25 which indicates it as a positive value.
However a number is positive without using unary plus (+) operator, if we have initially assigned it positively into the operand in the program.
II. Unary minus (-) Operator:
Unary minus operator (-) indicates negative value and differ from the unary plus operator. This (-) operator is also used to perform a type conversion operation on an operand. If a value of the integer operand is positive then that value can be produced as a negatively applying unary minus (-) operator. For example, lets see the expressions shown as:
int x = 0;
int y = 25;
x = (-y);
In this expression, a positive value is assigned tothe variable "y". After applying minus plus (-) operator on the operand "y", the value becomes "-25" which indicates it as a negative value. This behavior represents the number in two's complement format.
III. Increment (++) and Decrement Operators
The increment/decrement operators can be a prefix or a postfix .In a prefix expression (++ x or -- x), an operator is applied before an operand while in a postfix expression (x ++ or x --) an operator is applied after an operand. In both conditions 1 is added to the value of the variable and the result is stored back to the variable. However both operators have the same effect as "x = x + 1;"
Although there is a major difference between a prefix and a postfix expressions. In a prefix expression, a value is incremented first then this new value is restored back to the variable. On the other hand, In postfix expression the current value is assigned to a variable then it is incremented by 1 and restored back to the original variable.
( i ) example using prefix unary operator:
public class Prefix{
public static void main(String[] args){
int x = 0;
int y = 0;
y = ++x;
System.out.println("The value of x :" + x);
System.out.println("The value of y:" + y);
}
}
Output of the Program:
C:\nisha>javac Prefix.java
C:\nisha>java Prefix
The value of x :1
The value of y:1
The output of this program shows that always 1 is stored in both variables i.e. the value of "x" is incremented first then it is assigned to the variable "y".
( ii ) example using postfix unary operator:
public class Postfix{
public static void main(String[] args){
int x = 0;
int y = 0;
y = x++;
System.out.println("The value of x :"+ x );
System.out.println("The value of y:" + y );
}
}
The logical compliment (!) operator is also known as Boolean Negation Operator. It is used to invert the value of a boolean type operand i.e. the type of the operand must be boolean while using this operator,. If the value of the boolean operand is false, the ! operator returns true. But, if the value of the operand is true, the ! operator returns false.
Arithmetic assignment Operators
One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
This operator can also be used on objects to assign object references, as discussed in Creating Objects.
The Arithmetic Operators:
The Java programming language provides operators that 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.
+ additive operator (also used for String concatenation)
- subtraction operator
* multiplication operator
/ division operator
% remainder operator
The following program, ArithmeticDemo, tests the arithmetic operators.
class ArithmeticDemo {
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);
}
}
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.
The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:
class ConcatDemo {By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}