Images

Core Java - PART II


Core Java
Core Java offers a total immersion approach for C\C++ programmer wanting to learn java.Core Java
The course will use JDK(Java Development Kit) and covers all the new language features.
This course inclues worked out examples illustrating new JDKfeatures that are fully explained thoughout the course.
Core Java has been carefully planned to help students create faster, smaller and more efficient Java application.



Operator and Expression
Expressions and Operators
Operators enable us to perform an evaluation or computation on a data object or objects.
Operators applied to variables and literals form expressions.
An expression can be thought of as a programmatic equation. Therefore, an expression is a sequence of one or more data objects (operands) and zero or more operators that produce a result.
An example of an expression follows:
x = y / 3;
In this expression, x and y are variables, 3 is a literal, and = and / are operators.

This expression states that the y variable is divided by 3 using the division
operator (/), and the result is stored in x using the assignment operator (=).

Here the expression is described from right to left.

Operator and Expression
Operator Precedence
Java expressions are typically evaluated from left to right, there still are many times when the result of an expression would be indeterminate without other rules.
The following expression illustrates the problem:
x = 2 * 6 + 16 / 4
By using the left-to-right evaluation of the expression, the multiplication operation 2 * 6 is carried out first, which leaves a result of 12. The addition operation 12 + 16 is then performed, which gives a result of 28. The division operation 28 / 4 is then performed, which gives a result of 7. Finally, the assignment operation x = 7 is handled, in which the number 7 is assigned to the variable x.

But--it's wrong! The problem is that using a simple left-to-right evaluation of expressions can yield inconsistent results, depending on the order of the operators.

The solution to this problem lies in operator precedence, which determines the order in which operators are evaluated. Every Java operator has an associated precedence.

Following is a list of all the Java operators from highest to lowest precedence.

In this list of operators, all the operators in a particular row have equal precedence.

The precedence level of each row decreases from top to bottom. This means that the [] operator has a higher precedence than the * operator, but the same precedence as the () operator.
.[]()
++-!~
*/%
+-
<<>>>>>
<><=>=
=!=
&
^
&&
||
?:
=
Evaluation of expressions still moves from left to right, but only when dealing with operators that have the same precedence.
Otherwise, operators with a higher precedence are evaluated before operators with a lower precedence.
Knowing this, take another look at the sample equation:
x = 2 * 6 + 16 / 4
Before using the left-to-right evaluation of the expression, first look to see whether any of the operators have differing precedence.
Here the multiplication (*) and division (/) operators both have the highest precedence, followed by the addition operator (+), and then the assignment operator (=).

Because the multiplication and division operators share the same precedence, evaluate
them from left to right. Doing this, we first perform the multiplication operation 2 * 6
with the result of 12. Then we perform the division operation 16 / 4, which results in 4.
After performing these two operations, the expression looks like this:
x = 12 + 4;
Because the addition operator has a higher precedence than the assignment operator, we perform the addition operation 12 + 4 next, resulting in 16. Finally, the assignment operation x = 16 is processed, resulting in the number 16 being assigned to the variable x.
As we can see, evaluating the expression using operator precedence yields a completely different result.
Just to get the point across, take a look at another expression that uses parentheses for grouping purposes:
x = 2 * (11 - 7);
Without the grouping parentheses, we would perform the multiplication operation first and then the subtraction operation. However, referring back to the precedence list, the () operator comes before all other operators. So the subtraction operation 11 - 7 is performed first, yielding 4 and the following expression:
x = 2 * 4;
The rest of the expression is easily resolved with a multiplication operation and an assignment operation to yield a result of 8 in the variable x.
    

Operator and Expression
Integer Operators
There are three types of operations that can be performed on integers:
1. unary,
2. binary,
3. And relational.
Unary operators act on only single integer numbers,

Binary operators act on pairs of integer numbers.

Both unary and binary integer operators typically return integer results.

Relational operators, act on two integer numbers but return a Boolean result rather than an integer.

Unary and binary integer operators typically return an int type. For all operations involving the types byte, short, and int, the result is always an int.
The only exception to this rule is when one of the operands is a long, in which case the result of the operation is also of type long.
Unary Integer Operators
Unary integer operators act on a single integer. Lists of the unary integer operators.
The unary integer operators.
DescriptionOperator
Increment++
Decrement--
Negation-
Bitwise complement~
The increment and decrement operators (++ and --) increase and decrease integer ariables by 1.

These operators can be used in either prefix or postfix form. A prefix operator takes effect before the evaluation of the expression it is in; a postfix operator takes effect after the expression has been evaluated.

Prefix unary operators are placed immediately before the variable; postfix unary operators are placed immediately following the variable. Following are examples of each type of operator:
y = ++x;
z = x--;
In the first example, x is prefix incremented, which means that it is incremented before being assigned to y.
In the second example, x is postfix decremented, which means that it is decremented after being assigned to z. Here z is assigned the value of x before x is decremented.
The IncDec program, which uses both types of operators.
The IncDec class.
class IncDec
{
public static void main (String args[])
{
int x = 8, y = 13;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("++x = " + ++x);
System.out.println("y++ = " + y++);
System.out.println("x = " + x);
System.out.println("y = " + y);
}

}
The IncDec program produces the following results:
x = 8
y = 13
++x = 9
y++ = 13
x = 9
y = 14
Output
The negation unary integer operator (-) is used to change the sign of an integer value.
x = 8;
y = -x;
In this example, x is assigned the literal value 8 and then is negated and assigned to y.
The resulting value of y is -8.
The Negation class.
class Negation
{
public static void main (String args[])
{
int x = 8;
System.out.println("x = " + x);
int y = -x;
System.out.println("y = " + y);
}

}
Output
The bitwise complement operator (~), which performs a bitwise negation of an integer value.
Bitwise negation means that each bit in the number is toggled. In other words, all the binary 0s become 1s and all the binary 1s become 0s.
Example:
x = 8;
y = ~x;
In this example, x is assigned the literal value 8 again, but it is bitwise complemented before being assigned to y.

Well, without getting into the details of how integers are stored in memory, it means that all the bits of the variable x are flipped, yielding a decimal result of -9. This result has to do with the fact that negative numbers are stored in memory using a method known as two's complement.

NOTE: Integer numbers are stored in memory as a series of binary bits that can each have a value of 0 or 1. A number is considered negative if the highest-order bit in the number is set to 1. Because a bitwise complement flips all the bits in a number--including the high-order bit--the sign of a number is reversed.
The Bitwise Complement class.
class BitwiseComplement
{
public static void main (String args[])
{
int x = 8;
System.out.println("x = " + x);
int y = ~x;
System.out.println("y = " + y);
}

}
Output
Binary Integer Operators
Binary integer operators act on pairs of integers. Lists of the binary integer operators.
The binary integer operators.
DescriptionOperator
Addition+
Subtraction-
Multiplication*
Division/
Modulus%
Bitwise AND&
Bitwise OR|
Bitwise XOR^
Left-shift<<
Right-shift>>
Zero-fill-right-shift>>>
The Arithmetic program, which shows how the basic binary integer arithmetic operators work.
The Arithmetic class.
class Arithmetic
{
public static void main (String args[])
{
int x = 17, y = 5;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x + y = " + (x + y));
System.out.println("x - y = " + (x - y));
System.out.println("x * y = " + (x * y));
System.out.println("x / y = " + (x / y));
System.out.println("x % y = " + (x % y));
}

}
The results of running the Arithmetic program follow:
x = 17
y = 5
x + y = 22
x - y = 12
x * y = 85
x / y = 3
x % y = 2
Output
The bitwise AND, OR, and XOR operators (&, |, and ^) all act on the individual bits of an integer. These operators are sometimes useful when an integer is being used as a bit field.
The Bitwise class.
class Bitwise
{
public static void main (String args[])
{
int x = 5, y = 6;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x & y = " + (x & y));
System.out.println("x | y = " + (x | y));
System.out.println("x ^ y = " + (x ^ y));
}

}
The output of running Bitwise follows:
x = 5
y = 6
x & y = 4
x | y = 7
x ^ y = 3
In Bitwise, the variables x and y are set to 5 and 6, which correspond to the binary numbers 0101 and 0110.
The bitwise AND operation compares each bit of each number to see whether they are the same. It then sets the resulting bit to 1 if both bits being compared are 1; it sets the resulting bit to 0 otherwise. The result of the bitwise AND operation on these two numbers is 0100 in binary, or decimal 4.
The bitwise OR operator sets the resulting bit to 1 if either of the bits being compared is 1. For these numbers, the result is 0111 binary, or 7 decimal.
Finally, the bitwise XOR operator sets resulting bits to 1 if exactly one of the bits being compared is 1 and 0 otherwise. For these numbers, the result is 0011 binary, or 3 decimal.
The left-shift, right-shift, and zero-fill-right-shift operators (<<, >>, and >>>) shift the individual bits of an integer by a specified integer amount.
Following are some examples of how these operators are used:
x << 3;
y >> 7;
z >>> 2;
In the first example, the individual bits of the integer variable x are shifted to the left three places.
In the second example, the bits of y are shifted to the right seven places.
Finally, the third example shows z being shifted to the right two places, with zeros shifted into the two leftmost places.
The Shift class.
class Shift
{
public static void main (String args[])
{
int x = 7;
System.out.println("x = " + x);
System.out.println("x >> 2 = " + (x >> 2));
System.out.println("x << 1 = " + (x << 1));
System.out.println("x >>> 1 = " + (x >>> 1));
}

}
The output of Shift follows:
x = 7
x >> 2 = 1
x << 1 = 14
x >>> 1 = 3
Output
The number being shifted in this case is the decimal 7, which is represented in binary as 0111. The first right-shift operation shifts the bits two places to the right, resulting in the binary number 0001, or decimal 1.

The next operation, a left-shift, shifts the bits one place to the left, resulting in the binary number 1110, or decimal 14.

The last operation is a zero-fill-right-shift, which shifts the bits one place to the right, resulting in the binary number 0011, or decimal 3.
    

Operator and Expression
Relational Integer Operators
The last group of integer operators is the relational operators, which all operate on
integers but return a type boolean. Lists of the relational integer operators.
The relational integer operators.
Description
Operator
Less-than<
Greater-than>
Less-than-or-equal-to<=
Greater-than-or-equal-to>=
Equal-to==
Not-equal-to!=
These operators all perform comparisons between integers.
The Relational class
class Relational
{
public static void main (String args[])

{
int x = 7, y = 11, z = 11;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
System.out.println("x < y = " + (x < y));
System.out.println("x > z = " + (x > z));
System.out.println("y <= z = " + (y <= z));
System.out.println("x >= y = " + (x >= y));
System.out.println("y == z = " + (y == z));
System.out.println("x != y = " + (x != z));
}

}
The output of running Relational follows:
x= 7
y = 11
z = 11
x < y = true
x > z = false
y <= z = true
x >= y = false
y == z = true
x != y = true
Output
    

Operator and Expression
Floating point Operators
There are three types of operations that can be performed on floating-point numbers:
1. unary,
2. binary,
3. and relational
Unary operators act only on single floating-point numbers,

binary operators act on pairs of floating-point numbers.

Both unary and binary floating-point operators return floating-point results.

Relational operators, act on two floating-point numbers but return a boolean result.

Unary and binary floating-point operators return a float type if both operands are of type float. If one or both of the operands are of type double, however, the result of the operation is of type double.
Unary Floating-Point Operators
The unary floating point operators act on a single floating-point number. Lists of the unary floating-point operators.
The unary floating-point operators.
DescriptionOperator
Increment++
Decrement--
The only two unary floating-point operators are the increment and decrement operators. These two operators respectively add and subtract 1.0 from their floating-point operand.
Binary Floating-Point Operators
The binary floating-point operators act on a pair of floating-point numbers. Lists of the binary floating-point operators.
The binary floating-point operators.
DescriptionOperator
Addition+
Subtraction-
Multiplication*
Division/
Modulus%
The binary floating-point operators consist of the four traditional binary operations (+, -, *, /), along with the modulus operator (%).
The FloatMath class.
class FloatMath
{
public static void main (String args[])
{
float x = 23.5F, y = 7.3F;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x + y = " + (x + y));
System.out.println("x - y = " + (x - y));
System.out.println("x * y = " + (x * y));
System.out.println("x / y = " + (x / y));
System.out.println("x % y = " + (x % y));
}

}
The output of FloatMath follows:
x = 23.5
y = 7.3
x + y = 30.8
x - y = 16.2
x * y = 171.55
x / y = 3.21918
x % y = 1.6
Output
    

Operator and Expression
Relational Floating-Point Operators
The relational floating-point operators compare two floating-point operands, leaving a boolean result.
Boolean Operators
Boolean operators act on boolean types and return a boolean result.
The boolean operators
DescriptionOperator
Evaluation AND&
Evaluation OR|
Evaluation XOR^
Logical AND&&
Logical OR||
Negation!
Equal-to==
Not-equal-to!=
Conditional?:
The evaluation operators (&, |, and ^) evaluate both sides of an expression before determining the result.
The following code shows how the evaluation AND operator is necessary for the complete evaluation of an expression:
while ((++x < 10) && (++y < 15)) {
System.out.println(x);
System.out.println(y);


}
The three boolean operators--negation, equal-to, and not-equal-to (!, ==, and !=)
The negation operator toggles the value of a boolean from false to true or from true to false, depending on the original value.
The equal-to operator simply determines whether two boolean values are equal (both true or both false).

Similarly, the not-equal-to operator determines whether two boolean operands are unequal.

The conditional boolean operator (? :) is the most unique of the boolean operators This operator also is known as the ternary operator because it takes three items: a condition and two expressions.

The syntax for the conditional operator follows:

Condition ? Expression1 : Expression2

The Condition, which itself is a boolean, is first evaluated to determine whether it is true or false. If Condition evaluates to a true result, Expression1 is evaluated. If Condition ends up being false, Expression2 is evaluated.
The Conditional class
class Conditional
{
public static void main (String args[])
{
int x = 0;
boolean isEven = false;
System.out.println("x = " + x);
x = isEven ? 4 : 7;
System.out.println("x = " + x);
}

}
The results of the Conditional program follow:
x = 0
x = 7
Output
    

Operator and Expression
String Operator
There is only one string operator: the concatenation operator (+). The concatenation
operator for strings works very similarly to the addition operator for numbers--it adds
strings together.
The Concatenation class
class Concatenation
{
public static void main (String args[])
{
String firstHalf = "What " + "did ";
String secondHalf = "you " + "say?";
System.out.println(firstHalf + secondHalf);
}

}
The output of Concatenation follows:
What did you say?
Output
In the Concatenation program, literal strings are concatenated to make assignments to
the two string variables, firstHalf and secondHalf, at time of creation. The two string
variables are then concatenated within the call to the println() method.
    

Operator and Expression
Assignment Operators
Assignment operators actually work with all the fundamental data types.
The assignment operators
Description
Operator
Simple=
Addition+=
Subtraction-=
Multiplication*=
Division/=
Modulus%=
AND&=
OR|=
XOR^=
Examples:
x += 6;
x *= (y - 3);
In the first example, x and 6 are added and the result stored in x.
In the second example, 3 is subtracted from y and the result is multiplied by x.
The final result is then stored in x
    

Operator and Expression
Arithmetic assignment operations
  1. Combine arithmetic and assignment into a single operation to save coding time
  2. All five basic arithmetic operations have a corresponding arithmetic assignment operator .
Operator
Operation
+=Addition assignment
-=Subtraction assignment
*=Multiplication assignment
/=Division assignment
%=Modulo (remainder) assignment
Example:
This program reads a percentage value from the user (such as 5.5) and converts to the correct decimal equivalent (such as 0.055) by using the division assignment operator.
import java.util.*;
import java.io.*;

public class AppStr
{
public static void main(String[] args)
{

// Variable for holding a percentage entered by the user // Prompt for and read the percentage System.out.print("Enter a percentage in n.nn format: ");
double percent;
Scanner Keyboard = new Scanner(System.in);

percent = Keyboard.nextDouble();
//percent = Keyboard.readDouble();
// Convert it to its decimal equivalent and display the result
percent /= 100;
System.out.println("The decimal equivalent is " + percent);
}
}
Output
    

Operator and Expression
Conversions
Conversion is performed automatically when mixed numeric types appear within an expression.

Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss during the calculation. This is known as a "widening" conversion.
The order of conversion (from narrowest to widest) is as follows. Memorize this table!
The data type resulting from an expression is that of the largest or most precise variable or constant appearing in the expression but is never smaller than int.
Example:
This program to convert a fahrenheit temperature to celsius will NOT compile.
import
java.util.*;
import java.io.*;
public class Conversion
{
public static void main(String[] args)
{

// Variables for holding fahrenheit and celsius temperatures

float tempC;

// Prompt for and read the fahrenheit temperature

System.out.print("Enter the fahrenheit temperature (nn.n): ");
Scanner Keyboard=new Scanner(System.in);
double tempF;
tempF= Keyboard.nextDouble();

// Convert to celsius and display the result

tempC = 5 * (tempF - 32) / 9;
System.out.println("Celsius equivalent is " + tempC);

}
}
Note:
To fix the compile error in this code, tempC must be double or tempF must be float .
After Correction changing the tempC into double the result is.....
    

Operator and Expression
Casts
1. Are a programmer's way of telling the compiler to ignore possible loss of data or
precision that might result from a conversion?
2. Should be used with caution. Data loss is not to be taken lightly.
3. The general syntax is
identifier = (data-type) expression;
Example:
This is a corrected version of the previous program that uses a cast to prevent the compile error.
import java.util.*;
import java.io.*;
public class Application
{
public static void main(String[] args)
{

// Variables for holding fahrenheit and celsius temperatures

float tempC;

// Prompt for and read the fahrenheit temperature

System.out.print("Enter the fahrenheit temperature (nn.n): ");
Scanner Keyboard=new Scanner(System.in);
double tempF;
tempF=Keyboard.nextDouble();

// Convert to celsius and display the result

tempC = (float) (5 * (tempF - 32) / 9);
System.out.println("Celsius equivalent is " + tempC);
}
}
Output
Some thing on arithmetic expressions
Arithmetic expressions can be large and complex with several variables, constants, and operators. The order in which operations are performed is the same as in mathematics (multiplication and division first, then addition and subtraction, working from left to right).

To avoid confusion, good programmers keep their expressions as simple as possible and use parenthesis for clarity.
    

Operator and Expression
Boolean expressions and operations
Boolean expressions
1. Always result in a boolean value (either true or false)
2. Are used to resolve logic questions, such as determining if two variables have the same     value?
3. May contain several different operators?
Comparison operators
1. Used to compare the values of two variables or constants
2. Require that the two operands be either both numeric (including char) or both      boolean. A numeric value cannot be compared to a boolean value.
3. Frequently appear in if, for, while, and do-while statements (to be covered later)
Operator
Operation
<Less than
<=Less than or equal
>Greater than
>=Greater than or equal
==Equal
!=Not equal
Example:
This program reads two numeric values from the user and displays the result of several comparisons involving the two numbers.
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Variables for holding two numeric values entered by the user

int x;
double y;

// Prompt for and read the two numeric values

System.out.print("First number (integer): ");
Scanner Keyboard=new Scanner(System.in);
int x;
x=Keyboard.nextInt(();
System.out.print("Second number (floating-point): ");
Scanner Keyboard=new Scanner(System.in);
double y;
y=Keyboard.nextDouble();

// Display information comparing the two values

System.out.println(" " + x + " < " + y + " is " + (x "<" y));
System.out.println(" " + x + " <= " + y + " is " + (x <= y));
System.out.println(" " + x + " > " + y + " is " + (x > y));
System.out.println(" " + x + " >= " + y + " is " + (x >= y));
System.out.println(" " + x + " == " + y + " is " + (x == y));
System.out.println(" " + x + " != " + y + " is " + (x != y));
}
}
Output
    

Operator and Expression
Logical operators
1. Combine the results of two Boolean expressions into a single boolean value
2. Provide for complex logic. The following table shows the operators and how they can be
 used to combine the results of two Boolean expressions X and Y:
Operator
Operation
Resulting value true if...
X and Y always evaluated?
&ANDX and Y are both trueYes
|OReither X or Y is trueYes
^XOR (exclusive OR)X and Y have different valuesYes
&&Conditional ANDX and Y are both trueNo
||Conditional OReither X or Y is trueNo\
The conditional AND ( && ) and OR ( || ) are sometimes called "short-circuit" operators because the second operand is not always evaluated depending on the value of the first operand. If the first operand is false, the result of an AND will always be false regardless of the value of the second operand. If the first operand is true, the result of an OR will always be true regardless of the value of the second operand.
Example:
The following program uses two values entered by the user to determine if a customer is entitled to free shipping. A customer receives free shipping if their order amount is greater than or equal to 100 and they are a preferred customer.
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Variables for holding order amount and valued customer data to be
// entered by the user


// Variables for holding information about free shipping

boolean isFree;

// Prompt for and read order amount and valued customer data

System.out.print("Order amount (floating-point): ");
Scanner Keyboard= new Scanner(System.in);
double amount;
amount =Keyboard.nextDouble();
System.out.print("Valued customer? (Y)es or (N)o: ");
Char valuedCust;

valuedCust = Keyboard.nextChar();

// Determine and display information about free shipping.
// Shipping is free if the order amount is greater than or equal $100
// AND the customer is a valued customer.

isFree = (amount >= 100 && (valuedCust == 'Y' || valuedCust == 'y'));
System.out.println(" Free shipping? " + isFree);
}
}
Output
Certain logical operators can be combined with assignment
1. The operators are &= (AND equals), |= (OR equals), and ^= (XOR equals)
2. The left operand must be boolean
Example:
The following program reads a boolean value from the user and displays its opposite value.
public class AppCer
{
public static void main(String[] args)
{

// Variable for holding a boolean value entered by the user

boolean value;

// Prompt for and read the boolean value

System.out.print("Enter a boolean value (true or false): ");
value = Keyboard.readBoolean();

// Determine the opposite value. If the value is false, XOR with
// true results in true. If the value is true, XOR with true results
// in false.

value ^= true;

// Display the new value of the value.

System.out.println(" The opposite value is " + value);
}
}
***try this yourself
    

Operator and Expression
Bitwise operations
Bitwise operations act upon individual bits within integer data.
They are used to perform the logical operations AND, OR, and XOR (eXclusive OR), complementing (reversing all bits), and shifting (sliding bits to the left or right).
Logical bitwise operations
1. Use the standard boolean operators (&, |, and ^) to act upon two integer values. The     short-circuit boolean operators (&& and ||) are not used for bitwise operations and will     result in a compile error if attempted.
2. Produce an integer result (of size int or larger) that is the logical AND, OR, or XOR of two     operands.
The rules for these operations are as follows:
Operation
Rule
&If both corresponding operand bits are "on" the result bit is "on"
|If either corresponding operand bit is "on" the result bit is "on"
^If corresponding operand bits are different the result bit is "on"
    

Operator and Expression
The complement operator
1. Is unary (has a single operand)?
2. Uses the ~ operator to "flip" (reverse) the bits within an integer value. If a bit is "on" it is     turned "off". If a bit is "off" it is turned "on".
For example,
if
byte a = 17; // Binary value: 0001 0001 Hex value: 11
byte b;
after executing the statement
b = (byte) ~a;
variable b will have a value of -18 (because 0001 0001 reverses to 1110 1110). Once again, the cast is needed in order to store the int value that results from the operation.
Example:
The following program can be run to test complement operations.
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Variable to be read from the user


// Prompt for and read an integer value

System.out.print("Integer: ");
Scanner Keyboard=new Scanner(System.in);
int number;
number=Keyboard.nextInt();


// Display the result of complementing the number

System.out.println(" ~" + number + " = " + ~number);
}
}
Output
    

Decision making, Branching and Looping
Flow control with if and else
The if and else statements allow a block of code or a single statement to be ither executed or bypassed depending upon the result of a comparison operation.
They are an essential part of Java "flow control" by which execution may proceed along alternate logic paths within a program.
    

Decision making, Branching and Looping
The if statement
1. Identifies a single statement or a block of statements to be executed if an      expression evaluates to true.
2. Have two forms.
The general syntax is either of the following:
if (expression) statement;
or
if (expression)
{
statements;
}
The first form is often referred to as a "single statement if".
For example,
if (amountDue > 0)
System.out.println("You owe " + amountDue);
will display the message only if the value of amountDue is greater than zero. The logic path merges at the next statement in the program.
The second form is often referred to as a "multiple statement if".
For example,
if (amountDue > 0)
{
totalDueFromAllCustomers += amountDue;
System.out.println("You owe " + amountDue);
}
will add to the grand total and display the message only if the value of amountDue is greater than zero. The logic path merges at the first statement after the end of the statement block.
3) Can lure unsuspecting programmers into some nasty errors.
For example,
if (amountDue > 0);
System.out.println("You owe " + amountDue);
will display the message no matter what value amountDue has.
    

Decision making, Branching and Looping
The else statement
1) Defines an alternative and mutually exclusive logic path to be followed if the      preceding if statement expression evaluates to false
2) Must always be paired with, and follow, an if statement. It can never be coded separately
3) Have two forms.
The general syntax is either of the following:
else statement;
or

else
{
statements;
The first form is often referred to as a "single statement else".
For example,
if (amountDue > 0)
System.out.println("You owe " + amountDue);
else
System.out.println("You owe nothing");
will add to the grand total and display how much is owed if amountDue is greater than zero. Otherwise, the customerRating will be set to 'A' and the "You owe nothing" message will be displayed.
The two logic paths are mutually exclusive and merge at the first statement after the end of the else block.
4) Can trap programmers who get sloppy.
For example,
if (age < 65)
System.out.println("Regular admission");
else;
System.out.println("Senior admission");
will always display the "Senior admission" message no matter what value age has. The accidental semicolon after the else says that if the expression is false you want to do nothing. Logic then merges at the next statement, so the message is always displayed.
Nesting


It is permitted.
An if or an if-else can be coded within an if or an if-else.
Example:
import java.util.*;
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

System.out.print("Enter age: ");
Scanner Keyboard= new Scanner(System.in);
int age;
age=Keyboard.nextInt();
if (age >= 10)
{
if (age < 65)
{
System.out.println("$5 admission");
}
else
{
System.out.println("$4 admission");
}
}
else
{
if (age < 5)
{
System.out.println("Free admission");
}
else
{
System.out.println("$2 admission");
}
}

}
}
Output
Notes:
1. The program prompts for and reads a person's age from the user.
2. Based upon the value of age, it displays a different admission fee (under 5 is free, 5-17     is 2 dollars, 18-64 is 5 dollars, and 65 and over is 4 dollars).
    

Decision making, Branching and Looping
Switch statements
Flow control with if and else statements gets cumbersome when a variable must be tested for a large number of possible values, such as a menu selection that permits the user to enter an integer from 1 to 20. The solution to this problem is the switch statement.
The switch statement
1) Specifies an expression whose value is be tested. This is known as the "switch      expression" and is typically the name of a single variable.
2) Defines a number of "cases", each associated with a different value. There may also be     a "default" case that is not associated with a value. If the value of the switch expression     is equal to the value of a case, the statements for that case will be executed. Otherwise,     the statements of the default case will be executed.
3) General syntax:
switch (expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
break;
}
It has a number subtleties and restrictions:
1. The switch expression must be a primitive of type int or able to be promoted to int.     Specifically, it must be either byte, short, int, or char. Expressions of type boolean, long,     float, and double will not compile.
2. The value specified on a case must be a constant of type int or must be able to be     promoted to int (in other words a byte, short, int, or char). It must also be within the     possible range of values of the switch expression. For example, if the switch variable is a     byte, a case with a value of 200 would not compile because a byte may only have a     value from -128 to 127.
The value of a case may be an expression as long as the result is a constant.
For example,
case 5 + 1:
would compile successfully.
3. The break statement is optional and will be covered in more detail in a later lesson.     When encountered, it ends the execution of the switch statement. If omitted from a     case, processing falls through to the next case (a sometimes undesirable result).
4. Although the compiler doesn't care, cases should be arranged in a high probability to low     probability order to enhance processing efficiency. The default can be placed anywhere     (even first).
It may be nested.
A switch can be coded within another switch or in either leg of an if-else.
It can also contain if-else code.
Example:
import java.util.*;
import java.io.*;
import java.lang.*;
public class Aman
{
public static void main(String[] args)
{

// Variables
// Prompt for and read data

System.out.print("Enter customer's starting balance: ");
Scanner Keyboard=new Scanner(System.in);
Double balance;
balance = Keyboard.readDouble();
System.out.print("Enter transaction amount: ");
double amount;
amount = Keyboard.readDouble();
System.out.println("Transaction codes are");
System.out.println(" " + "C - charge");
System.out.println(" " + "P - payment");
System.out.println(" " + "R - refund or return");
System.out.print("Enter transaction code: ");
char code;
code = Keyboard.readChar();

// Process based upon transaction code

switch (code)
{
case 'C':
case 'c':
balance += amount;
System.out.println("New balance is " + Utility.moneyFormat(balance));
break;
case 'P':
case 'p':
balance -= amount;
System.out.println("New balance is " + Utility.moneyFormat(balance));
break;
case 'R':
case 'r':
balance -= amount;
System.out.println("New balance is " + Utility.moneyFormat(balance));
break;
default:
System.out.println("Invalid transaction code");
break;
}
}
}
***try it with the help of under given suggestion.
Notes:
1. The balance, code, and amount variables hold data entered by the user.
2. After all data has been read from the user, the transaction is processed by the switch     statement with the transaction code (code) used as the switch expression.
3. Within the switch, if the value of code matches the value of a particular case, processing     jumps to the statement block for that case, otherwise processing jumps to the statement     block for the default. Processing will then continue until either a break statement is     encountered or the end of the switch is reached.
4. Stacking two or more cases without at break statement constitutes an OR.
For example,
case 'R':
case 'r':
will result in the same processing being performed if the value of code is either an uppercase or lowercase 'R'.
5. For transactions with a valid transaction code, the customer's new balance is displayed     using the moneyFormat() method of my Utility class. If the transaction code is bad, an     error message is displayed.
    

Decision making, Branching and Looping
for, while, and do-while statements
The ability to "loop" by executing one or more statements repetitively is an important part of programming.
Loops reduce the number of statements a programmer must code and result in a smaller, more memory efficient program.
In Java, looping is performed using the for, while, and do-while statements.
    

Decision making, Branching and Looping
The for statement
1) It is useful when the number of passes (iterations) can be predetermined
The general syntax
for (initialization; condition; update)
{
statements;
}
where:
initialization - represents the declaration of one or more local variables of the same data type. When loop processing is complete, all such variables are destroyed.
condition - represents a binary expression that, if true, allows the loop to continue. The condition is tested prior to each iteration. If no longer true, processing continues at the first statement after the closing brace of the for loop.
update - represents one or more expressions to be executed at the end of each iteration.
The braces may be omitted if the loop consists of a single statement. This would constitute a "single statement for loop".
Example 1:
Counting to 10 with a local variable
for (int i = 1; i <= 10; i++)
System.out.println(i);
This is a single statement for loop.
Local variable i is initialized to 1 before the first iteration and is used for loop control (its value determines when the loop will end). As long as i is less than or equal to 10, looping will continue. At the end of each iteration, i is incremented. Within each iteration, the current value of i is displayed.
When the condition is no longer true, processing will continue at the next statement in the program and variable i will be destroyed.
Example 2:
Counting to 10 without a local variable
Counting to 10 without a local variable
int i = 1;
for (; i <= 10; i++)
System.out.println(i);
System.out.println("Now i is " + i);
Here loop control variable i is initialized outside the loop, it will not be destroyed when the loop completes. Its final value (which will be 11) is displayed by the statement after the loop.
Notice that when no initialization expression is coded, a place holding semicolon is still required.
Example 3:
Coding multiple initialization and update expressions
for (int i = 1, j = 10; i <= 10; i++, j--)
System.out.println(i + " x " + j + " = " + (i * j));
This loop initializes two local variables, i and j, of the same data type before the first iteration.
At the end of each iteration, i is incremented and j is decremented. Within each iteration, the product of i and j is displayed.
Notice that commas are used to separate multiple initialization and update expressions.
It can be nested.
For example,
the following program generates a simple 9 x 9 multiplication table:
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// This outer loop generates one row of the multiplication
// table during each iteration.

for (int row = 1; row <= 9; row++) {

// This inner loop generates one column of the current row
// of the multiplication table during each iteration.

for (int column = 1; column <= 9; column++)
{

// If a one digit number is about to be displayed, preceed it
// with four spaces. Otherwise, preceed it with three spaces.

if ((row * column) < 10)
{
System.out.print(" ");
}
else
{
System.out.print(" ");
}

// Display the number.

System.out.print((row * column));
}

// End the current line.

System.out.print(" ");
}
}
}
Output
    

Decision making, Branching and Looping
The while statement
1) It Defines a block of code to be executed as long as a particular condition is met.
The condition is tested prior to each iteration.
It has the general syntax
while (condition)
{
statements;
}
where condition represents a binary expression that, if true, permits an iteration of the loop. If no longer true, processing continues at the first statement after the closing brace of the while loop.
The braces may be omitted if the loop consists of a single statement. This would constitute a "single statement while loop".
1) It does not provide for initialization of variables or automatic update expressions. In     spite of these limitations, a while loop can be used in place of nearly any for loop as     shown by these examples:
Example 1:
Counting to 10 without a local variable
int i = 1;
while (i <= 10)
{
System.out.println(i);
i++;
}
Loop control variable i is initialized outside the loop. Prior to each iteration, the value of i is tested to determine if it is still less than or equal to 10. If so, the current value of i is displayed and i is incremented. Otherwise processing will jump to the first statement after the closing brace of the loop.
Example 2:
An endless loop
while (true)
System.out.println("I won't end");
This is the preferred technique for launching an endless loop.
Example 3:
A small program using nested while loops to generate a 9 x 9 multiplication table:
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Initialize the row number.

int row = 1;

// This outer loop generates one row of the multiplication
// table during each iteration.

while (row <= 9)
{

// Initialize the column number.

int column = 1;

// This inner loop generates one column of the current row
// of the multiplication table during each iteration.

while (column <= 9)
{

// If a one digit number is about to be displayed, preceed it
// with four spaces. Otherwise, preceed it with three spaces.

if ((row * column) < 10)
{
System.out.print(" ");
}
else {
System.out.print(" ");
}

// Display the number.

System.out.print((row * column));

// Increment the column number.

column++;
}

// End the current line.

System.out.print(" ");

// Increment the row number.

row++;
}
}
}
Output
    

Decision making, Branching and Looping
The do-while statement
1) It defines a block of code to be executed as long as a particular condition is met. The     condition is tested at the end of each iteration. It always guaranteed at least one pass     through a do-while loop.
syntax
do
{
statements;
} while (condition);
where condition represents a binary expression that, if true, permits another iteration of the loop to be performed. If no longer true, processing continues at the next statement.
The braces may be omitted if the loop consists of a single statement. This would constitute a "single statement do-while loop".
It can be used in place of nearly any while loop as shown by these examples:
Example 1:
Counting to 10 without a local variable
int i = 1;
do
{
System.out.println(i);
i++;
} while (i <= 10);
Loop control variable i is initialized outside the loop. Within the loop, the current value of i is displayed and i is incremented. At the end of each iteration, the value of i is tested to determine if it is still less than or equal to 10. If so, the body of the loop is repeated. Otherwise processing will jump to the next statement.
Example 2:
An endless loop
do
{
System.out.println("I won't end");
} while(true);
Example 3:
A small program using nested do-while loops to generate a 9 x 9 multiplication table
import java.io.*;
public class Aman
{
public static void main(String[] args)
{

// Initialize the row number.

int row = 1;

// This outer loop generates one row of the multiplication
// table during each iteration.

do
{

// Initialize the column number.

int column = 1;

// This inner loop generates one column of the current row
// of the multiplication table during each iteration.

do
{

// If a one digit number is about to be displayed, preceed it
// with four spaces. Otherwise, preceed it with three spaces.

if ((row * column) < 10)
{
System.out.print(" ");
}
else
{
System.out.print(" ");
}

// Display the number.

System.out.print((row * column));

// Increment the column number.

column++;
} while (column <= 9);

// End the current line.

System.out.print(" ");

// Increment the row number.

row++;
}
while (row <= 9);
}
}
Output
    

Decision making, Branching and Looping
Using break and continue
At times, it is desirable to exit from a loop or short-circuit the current iteration of a loop. The break and continue statements make it happen.
  

Decision making, Branching and Looping
The continue statement
1) Can only appear within a loop.
2) Skips all remaining statements within the loop and resumes with the next iteration.
For example,
for (int x = 0; x < 10; x++)
{
if (x == 5)
continue;
else
System.out.print(" " + x);
}
will short-circuit when x takes on a value of 5.
The output displayed will be:
0 1 2 3 4 6 7 8 9
3)It may specify the label of the loop to be continued. This makes it possible to skip to the    next iteration of the specified loop.
For example,
outer: for (int i = 1; i <= 5; i++)
{
for (int j = 5; j >= 1; j--)
{
if (i == j)
continue outer;
else
System.out.println("i = " + i + ", j = " + j);
}
}
will short-circuit to the next iteration of the loop labeled outer when i equals j.
The output displayed will be:
i = 1, j = 5
i = 1, j = 4
i = 1, j = 3
i = 1, j = 2
i = 2, j = 5
i = 2, j = 4
i = 2, j = 3
i = 3, j = 5
i = 3, j = 4
i = 4, j = 5
    

Class Object and Method
Introduction to Classes
Definition:
A class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind.
  

Class Object and Method
The Benefit of Classes
Objects provide the benefit of modularity and information hiding. Classes provide the benefit of reusability. Software programmers use the same class, and thus the same code, over and over again to create many objects.
  

Class Object and Method
Defining Classes
To define a class, we use the class keyword and the name of the class:
class MyClassName
{
...
}
By default, classes inherit from the Object class.
If this class is a subclass of another specific class (that is, inherits from another class), use extends to indicate the superclass of this class:
class myClassName extends mySuperClassName
{
...
}
Following is the code for a class called SimplePoint that represents a point in 2D space:
public class SimplePoint
{
public int x = 0;
public int y = 0;
}
This segment of code declares a class-- a new data type really-- called SimplePoint. The SimplePoint class contains two integer member variables, x and y. The public keyword preceding the declaration for x and y means that any other class can freely access these two members.
We create an object from a class such as SimplePoint by instantiating the class. When we create a new SimplePoint object space is allocated for the object and its members x and y. In addition, the x and y members inside the object are initialized to 0 because of the assignment statements in the declarations of these two members.
Ex:
public class SimpleRectangle
{
public int width = 0;
public int height = 0;
public SimplePoint origin = new SimplePoint();
}
Here the segment of code declares a class SimpleRectangle-- that contains two integer members, width and height.
SimpleRectangle also contains a third member, origin, whose data type is SimplePoint.
Here the class name SimplePoint is used in a variable declaration as the variable's type. We can use the name of a class anywhere we can use the name of a primitive type.
As with SimplePoint, when we create a new SimpleRectangle object, space is allocated for the object and its members, and the members are initialized according to their declarations.
The initialization for the origin member creates a SimplePoint object with this code: newSimplePoint() as illustrated here:
This diagram shows the difference between primitive types and reference types
    

Class Object and Method
Class using constructor
Here's a of SimpleRectangle, called Rectangle, that contains four constructors, a method to"move" the rectangle, a method to compute the area of the rectangle, and a finalize method to provide for clean up:
public class Rectangle

{

public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public Rectangle()
{
origin = new Point(0, 0);
}

public Rectangle(Point p)
{
origin = p;
}

public Rectangle(int w, int h)
{
this(new Point(0, 0), w, h);
}

public Rectangle(Point p, int w, int h)
{
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle

public void move(int x, int y)
{
origin.x = x;
origin.y = y;
}

// a method for computing the area of the rectangle

public int area()
{
return width * height;
}

// clean up!

protected void finalize() throws Throwable
{
origin = null;
super.finalize();
}

}
Here the four constructors allow for different types of initialization.
    

Class Object and Method
Object
An object is a distinct instance of its class (an actual occurrence). It has its own set of variables (known as "instance variables") and methods (known as "instance methods"). When called, an object's instance methods automatically act upon its instance variables Java program creates many objects from a variety of classes.
These objects interact with one another by sending each other messages. Through these object interactions, a Java program can implement a GUI, run an animation, or send and receive information over a network. Once an object has completed the work for which it was created, it is garbage-collected and its resources are recycled for use by other objects.
Creating Objects
In Java, we create an object by creating an instance of a class or, in other words, instantiating a class.
Ex:
Rectangle rect = new Rectangle();
The above single statement performs three actions:
1. Declaration: Rectangle rect is a variable declaration that declares to the compiler that the     name rect will be used to refer to a Rectangle object. Here a class name is used as the     variable's type.
2. Instantiation: new is a Java operator that creates the new object (allocates space for it).
3. Initialization: Rectangle() is a call to Rectangle's constructor, which initializes the object.
    

Class Object and Method
Declaring an Object
Like other variable declarations, object declarations can also appear alone, like this:
Rectangle rect;
Declarations notify the compiler that you will use name to refer to a variable whose type is type. Declarations do not create new objects. Rectangle rect does not create a new Rectangle object, just a variable named rect to hold a Rectangle object.
To create a Rectangle object, or any other object, use the new operator.
  

Class Object and Method
Instantiating an Object
The new operator instantiates a class by allocating memory for a new object of that type. new requires a single, postfix argument: a call to a constructor.
Each Java class provides a set of constructors used to initialize new objects of that type. The new operator creates the object, and the constructor initializes it.
Here's an example of using the new operator to create a Rectangle object:
new Rectangle(100, 200);
Here, Rectangle(100, 200) is the argument to new. The new operator returns a reference to the newly created object.
This reference can be assigned to a variable of the appropriate type, as here.
Rectangle rect = new Rectangle(100, 200);
  

Class Object and Method
Initializing an Object
The classes can provide one or more constructors to initialize a new object of that type.
We can recognize a class's constructors because they have the same name as the class and have no return type.
Here are the declarations for Rectangle's constructors:
public Rectangle(Point p)
public Rectangle(int w, int h)
public Rectangle(Point p, int w, int h)
public Rectangle()
If a class has multiple constructors, they all have the same name but a different number of arguments or different typed arguments.
The compiler differentiates the constructors, and knows which one to call, depending on the arguments.
Using Objects
Objects give us two ways to do these things:
1. Manipulate or inspect its variables.
2. Call its methods.
Java provides an access control mechanism whereby classes can restrict or allow access to its variables and methods.
A class should protect variables against direct manipulation by other objects if those manipulations could endanger the object's state. State changes should then be affected and therefore controlled by method calls.
    

Class Object and Method
Referencing an Object's Variables
Assume we create a rectangle named rect as described in the previous section. To move rect to a new location,
we would write:
rect.origin = new Point(15, 30);
This statement moves the rectangle by setting its point of origin to a new position. rect.origin is the name of rect's origin variable.
The Rectangle class has two other variables-- width and height-- that are accessible to objects outside of the class. We can use the same notation to access them and calculate the rectangle's area using this statement
area = rect.height * rect.width;;
In general, to refer to an object's variables, append the name of the variable to an object reference with an intervening period (.):
objectReference.variable
The first part of the variable's name, objectReference, must be a reference to an object.
    

Class Object and Method
Calling an Object's Methods
To move rect to a new location using its move method, we write this:
rect.move(15, 30);
This Java statement calls rect's move method with two integer parameters, 15 and 30. It moves the rect object because the rect method assigns new values to origin.x and origin.y, and is equivalent to the assignment statement used previously:
rect.origin = new Point(15, 30);
The notation used to call an object's method is similar to that used when referring to its variables: we append the method name to an object reference with an intervening period (.). Also, we provide any arguments to the method within enclosing parentheses. If the method does not require any arguments, use empty parentheses.
objectReference.methodName(argumentList);
or
objectReference.methodName();
    

0 comments: