Tuesday, 2 November 2010

Decision Making And Branching


Decision Making And Branching
If statement
What is a decision? In simple terms it is a task done when a particular condition is met. Let us see some examples.
My father will buy me a bike if I come first in my class
She will go out with me if I have a car
Ramesh can watch the cricket match if his boss gives him the day off.
In each of the following statement the first part is the task which will be accomplished if the condition in the second part is met. This is written in English now let us see how we can write this in a more general manner
If (student comes first in class) then
            Father buys a bike
End if
If (person has car) then
            Girl goes out
End if
If (boss gives a day off) then
            Ramesh watches the cricket match
End if

Therefore the general syntax of the Decision making statement is
If(condition)
            Statements to be executed

How is it useful in our Java program, let us say that if the age of a driver is greater than 18 then he can drive and we want to print the message “You are eligible to drive”
The line if(age>=18) can have only two options either True or False. If it is true then the next line is executed if the answer is false then the next line is skipped.
The next question that might arise is what if I need more than one lines to be executed on a true condition. In the present format it only executes a single line. To overcome this drawback we can use curly brackets to signify a block of code that is executed when the condition is true.
For example look at the next program.
Please mark the difference if the condition is true then two lines are executed and to implement this situation we use the braces to create a block of code or a body.

The next genuine question should be what about those people who cannot drive or are below the age of 18. To add a false condition we use the if()…else construct. Let us first look at some simple examples in English which clearly bring out the difference.
My mother will buy Chinese food today if it does not rain else she will cook at home

My father will buy a house in Bombay if he gets a loan else he will look for something in his hometown.

I will try to become a doctor if I clear the medical exams else I will try for my PhD.
To represent the above mentioned statements we will use if…else construct

If(it rains)

{
            Buy Chinese food
}
else
{
            Cook at home
}
Now let’s try this on the same java program with a message for people who are not eligible to drive. In this program if the age is greater than equal to 18 the program will print a congratulation message. On the other hand if age is less than 18 then it will print the sorry message.
I would like to show you one more example. This program prints if the given number is even or odd. As we all know an even number is completely divisible by 2 and odd number is not. Therefore our condition becomes true if number is divisible by 2 and false if the number is not divisible by 2.


Let us look at one more example to print the greater of two numbers. The condition is quite simple we have to compare two numbers using a if statement.

The next program makes everything a bit more interesting, depending on your likes and dislikes there are two ways of doing it, first I will show you the easy way using logical operators and then I will show you the same program without using logical operators. In java you can use if in conjunction with else, this is used to test more than one conditions, it is particularly useful where simple if … else construct fails. In the next program you are given three sides of a triangle and your program must print if the side is an equilateral triangle, isosceles triangle or scalene triangle. For the uninitiated a triangle is equilateral if all its sides are of same length, if any two sides are the same then it is an isosceles triangle and if none of the sides are equal then it is called a scalene triangle.
As you can see if the first condition is false then it checks another condition and if that too is false then it checks the third condition.

Now let me give the alternative which happens to be my favored way of writing conditional statement. It may be a bit difficult to understand to begin with but I find it more elegant.


There are many ways in which you can use these statements, please remember there is no hard and fast rules except the syntax, beyond which it is your own imagination. Another popular if..else example is student grade program. For example if each student in your class gets grade according to the following criteria
Marks greater than or equal to 85 grade is A, marks greater than or equal to 70 Grade is B, marks greater than or equal to 50 Grade is C and marks less than 50 Grade is F.

Let us make it a bit more interesting and calculate our net salary based on the following criteria
If basic pay is more than 50,000 then HRA is 2% DA is 40% and Income Tax (IT) is 25%
If basic pay is more than 20,000 and less than or equal to 50,000then HRA is 4% DA is 50% and Income Tax (IT) is 20%
If basic pay less than or equal to 20,000 then HRA is 8% DA is 70% and Income Tax (IT) is 5%. Most important point to remember here is the calculations may give us floating point numbers therefore in this program we cannot use integer numbers.
 












Monday, 1 November 2010

Java Tokens

In this section we will discuss

1. Literals
2. Identifiers
3. Keywords
4. Operators
5. Comments

Literals
In the previous sections I have already clarified what are Literals they are called constants. These are the values that do not change or cannot accept any other value except their own.
int a=0;
In the above Java statement the numeral zero represents a ‘Literal’. It represents a value which cannot be changed thus it is called a ‘Literal’ or ‘Constant’. These values may represent character, integer, float or Boolean type of values. I had told you about two basic types of literals alpha-numeric and numeric. Let’s see these in a bit more detail in relation to Java.(These are known as primitive data type)


  • byte: The byte data type is an 8-bit signed integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory.
  •  short: The short data type is a 16-bit signed integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
  •  int: The int data type is a 32-bit signed  integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.
  • long: The long data type is a 64-bit signed integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. This data type should never be used for precise values, such as currency.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
Examples of Boolean literal
true, false
Example of float literals
2.3f , 4.089f
Example of double literal
0.0d , 0.5555d
Example of int literals
3456, 5678
Example char literal
‘s’, ‘\n’

Identifiers
Identifiers are also known as variables. Basically variables are memory locations where we store any value we require for further computation during the program execution. They are like containers, empty by itself but useful when filled with some value. Example a water bottle is empty to begin with but it stores the amount of water you pour in. It depends if you want to fill the whole water bottle or part of it. Same way memory locations on the computer memory are empty by default but can be used to store data you require. Thus each memory location can be given any name. It totally depends on you as long as you follow some simple naming conventions it is ok with the compiler. The rules to for naming a variable are
  • you can use letters from A to Z as well as lowercase representation a to z
  • any integer number can be used as long as the name does not start with a number
  • no special character can be used except underscore
Some of the good programming practices dictate few more rules, please be advised that rules mentioned below are guidelines and are not implemented or checked by the Java compiler
  • the variable name should be something which makes the it easy to understand what value is stored inside
  • the name should be descriptive rather than cryptic bs is not a good name instead you can use basic_salary

Variable name
Valid/Invalid
basic_sal
valid
12salalry
Invalid
basic*sal
invalid


Keywords
These are special words which have been reserved for use in Java and you cannot use them as identifier name. They can be used to perform some task or give a command to the compiler. Some of the Java keywords are
abstract
continue
for
new
switch
assert
default
goto
package
synchronized
boolean
do
if
private
this
break
double
implements
protected
throw
byte
else
import
public
throws
case
enum
instanceof
return
transient
catch
extends
int
short
try
char
final
interface
static
void
class
finally
long
strictfp
volatile
const
float
native
super
while


Operators
These are mathematical or logical symbols used to perform some operation on one or more values.
Java supports the following type of operators
Simple Assignment Operator
=          Simple assignment operator
Arithmetic Operators
         Additive operator (also used for String concatenation)
          Subtraction operator
*           Multiplication operator
          Division operator
%         Remainder operator
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 compliment operator; inverts the value of a boolean
Equality and Relational Operators
==        Equal to
!=         Not equal to
>          Greater than
>=        Greater than or equal to
<          Less than
<=        Less than or equal to
Conditional Operators
&&        Conditional-AND
||           Conditional-OR
?:      Ternary (shorthand for if-then-else statement)
Type Comparison Operator
instanceof         Compares an object to a specified type
Bitwise and Bit Shift Operators
~          Unary bitwise complement
<<        Signed left shift
>>        Signed right shift
>>>      Unsigned right shift
&          Bitwise AND
^           Bitwise exclusive OR
|           Bitwise inclusive OR

Operator Precedence
In math’s we have BODMAS which defines precedence of the operators. In the same way Java too has its own rules for operator precedence 

The operators in Java, shown in order of precedence - from highest to lowest
Priority
Operators
Operation
Associativity
1
[ ]
array index
left
()
method call
.
member access
2
++
pre- or postfix increment
right
--
pre- or postfix decrement
+ -
unary plus, minus
~
bitwise NOT
!
boolean (logical) NOT
(type)
type cast
new
object creation
3
* / %
multiplication, division, remainder
left
4
+ -
addition, substraction
left
+
string concatenation
5
<< 
signed bit shift left
left
>> 
signed bit shift right
>>> 
unsigned bit shift right
6
< <=
less than, less than or equal to
left
> >=
greater than, greater than or equal to
instanceof
reference test
7
==
equal to
left
!=
not equal to
8
&
bitwise AND
left
&
boolean (logical) AND
9
^
bitwise XOR
left
^
boolean (logical) XOR
10
|
bitwise OR
left
|
boolean (logical) OR
11
&&
boolean (logical) AND
left
12
||
boolean (logical) OR
left
13
? :
conditional
right
14
=
assignment
right
*= /= += -= %=

     <<= >>= >>>=

     &= ^= |=
combinated assignment
(operation and assignment)


Comments
Comments are non-executable lines of java code. They are put in the program for documentation and future reference. Java compiler ignores these lines.There are two types of comments
a)     single line coment
These comments begin with a //
b)    Multi line comments
These comments start with /* and end with */