Java Language Basics

Java program is a collection of different atomic elements namely, whitespace, identifiers, literals, comments, operators, separators and keywords. In this chapter we will discuss all the parts that are mentioned above.
Whitespace
In java indentations are not obligatory, so writing 100 lines of code and 10 lines of compact code may be same. We can write a program continuously without separating it from the previous statement by a new line or other forms of white space. Whitespace is mandatory only if we are representing different tokens and that do not use operators and separators. For example int     x,y,     z; is identical to int x,y,z;. but intx,y,z is erroneous because int is a special keyword and it must be separated in some way by whitespace or may be by some separators if permitted.
Identifiers
Identifiers are the words that describe variable’s name, method names, class names etc. An identifier can be any string of letters lower and upper characters, dollar sign ($), underscore ( _ ), and digits with the exception that it cannot start with digits. Remember java is case sensitive identifier ram is different from Ram.
Examples:
Hello, hi,        hi123, $wer,   _dsf,    sd_ew,             etc are valid identifiers.
1hi,      hello Mr,          Mr.X, hello-dude,      etc are not valid identifiers.
Note: We can not have reserved keywords as identifiers (Reserved keywords: later).
Literals
Literal representation is used in java to create constant values. For example
75,       56.89,              ‘y’,       “this is string”,            etc are literal representing different constant values (more on this later).
Comments
Comments are sentences that are not treated as a part of the program. In java there are three ways of putting comments on the program codes. They are:
  • Single line comment followed by //
e.g.        // this is single line comment
  • Multi line comment enclosed in /*  …… */
e.g.            /* This comment can be of multiple lines but it is single line here */
  • Documentation comment enclosed in  /**  …..          */. This comment is used to produce documentation using javadoc tool.
e.g.            /** this is the sentence that is produced as document in documentation file when javadoc is used*/
Separators
There are different separators in java with different intention. The separators we have in java are:
()          Paranthesis:   It is used to enclose list of parameters in methods definition and invocation. It is used to define precedence in an expression. It is used to enclose type cast.
[]          Brackets:        It is used to declare an array and also used to dereference array values.
{}         Braces:           It is used to put automatically initialized array and to define the block of codes.
;           Semicolon:      It is used to terminate the statements.
,           Comma:         It is used to separate consecutive identifiers in variable declaration and is used to join statements in for loop.
.           Period:            it is used to separate package name from subpackages names and is also used to reference variable and methods of an object.
Keywords
Keywords are word that have distinct and special meaning in java language and treated in special way by java compiler. So we cannot use keywords as identifiers. Apart from the below listed keywords true, false and null are reserved words and cannot be specified as an identifier though they are not keywords. The java keywords are listed below:
The table is extracted from java tutorial
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

*

not used
**

added in 1.2
***

added in 1.4
****

added in 5.0
Operators
Discussed in subsequent sections
Data Types
Java is strongly typed language so every variable in java must be declared of specific type explicitly so that the compiler understands what kind of variable we are considering. Data type defines the amount of memory that will be used by a variable and the valid range of values that a variable can represent. There are eight primitive data types in java. The eight types constitutes four groups namely Integers, Floating points, characters and Boolean.

Primitive Data Types

Java defines eight primitive data types, which define the core data that can be represented in the Java programming language. A data type defines the amount of memory that will be used when defining one of the data types and the valid range of values it can represent.
Integer Data Types
Integers represent the numbers without the fractional part i.e. whole numbers. In Java four data types represent integers: byte, short, int, and long. The following table shows the memory required for each type and the valid range of values it can represent.
Integer Type
Memory Required
Range of Values
byte
1 byte (8 bits)
–128 to +127 (–27 to 27–1)
short
2 bytes (16 bits)
–32,768 to 32,767 (–215 to 215–1)
int
4 bytes (32 bits)
–2,147,483,648 to 2,147,483, 647 (–231 to 231–1)
long
8 bytes (64 bits)
–9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L (–263 to 263–1)
You choose the particular type of integers according to your need. For example if you need age of man in years to be represented, byte is the suitable one since we do not expect age of the man to be more than 127.
We declare Integer Types as:
int x;            byte num;   short snum; long lnum;
We can initialize the above types while declaring or afterwards. In any case literals are used for initialization. For example:
int second = 5, minute;       /*here two variables are declared where one is initialized
minute = 30;            and the other is not. The other variable minute is initialized after declaration statement*/
Default value for these types, if not initialized is 0 for all types with usual literal conventions. There are 3 types of literal representations for integer types they are decimal literals like 10 and -34, octal literals with leading 0 like 012 (decimal 10), and hexadecimal literals with leading 0x like 0x1A (decimal 26). Here if we use literal for long integer we append the letter L at the normal literal for e.g. long howlong = 123456L.
Floating-Point Types
The types of numbers with the fractional parts are referred to as floating-point types. A common way in mathematics, as well as in computer science, to represent floating-point numbers is to provide an exponential representation of a number. This is defined as listing the significant digits with one digit written before the decimal point, and then defining the power of 10 to multiply by the number to generate its real value. So 123 million could be written as- 1.23E+8. We have two types of floating-point data types float and double. The following table shows the memory required for each type and the valid range of values it can represent.
Floating -point Type
Memory Required
Range of Values
float
4 bytes (32 bits)
+/– 3.40282347E+38F (6–7 significant digits)
double
8 bytes (64 bits)
+/– 1.7976931346231570E+308 (15 significant digits)
The choice of the above type depends upon the precision we need. As an instance if you are representing currency, float will be ok, but if you are calculating the amount of light to apply to a surface rendering in graphics application, a double becomes more appropriate.
We declare Floating-Point Types as:
float floatval;               double doubval;
We can initialize the above types while declaring or afterwards as defined previously for integer types.
Default value for these types, if not initialized is 0.0 for both types with usual literal conventions. Here if we use literal for float we append the letter f or F at the number for e.g. float floatliteral = 12.3456f,  floatlit2 = 1.234e4F. Similarly we can append d or D for double type (for double type d or D may be omitted). There are three special values for floating type numbers Double.POSITIVE_INFINITY, Double.NEGATIVE_ INFINITY and Double.NaN (also corresponds to Float class) to represent positive infinity, negative infinity and not a number respectively.

Character Type
It is a single 16 bit unsigned quantity to represent text. It uses 16 bit Unicode format. We declare character type as: char mychar; Characters can be represented in their Unicode form as: \uXXXX, Where XXXX is a number in the range of 0000 to FFFF (hexadecimal), or as their English equivalents delimited by single quotes: like ‘a’, ‘x’, etc. if we need group of characters we normally use String (discussed later) that is not a primitive type. Since characters are delimited by single quotes, Strings are delimited by double quotes. Java defines a set of special characters that are used with special meanings. They are as shown in table below:
Character
Meaning
Unicode Equivalent
\b
Backspace
\u0008
\t
Tab
\u0009
\n
Linefeed
\u000a
\r
Carriage Return
\u000d
\”
Double Quote
\u0022
\’
Single Quote
\u0027
\\
Back Slash
\005c
For more information about Unicode visit http://www.unicode.org.
Example of character declaration and initialization:
char mychar = ‘x’;
char notmychar = ‘\t’;
Note: we can perform arithmetic operations on char type variables.
Boolean Data Type
The last primitive data type in the Java programming language is the boolean data type. A boolean data type has one of two values: true or false. These are not strings, but reserved words in the Java programming language.
The declaration and initialization of Boolean variable is as: boolean boolval = false;

Note: your compiler may generate error message if you do not initialize variable.
Variables
When we declare a data type it defines the storage capacity and usage for a region in memory. To access such memory in Java we assign a meaningful valid identifier (see above to know about valid identifiers), that identifier is called a variable. The act of creating a variable is called declaring a variable, and it has the following form:
datatype variableName [= value1, varaibleName2[= value2], …..] ; {here variable names may be chained by using comma as a separator entities inside [ and ] are optional}.
For example:
               char c; 
               int numberOfStudents; 
The convention adopted by the Java world in naming variable is to start with a lowercase letter, and if the name has multiple words, capitalize the first letter of every word. For example: myVaraible, hisChair, redHat. If we are naming class the convention is to start with capital letter like MyClass.
In java there are four types of variables as given below:
Instance Variables (Non-Static Fields) objects store their state in fields. Objects actually store their individual state in the fields that are declared as non static. This type of fields are also known as instance variables. For e.g. if we have class name Students, then studentName can be instance variable.
Class Variables (Static Fields) When a variable id declared using static modifier, then  the resulting variable is called class variable such that regardless of the number of instantiation of the class the variable is unique to the class. For example numberOfStudents in class student can be static since it represents the whole class.
Local Variables There is no keyword that defines the local variable. However, the place where the variable is declared makes the variable local and the place is inside the method’s block. Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Parameters The variable defined within the parenthesis in a method is parameter. As an example args in public static void main(String[] args) is the parameter to this method.

Conversion Between Numeric Types

When using numeric variables the type does not necessarily have to be the same. Whenever two numbers are operated then there will be conversion between number types like byte is converted to int if byte and int type variables are operated. This is referred to as arithmetic promotion. All mathematical operations in Java are performed by promoting each operand in the operation to a specific data type, following these rules in this order:
1.      If any of the operands is of type double, the other one will by converted to a double.
2.      If any of the operands is of type float, the other one will be converted to a float.
3.      If any of the operands is of type long, the other one will be converted to a long.
4.      Otherwise all operands will be converted in ints.
The promotion, or conversion, of a narrower type (fewer number of bytes) to a wider type (greater number of bytes), such as the conversion of a short to an int. this type of conversion is safe and does not result in the loss of information. 

Conversion Through Assignment

Consider the following:
byte b1 = 13;         byte b2 = 17;         byte result = b1 + b2; 
The Java compiler generates error saying "possible loss of precision" because although b1 and b2 are both bytes, they are promoted to ints before assigning the result to variable. The rule for conversion between primitive numeric types is that a type can be assigned to a wider type, but not a narrower type. So, the following conversions are permissible by the compiler:
1.      byteshort, int, long, float, double
2.      shortint, long, float, double
3.      intlong, float, double
4.      longfloat, double
5.      floatdouble
6.      charint
Example: int i = 10;   long l = i; // legal     double d = i; // legal   short s = i; // Illegal!

Casting Between Data Types

Java offers a mechanism for overriding the compiler called casting. Casting tells the compiler to convert the data to the specified type even though it might lose data. Casting is performed by prefixing the variable or value by the desired data type enclosed in parentheses:
datatype variable = ( datatype )value; 
For example: int i = 10;  short s = ( short )i;
long l = 100;          byte b = ( byte )l; 
This type of casting must be carefully done since it may result in loss of data.

Constants

To declare a variable to be a constant, or not changing, Java uses the keyword final to denote that a variable is in fact a constant. For example we know that the value of PI is constant so we can declare PI with the keyword final and ensure that its value cannot change as final double PI = 3.14285;
If you try to compile a statement that modifies a constant value, such as PI with
PI = PI*2; 
The compiler generates an error saying that you cannot assign a value to a final variable. By convention, programmers usually capitalize all the letters in a constant's name so that it can be found with only a mere glance of the source code. Pi, therefore, was declared as final double PI = 3.14285;

Object Wrappers for Primitives

For each primitive type discussed above there is a class that corresponds to that type of value. For e.g. there is a class java.lang.Integer that corresponds to primitive type int. These class types accompanying the primitive types are known as object wrappers and they serve several purposes:
·         The class is a convenient place to store constants like the biggest and smallest values the primitive type can store.
·         The class also has methods that can convert both ways between primitive values of each type and printable Strings.
·         Some data structure library classes only operate on objects, not primitive variables. The object wrappers provide a convenient way to convert a primitive into the equivalent object, so it can be processed by these data structure classes. One example of a data structure class that only operates on objects is the class java.util.SortedSet, which keeps a collection of objects in sorted order for you.

Primitive type
Corresponding wrapper class
boolean
java.lang.Boolean
char
java.lang.Character
int
java.lang.Integer
long
java.lang.Long
byte
java.lang.Byte
short
java.lang.Short
double
java.lang.Double
float
java.lang.Float

Example: Using Wrapper class.
int i = 15;
Integer myInt = new Integer(i); //wrap an int in a object
// get the printable representation of an Integer:
String s = myInt.toString();
// gets the Integer as a printable hex string
String s = myInt.toHexString(15); // s is now "f"
// reads a string, and gives you back an int
i = myInt.parseInt( "2047" );
// reads a string, and gives you back an Integer object
myInt = myInt.valueOf( "2047" );
Note:  See documentation for detail.
Operators
An operator is a symbol that is used to perform some action on one, two or three operands. For e.g. in a + b the operator + (arithmetic addition operator) is used in two operands and its function is to add two operands a and b. At this point you must understand the concept of order of evaluation. The java order of evaluation for all binary operators except assignment operators is left to right i.e. the left operand is fully evaluated before the right operand so in above addition a is evaluated before b.

Java operators

The java operators and their corresponding associativity are as given in table below where high precedence operators appear before low precedence operators and operators within the same group have same precedence.
Operator(s)
Name
Associativity
[] . () {method call}
-
Left to Right
++   -- {postfix}
Unary
Left to Right
~  !  - + ++  -- {prefix} ( ) {cast} new
Unary
Right to Left
*  /  %
Multiplicative Operators
Left to Right
-  +
Additive Operators
Left to Right
<< >> >>>
Bitwise Shift
Left to Right
instanceof  < <=  >  >=
Relational Operators

==  !=
Equality Operators
Left to Right
&
Bitwise AND
Left to Right
^
Bitwise Exclusive OR
Left to Right
|
Bitwise Inclusive OR
Left to Right
&&
Logical AND
Left to Right
||
Logical OR
Left to Right
? :
Conditional Operator
Left to Right
= *= /= %= += -= <<= >>= >>>= &= ^= |=
Assignment Operators
Right to Left

The [], ( ) and . operators

·         [] operator is used for accessing the array elements at particular position. For e.g. if we have array1[5] then we are accessing 6th element of an array called array1.

  • ( ) operator here is used fro calling the methods. For e.g. if static method of  Math class called min, then we can have Math.min(7,5). Similarly ( ) operator is used as cast operator for type casting as discussed previously. For e.g. if we have a variable x of double type and we want to cast it to the int type we must cast the variable x as (int)x.
  • . operator is used for accessing the instance variable and methods of an object or static variable or method of the class. For e.g. Math.PI (what is this?)

The ++ and -- operators

The above two operators are unary operators and are notation that are used to add or subtract 1 to the operand. For example x++ means add 1 to x and assign it to x. These operators can be both pre increment (decrement) and post increment (decrement) depending upon the place of the operator in an operand. The following example clarifies the operators.
++i;     // pre-increment
i++;     // post-increment
Example piece of code:
int x = 5;
System.out.println(“x++ = “+ (x++) + “ and ++x = “+(++x));
System.out.println(“x-- = “+ (x--) + “ and --x = “+(--x));
Here if you write this code in main method the output will be:
x++ = 5 and ++x = 7
x-- = 7 and --x = 5
Notice that initially the value of x was five and first x++ (post increment) used the value of x and incremented it so it became 6, but the printed value was 5 (before increment). When ++x is placed previous value of x was 6 and the value of x was printed after incrementing x (6) to 7 so the output for ++x was 7. Similar reason can be applied for x--and –x.
Note: The pre and post-increment operators can appear in the middle of an expression like: int nextArrayValue = array1[i++]; // post-increment. Here the current value of i is used and 1 is added it.

Unary Operators (Others)

Unary operators operate on only one operand. Here we present unary operators except bitwise negation (~) and those mentioned previously.

·         + operator is used to represent positive value (normally not used)

  • - operator is used to negate the expression having numeric value.
  • ! (logical not) operator is used to negate the boolean value i.e. if the value of the Boolean variable is true then its negation will be false.
  • new operator is used to instantiate the class (more on this later).
Example piece of code:
int x = 5;
boolean boolVar = false;
System.out.println(“+x = “ + (+x)+”, -x = “+(-x)+”, and  !boolVar = “+ (!boolVar));

The result is:

+x = 5, -x = -5, and !boolVar = true               (understood?)

Arithmetic Operators
There are five arithmetic operators in Java. All the arithmetic operators are given below:
·         /           operator for division. This operator performs integer division (rounded) on integer types i.e. if both the operands are integers.
·         *          operator for multiplication
·         +          operator for addition (remember string concatenation also)
·         -           operator for subtraction
·         %        operator for obtaining remainder (called modulus operator).
Examples:
7.5/5 =  1.5                  7/5 = 1             2+3 = 5            3-2 = 1             5%3 = 2.

Assignment Operators

There are different assignment operators in java as provided in table above. All such operators meaning can be interpreted easily.
·         =          operator is used to assign value of an expression to another expression. For e.g. if we want to assign value 5 to the variable five, then we do five = 5;, similarly, str = “hello”; assigns string value “hello” to the variable str.
·         +=        operator is used to assign variable a value obtained by adding the previous value of the variable and value of the other expression. For example res += res1; is equivalent to the statement res = res + res1;, where res and res1 are two expressions.
·         Similarly the other assignment operators are interpreted as above.
Relational and Equality Operators
Relational and equality operators are very important in any programming. They are used for comparing the operands. Java has various such operators as given below:
  • ==                    operator is used to verify whether two operands are equal.
  • !=                     operator is used to verify whether two operands are not equal
·                                                         >          operator is used to verify whether the first operand is greater than    the second operand or not.
·                                                         >=        operator is used to verify whether the first operand is greater than or equals to the second operand or not.
·                                                         <          operator is used to verify whether the first operand is less than    the second operand or not
·                                                         <=        operator is used to verify whether the first operand is less than or equals to the second operand or not.
  • instanceof       operator is used for type comparision.
Example piece of code:
int a = 23;
int b = 23;
int c = 15;
if(a == b) System.out.println("a == b");
if(a != c) System.out.println("a != c");
if(a > c) System.out.println("a > c");
if(a < b) System.out.println("a < b");
if(a <= b) System.out.println("a <= b");
Here is the output:
a =  b   a != c
a > c   
a <=b
Using instanceof:
Instanceof operator compares the object to the specified type. For e.g. if we have classes say Parent and Child, where Child class extends Parent and implements MyInterface. The following piece of code is interpreted as given below in out put.
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));
Here is the output (see tutorial for detail code)
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
Note: null is not an instance of anything.

Logical Operators
The logical operators operate on Boolean operand(s) and results the value as true or false. Logical operators in java are as given below:
  • !           discussed above in unary operators.
·                                 &&      logical AND operator outputs the result true if both the operands on which the operator is operating are true, false otherwise.
·                                 ||           logical OR operator outputs the result false if both the operands on which the operator is operating are false, true otherwise.
Usage Example:
if(((x==6)&&(y!=4))||(!z)) { //code to do something.} here the expression inside if is true when we have either x is equal to 6 and y is not equal to 4 or z is false.
Bitwise Operators (no details required)
The purpose of bitwise operators is to operate on the given integral operand in low level i.e. bit level used to represent the data. The following are the bitwise operators in java.
  • ~          operator is used to negate the individual bits of the operand.
·                                 &         operator does the ANDing of individual bits and produces output. The ANDing of two bit results in 1 if both the bits are 1, 0 otherwise.
·                                 |           operator does the ORing of individual bits and produces output. The ORing of two bit results in 0 if both the bits are 0, 1 otherwise.
·                                 ^          operator does the XORing of individual bits and produces output. The XORing of two bit results in 1 if exactly one of the bits is 1 and the other is 0, 0 otherwise.
·                                 >>        Right shift operator shifts all of the bits in the first operand (left to the operator) to the right a specified number of times given as second operand. The top (leftmost) bits due to right shift are filled in with previous content of the top bit. This is called sign extension that serves to present the sign of the number shifted.
·                                 >>>     Unsigned right shift (shift right and zero fill) operator shifts all of the bits in the first operand to right a specified number of times given as a second operand. The leftmost bits due to shifting are 0.
·                                 <<        Left shift operator shifts all of the bits in the first operand (left to the operator) to the left a specified number of times given as second operand. The top (leftmost) bits due to left shift are lost and the rightmost bits shifted are filled in with 0’s.
Examples: actually numbers are represented using 32 bits if they are integers.
·         ~2 =  ~(0000 0010) = 1111 1101 is interpreted like -3 in computer internal representation as 0000 0010 (1’s complement of 1111 1101) + 1 = 0000 0011 with sign changed.
·         5&2 = 0 since 5 = 0000 0101 and 2 = 0000 0010 so ANDing of bits is 0000 0000 = 0.
·         5|2 = 0000 0101 | 0000 0010 = 0000 0111 = 7 (understood ?)
·         7^2 = 0000 0111 ^ 0000 0010 = 0000 0101 = 5 (understood ?)
·         35>>2 = 8, since 0010 0011 >> 2 = 0000 1000 = 8.
·         -5>>1 = -3, since (2’s complement of 5 = 0000 0101 is 1111 1010+1 = 1111 1011 = -5 and  1111 1011 >> 1 = 1111 1101 = (2’s complement of 1111 1101 is 0000 0011 = 3) so negative value is -3.
·         35>>>2, since 0010 0011 >>> 2 = 0000 1000 = 8.
·         -5>>1 = 24 1’s and 1111 1011>>> 1 = 0111 1111 1111 1111 1111 1111 1111 1101 = 2147483645 (here exact 32 bit representation should be considered however in above and below examples also the same is true but our representation does not alter values).
·         35<<2 = 140, since 0010 0011 << 2 = 1000 1100 = 140.
·         -5<<1 = -10, since 1111 1011<<1 = 1111 0110 = -10
Conditional Operator (? :)
This operator is ternary operator i.e. it requires three operands. The syntax for this operator is condition ? statement1:statement2. Here we interpret like: if condition is true then statement 1 is executes else statement 2 is executed. For e.g. int min = (x <= y) ? x : y; means if x <= y then min = x, otherwise min = y.

Associativity

If we come up with the situation where operators are from the same precedence group then the order of evaluation is provided by the associativity. As an example take If we have 3 * 5 % 3, what is the result (3 * 5) % 3 or as 3 * (5 % 3)? First expression is 15 % 3, which is 0. The second expression is 3 * 2, which is 6. Here, since * and the % operators have the same precedence, precedence does not give the answer. So we take the advantage of associativity and calculate the expression 3 * 5 % 3 as (3 * 5) % 3 since * and % are left to right associative. Students: to come out of this kind of confusing situation use parenthesis to define precedence.

Expressions

Expressions are the logical constructs consisting the combination constructs like variables, operators and method invocations such that it results in single value.
Examples:
124 (a literal)               this (this object reference)       Double.MAX_VALUE (field access) Math.sqrt(16)   (a method call)        new String(“hello”)  (object creation)                           new arr[2]   (array creation)                arr[1] (array access)      x+y (expression with operators)
(x*200+3)  (Expression in parenthesis).

Statements

Statement is set of constructs that make an executable portion of program. In java, most of the statements are ended with semicolon (;).different types of statements in java are:
Expression Statements: Statement that consists of expression and ended with semicolon. The following type of expressions are made statements suffixing ; in Java.
Assignment expressions          e.g. a = 3;
Any use of ++ or --                 e.g. x++;
Method invocations                e.g. Math.pow(2,3);
Object creation expressions    String str = new String(“Oops!”);
Declarative Statements:  Statements declaring the variables. For e.g. int x = 101;
Control Flow Statements: These statements define the order of execution (more later).

Blocks

Block is a compound statement, or a group of statements enclosed within braces ({ … }). Block can be placed where we can have statements placed. The following is the example of block taken from the java tutorial trails.
class BlockDemo {
     public static void main(String[] args) {
          boolean condition = true;
          if (condition) { // begin block 1
               System.out.println("Condition is true.");
          } // end block one
          else { // begin block 2
               System.out.println("Condition is false.");
          } // end block 2
     }
}

Control Flow Statements

Conditional Statements

Conditional statements allow us to decide the statement of the code to execute depending upon the given condition. There are two types of conditional statements also called selection statements if-then-else statements and switch statement.

The if-else Statements

This type of statements are used when we have to select the block if certain condition is satisfied and take some other action if the condition is not satisfied. There are different forms of if-else statements as provided below:
if only statement
Consider the situation when we have to perform the action only if certain condition is matched and do nothing if the condition is not matched. This situation can be best described by if only statements. The syntax for if only statement is

               if( condition ) {    // Execute statements here} . 
The statement accepts value that provides condition i.e. results Boolean value if the condition is true then statements in block are executed else nothing is done.
Example piece of code:
int x = 5,  y = 10;
if(x<10)
    System.out.println(“X is less than ten”);
if(y > 10)
    System.out.println(“wow y is greater than ten”);
Output:
Here since only the condition at the first if statement is true i.e. x<10, the output is
X is less than ten
if-else statement
When there is a need of executing the statement (block) if a condition matches and another statement (block) is to be executed otherwise, then we use if – else statements. It has the general syntax as given below:
if(condition) { //execute if true statements here}
else { //execute if not true statements here}
In this situation, if the condition is satisfied the first block is executed, otherwise the second block is executed.
Example piece of code:
int x = 3;
if(x>2)
    System.out.println(“condition true”);
else 
    System.out.println(“condition false”);
Output:
Since x = 3, x>2 is true so the output is - condition true. If we had x = 1, then x>2 would have been false giving us an output as – condition false.
Nested if (if-else) Statement
Nested if is very common in programming. The concept is same as in simple if-else but it is applied in different levels as required. Here is the example:
Example piece of code:
int x = 3;
if(x>2)
{
    if(x==3)     System.out.println(“X is three”);
}
else
{
    if(x==1)       System.out.println(“X is one ”);
    else              Sustem.out.println(“X less than two and it is not one”);
}
Output:
Since x = 3, x>2 is true so it checks whethter x is equal to 3 or not. Here x is 3 so the output is – X is three. If we had x = 0, then x>2 would have been false so there would have been another check for equality of x to 1. Here again the condition would have been false giving us an output as – X is less than two and it is not one.
if-else-if Ladder statements
If we have the situation where there are different actions that are executed depending upon different condition with same type of instance then if-else-if is useful. It has general syntax as given below:
               if( condition1 ) {    // c1 statements; } 
               else if(condition2 ) {    //c2  statements; } 
               else if( condition3 ) {    //c3  statements; } 
               else {    // final statements; } 
Here if condition1 is true c1 statements are executed, otherwise if condition2 is true c2 statements are executed, for true condition3, c3 statements are executed and final statements are executed if no condition matches. 
Example: 
int age // this is taken as input 
if( age < 18 ) { 
   System.out.println( "You are a child!" ); 
} 
else if( age < 55 ) { 
   System.out.println( "You are an adult" ); 
} 
else { 
   System.out.println( "You are a senior" ); 
} 
Output:
Students, determine the output if age = 24. (Is it, You are an adult??)
Conditional  Operator and if-else
As discussed previously the condition operator has syntax
condition ? true statement : false statement; (See conditional operator above)
This could be expressed using the if statement as follows:
               if( condition ) {    // true statement(s); } 
               else {  // false statement(s); } 
Remember the intention of conditional operator is based on returning or computing a value to be returned to the caller based on a condition. For example:
               boolean isChild = ( age < 18 ) ? true : false; 

The switch Statement

The switch statement is normally used to make a choice between multiple alternative execution paths based on an integer value (or any value that can be converted to an integer).The general form of the switch statement is:
switch( variable ) { 
case value_1: 
   // statements 
   break; 
case value_2: 
   // statements 
   break; 
... 
default: 
   // default statements 
} 
The variable must be an int or be able to be converted to an int. Depending upon the value of variable different statements pertaining to the case of matched value are executed. If no case is matched the default statements are executed.
Consider the example below to understand switch:
switch( menuValue ) { 
               case 0: 
                               System.out.println( "print" ); 
                               break; 
               case 1: 
                                System.out.println( "do not print" ); 
                               break; 
               case 2: 
                               System.out.println( "show" ); 
                               break; 
               case 3: 
                               System.out.println( "hide" ); 
                                break; 
               default: 
                               System.out.println( "Nothing" ); 
} 
The switch statement converts menuValue to an int, if it is not one already, and then compares its value to the values specified in case statements. If the value of menuValue is 0 the statement “print” is printed, for menuValue 1 “do not print” is printed, and so on. If the value of menuValue does not match any of the cases, it executes the statements following the default statement i.e. “Nothing”. Here one important thing is to remember to put break statement (break is explained later). If break statement is not after the statements for each case then after the case is matched all the statements including statements of other cases below matched case are executed. Consider the following: 
switch( menuValue ) { 
               case 0: 
                               System.out.println( "print" ); 
               case 1: 
                                System.out.println( "do not print" ); 
               case 2: 
                               System.out.println( "show" ); 
               default: 
                               System.out.println( "Nothing" ); 
} 
Output: menuValue = 1.
The case 1 is matched and all the statements below the case 1 are executed with output
               do not print
               show
               Nothing
This effect is referred to as falling through, and can be sometime useful if there are several cases that executes same statements. Consider the following example:
switch( month ) { 
               case 4: 
               case 6: 
               case 9: 
               case 11: 
                                System.out.println( "30 days" ); 
                               break; 
               case 1: 
               case 3: 
               case 5: 
               case 7:
               case 8: 
               case 10: 
               case 12: 
                               System.out.println( "31 days" ); 
                               break; 
               case 2:
                                System.out.println( "if leap year 29 days else 28 days" ); 
                               break; 
               default: 
                               System.out.println( "not a number for months must be 1-12" ); 
    }
If month is 4, 6, 9, or 11, then “30 days” is printed. If month is 1, 3, 5, 7, 8, 10, or 12, then “31 days” is printed. If month is 2, then “if leap year 29 days else 28 days” is printed. Lastly, if the month value is not between 1 and 12 no case is matched, so the default statement “not a number for months must be 1-12” is printed.

Iteration Statements

When there is a need of executing a task a specific number of times or until some condition is satisfied we use iteration statements. Java provides three ways of writing iterative statements. They are while statement, do-while statement, and for statement.

The while Statement

The while statement executes the statements as long as the given condition remains true. The general syntax of while statement is:
               while(condition ) {    //statements; } 
Here the statements within the brace are executed as long as the condition is true. When the condition becomes false, the while loop stops executing these statements exits out of loop.
Example piece of code:
int i=1; 
while( i <= 10 ) { 
System.out.print( "i=" + i ); 
i++; 
} 
Output:
The above code prints the number 1 to 10 as i = 1, i = 2, …, i = 10, when i reaches 11 the condition i<=10 becomes false and the loop terminates.
Remember: do not forget to increment i, otherwise loop will never terminate i.e. code goes into infinite loop. So when using loop, remember to guarantee its termination. 

The do while Statement

The statements inside the loops are not guaranteed to be executed at least once. So, to guarantee, at least one time, execution of statements do while loop is used. The basic syntax of do while loop is:
               do {    // statements; } while(condition );
Here the statements inside the braces are executed at least once and the condition is checked for truth value.
Example:
int i = 10; 
do{ 
   System.out.println( "Hello" ); 
  i++;
} while( i < 10 );
Output:
“Hello” is printed, though i<10 is false. (Why?).

The for Statement (For another for loop version enhanced for see tutorial)

When we have the fixed number of the iteration known then we use for loop (normally, since while loop is also possible). The basic syntax of for statement is:
for( initialization; termination; increment ) {    // statements; } 
First before loop starts, the initialization statement is executed that initializes the variable or variables in the loop. Second the termination condition is evaluated, if it is true, the body of the for loop will be executed. Finally, the increment statement will be executed, and the termination condition will be evaluated, this continues until the termination condition is false. Consider the following to compare with the parts of the for loop.
int i=10;                                               // Initialization statement 
while( i > 1 ) {                                      //  termination condition 
               System.out.print(i );               // Body 
               i--;}                                       // increment statement 
The below piece of code is the representation of above example using for loop.
      for( int i=10; i > 1; i-- ) { 
         System.out.print(i ); 
      } 
Output:
               10 9 8 7 6 5 4 3 2 
Remember: variable declaration in initialization part of the for loop is permissible and generally is a good practice. If tou have already declared and initialized the variable you could leave the initialization section blank as shown below
int i = 0; 
for( ; i<10; i++ ) {    // statements; }
Note: You can nest the loops so that one loop can be placed inside another loop. In this situation the inside loop is first terminated and again restarted when the first loop starts for the next incremented value. The outer loop is terminated last. 
Example:
for(int i = 1; i<=2;i++){


Output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
 
    for(int j=1; j<=3;j++)
               System.out.print(”(”+ i +”, ”+ j + ”)”); 
    System.out.println();}
Output:
The output is given alongside.
Jump Statements
Java, for the transfer of control from one part to another, supports three jump statements: break, continue, and return.
break Statement
The use of break statement cause the immediate termination of the loop (all type of loops) from the point of break statement and the passage of program control to the statements following the loop.
Example piece of code:
for( int i=1; i<= 10; i++ ) { 
               if( i == 5 ) { 
                               break; 
                               } 
               System.out.print( " i=" + i ); 
               } 
System.out.println( "oho char pachhi khai ta" ); 
} 
Output:
i=1 i=2 i=3 i=4 oho char pachhi  khai ta 
In the code above the loop is terminated immediately after the value of i is 5.
Remember: In case of nested loop if break statement is in inner loop only the inner loop is terminated. See the use of break in switch statement too.

There is another form of break statement called labeled break. This kind of break has the general form break label;, where label is the name of label identifying a block of code. A label is defined by a string of text (same rules apply to defining a label name as to defining a variable name) followed by a colon. To use this break the block of code with label must enclose break statement within it. Purpose of this statement is to jump out of the portion defined by label as shown in an example below:
Example piece of code: taken from the tutorial

int[][] arrayOfInts = {{32, 87, 3, 589}, {12, 1076, 2000, 8}, {622, 127, 77, 955}};
 int searchfor = 12;
 int i;
int j = 0;
boolean foundIt = false;
 search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length; j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                } } }
   if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
Output:
Found 12 at 1, 0 (try to understand program we will explanation consider in class).
continue Statement
Continue statement causes the execution of the current iteration of the loop to cease, and then continue at the next iteration of the loop.
Example:
for( int i=1; i<= 10; i++ ) { 
               if( i == 5 || i == 7 ) { continue; } 
               System.out.print(i ); } 
System.out.println( "Hurray Hami Ek Dam Dami" ); 
Output:
1 2 3 4 6 8 9 10 Hurray Hami Ek Dam Dami  (Details in the class!!)
The other type of continue is labeled continue that has similar difference with continue as of break has with labeled break for break operation i.e. labeled continue statement skips the current iteration of loop marked with the given label.
Example piece of code: taken from the tutorial
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
 int max = searchMe.length() - substring.length();
 test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++)
                        != substring.charAt(k++)) {
                    continue test;
                } }
            foundIt = true;
                 break test;
        }
        System.out.println(foundIt ? "Found it" :   "Didn't find it");
Output:
Found it                      (try to understand the code, details in the class)
return Statement
It is used to transfer the program control back to the caller of the method. There are two forms of return statement. First with general form return expression; returns the value whereas the second with the form return; returns no value but only the control to the caller.
Exercises
1.      Do all the exercises from the tutorial language basics section [remember after submission you are assessed through quiz in the class]
2.      How do you designate a variable to be a constant?
3.      Are the following statements legal? Why or why not?
               short s1 = 10; 
               short s2 = 10; 
               short result = s1 + s2;   
  1. What is the difference between the following operators: && and &?
  2. What is the result of 21 ^ 3
  3. What is the result of the following code fragment?
               int a = 5; 
               a += 6 * ++a / 2 – 6 * 9 + 2 
  1. Write a program that displays the temperatures from 0 degrees Celsius to 100 degrees Celsius and its Fahrenheit equivalent. Note that the conversion from Celsius to Fahrenheit uses the following formula: F = C * 9/5 + 32;
  2. Write a program that displays all prime numbers from 1 to 100. Note that a prime number is a number that is only divisible by itself and 1. For example the number 7 is prime, but the number 6 is not:             6 = 6*1 and 2*3
  3. Identify and correct the errors in each of the following sets of code (there may be more than one errors):
a.        while ( c <= 5 ){
                                        product *= c;
                                        ++c;
b.      if ( gender == 1 )
                                        System.out.println( "Woman" );
                         else;
                            System.out.println( "Man" );
c.       if ( age >= 65 );
                               System.out.println( "Age greater than or equal to 65" );
               else
                               System.out.println( "Age is less than 65 )";
  1.  What is wrong with the following while statement?
               while ( z >= 0 )
                               sum += z;
  1.  What does the following program print? Explain.
               public class Mystery
               {
               public static void main( String args[] )
               {
                               int y;
                               int x = 1;
                               int total = 0;
                               while ( x <= 10 )
                               {
                                                y = x * x;
                                              System.out.println( y );
                                              total += y;
                                              ++x;
                                } // end while
                                System.out.printf( "Total is %d\n", total );
               } // end main
               } // end class Mystery
  1. Write the output of the following code segment
         if ( x < 10 )
         if ( y > 10 )
         System.out.println( "*****" );
         else
         System.out.println( "#####" );
         System.out.println( "$$$$$" );
  1. (Palindromes) A palindrome is a sequence of characters that reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write an application that reads in a five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display an error message and allow the user to enter a new value.
  2. Write the program to determine the sum of the following harmonic series for a given value of n (input from command line).
1 + 1/2 + 1/3 + 1/4 + … + 1/n.
  1. The straight-line method of computing the early depreciation of the value of an item is given by
Depreciation = (purchase price – salvage value)/years of service.
Write a program to determine the salvage value of an item when the purchase price, years of service, and the annual depreciation are given.
  1. Write a program to find the number of and sum of all integers greater than 100 and less than 200 that are divisible by 7.
  2. Given a list of marks ranging from 0 to 100, write a program to compute and print the numbers of student who have obtained marks in the range
    1. in the range 81 to 100,
    2. in the range 61 to 80,
    3. in the range 41 to 60, and
    4. in the range 0 to 40
  3. Write a program that computes the sum of the digits of the given integer number.
  4. The number in the sequence 1 1 2 3 5 8 13 21 … are called Fibonacci numbers. Write a program to find nth Fibonacci number.[Hint: nth Fibonacci number is sum of (n-1)st and (n-2)nd Fibonacci numbers]



0 comments:

Post a Comment