Tải bản đầy đủ (.pdf) (54 trang)

Java programming Tài Liệu Lập Trình Java Căn Bản Full

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (563.07 KB, 54 trang )


Java Programming
Constructs
Chapter 4







In this chapter, you will learn to:
 Use conditional statements
 Use looping statements
 Enhance methods of a class
 Pass arguments to methods
 Create nested classes
Objectives

NIIT Java Programming Constructs 4.3

Conditional statements allow selective execution of a set of statements depending on the
value of expressions associated with them. Conditional statements are also known as
decision-making statements. You make decisions in your daily life, such as which ice
cream to have or which movie to watch. The same decision-making is also incorporated in
programs by using conditional statements. You can control the flow of a program by
using conditional statements. The two types of conditional statements in Java are:
 The if-else statement
 The switch statement



The
if-else statement enables you to execute the statement selectively. The if-else
statement is followed by a boolean expression. The following code snippet shows the
syntax of the
if-else statement:

if(boolean expression)
{
statement(s)
}
else
{
statement(s)
}
In the preceding code snippet, if the boolean expression of the if statement evaluates to
true, the Java compiler executes the statements following the
if statement. If the boolean
expression of the
if statement evaluates to false, the Java compiler executes the
statements following the
else construct. The if statement and the else statement can
contain either a single statement or multiple statements. Multiple statements are enclosed
within a pair of braces. The
else statement is optional in the if-else statement.
The
if-else statement uses a boolean expression, which comprises of relational
operators. Multiple boolean expressions are combined into a single boolean expression by
conditional operators.
Using Conditional Statements
Using the if-else Statement

4.4 Java Programming Constructs NIIT
Relational Operators
Relational operators are used to compare the values of two variables or operands and find
the relationship between the two. The relational operators are also called comparison
operators. The following table lists the various relational operators in Java.

Operator Use Operation
> op1 > op2
Returns true if the value of the op1 operand is greater
than the value of the op2 operand.
< op1<op2
Returns true if the value of the op1 operand is less than
the value of the op2 operand.
>= op1>=op2
Returns true if the value of the op1 operand is greater
than or equal to the value of the op2 operand.
<= op1<=op2
Returns true if value of op1 operand is less than or
equal to value of op2 operand.
== op1 ==op2
Returns true if value of op1 operand is equal to value of
op2 operand.
!= op1 != op2
Returns true if value of op1 operand is not equal to
value of op2 operand.
Relational Operators in Java
The following code shows the use of relational operators:

class RelationOp //class declaration
{

public static void main(String args[])
{
int age;
age =20; // Value assigned to the data member
if(age<10) // The if construct
{
System.out.println("The given age is below 10.");
//if the condition is true this statement is executed.
}
else
{ //if the condition is false, this construct is executed
if(age>10)
{
System.out.println("The given age is above 10.");
}
}
}
}
NIIT Java Programming Constructs 4.5
The following figure shows the output of the preceding code.

Using Relational Operators
Conditional Operators
The conditional operators are used to combine multiple conditions in one boolean
expression. Conditional operators are of two types, unary and binary. Unary conditional
operators operate on a single operand of a boolean type and the result is also a boolean.
Binary conditional operators operate on two boolean operands and the result is also a
boolean. The following table lists the various conditional operators and their operations.

Operator Use Operation

AND (&&) op1 && op2
Returns true if both the op1 operand and the op2
operand are true
OR (||) op1 || op2
Returns true if either the op1 operand or the
op2operand is true
NOT (!) ! op1 Returns true if the op1 operand is not true
Conditional Operators in Java
The NOT operator is an example of unary conditional operator because it operates on a
single boolean operand. The AND and OR operators are examples of binary conditional
operators because they operate on two operands.
4.6 Java Programming Constructs NIIT
The AND Operator
The AND operator performs an action after checking two conditions. The conditions are
boolean expressions and return either true or false. The AND operator returns true only if
both the conditions are true. If the first condition returns false, the second condition is not
evaluated and the AND operator returns false. The AND operator evaluates the conditions
from left to right.
Consider an example of a bank, which provides interest to its customers depending on the
present balance in the account of a customer. The rate of interest is 5% when the balance
is greater than zero and less than $10000, otherwise no interest is given. You can use the
following code to build this condition by using the AND operator:

class CalculateInterest
{
public static void main(String args[])
{
double balance = 6000; //Double is a floating point data type
if((balance > 0) && (balance < 10000))
//checks for the multiple conditions

{
System.out.println("Interest Rate offered is 5%");
}
else
{
System.out.println("No interest is offered");
}
}
}
In the preceding code, the balance in the account of the customer is $6,000 that is greater
than zero and less than $10,000. Therefore in the
if construct, the first condition and the
second condition return true. The AND operator returns true value only if both the
conditions are true. Therefore, the condition in the
if construct returns true and prints the
output, as "Interest rate offered is 5%".
NIIT Java Programming Constructs 4.7
The following figure shows the output of the preceding code.


Using the AND Operator
The OR Operator
The OR operator performs conditional OR operation on two conditions. The OR operator
returns true if at least one of the conditions evaluates to true and false if both the
conditions are false. If the first condition evaluates to true, then the second condition is
not evaluated and the OR operator returns true.
Consider an example of a bank that gives loans to its customers on the condition that
either the loan demanded by the customer must be less than $5000 or the customer must
be able to return the loan within five years. You can use the following code that uses the
OR operator to decide whether a customer is eligible for bank loans:


class Loan
{
public static void main(String args[])
{
double LoanRequest = 4000;
int nOfYear = 6;
if((LoanRequest < 5000) || (nOfYear < 5))
{
System.out.println("Loan can be offered.");
}
else
{
System.out.println("No Loan is offered.");
}
}
}
4.8 Java Programming Constructs NIIT
In the preceding code, the OR operator contains two conditions; one condition checks the
loan request amount and the second condition checks the loan repayment duration. The
loan demanded by the customer is $4000, which is less than $5000, as a result the first
condition returns true. The number of years needed by the customer to repay the loan is
six years, as a result the second condition returns false. Since the first condition in the OR
operator evaluates to true, therefore the OR operator in the if construct returns true and
the message, “Loan can be offered” is displayed.
The following figure shows the output of the preceding code.

Using the OR Operator
The NOT Operator
The NOT operator is a unary operator because it operates only on one operand. It returns

false if its operand value is true and returns true if the operand value is false. Consider an
example of a bank that gives loan to its customers if the loan demanded by the customer is
less than $5000 and the bank has not given a loan to the customer previously. You can use
the following code to print an output whether loan can be offered to a customer or not:

class LoanRequest
{
public static void main(String args[])
{
boolean preLoanRequest = false;
double LoanAmount = 4000;
if((!(preLoanRequest)) && (LoanAmount < 5000))
{ // The NOT operator evaluates the boolean false value of the
preLoanRequest data member value to true
System.out.println("Loan can be offered.");
}
else
{
NIIT Java Programming Constructs 4.9
System.out.println("No Loan is offered.");
}
}
}
In the preceding code, preLoanRequest is a boolean variable, which is set to false and it
shows that the customer has not availed any previous loan facility. The NOT operator
applied on the
preLoanRequest variable returns true and requested loanAmount is also
less than 5000. Therefore, both the conditions in the
if construct are true and the AND
operator returns true. The message, “Loan can be offered” gets displayed.

The following figure shows the output of the preceding code.

Using the Not Operator
Multiple if-else Statements
Java also supports another form of the if-else statement. You can replace a single if
statement with multiple
if-else statements to write a compound if statement. The
multiple if-else construct allows you to check multiple boolean expressions in a
single compound
if statement. The following code snippet shows the syntax of the
multiple
if-else statements:

if (Boolean_expression_1)
{
statements
}
else if (Boolean_expression_2)
{
statements
}
else if (Boolean_expression_3)
{
4.10 Java Programming Constructs NIIT
statements
}
else
{
statements
}

For example, you can use the following code to print the rate of interest offered to a
customer depending on the balance amount in the account of a customer:

class MultipleCond
{
public static void main(String args[])
{
double balance = 12000;
if((balance != 0) && (balance < 5000))
{
System.out.println("Interest rate offered is 2%.");
}
else if((balance >= 5000) && (balance < 10000))

{
System.out.println("Interest rate offered is 4%.");
}
else if((balance >= 10000) && (balance < 15000))

{
System.out.println("Interest rate offered is 7%.");
}
else
{
System.out.println("Interest rate offered is 10%.");
}
}
}
In the preceding code, the interest rate offered is decided by using multiple if-else
statements. Multiple

if-else statements check the balance amount to decide the correct
interest rate.
NIIT Java Programming Constructs 4.11
The following figure shows the output of the preceding code.

Using the Multiple if-else Statements


The switch statement successively tests the value of an expression or a variable against a
list of case labels with integer or character constants. When a match is found in one of the
case labels, the statements associated with that case label get executed. The
switch
keyword in the switch statement contains the variable or the expression whose value is
evaluated to select a case label. The
case keyword is followed by a constant and a colon.
The data type of a case constant should match the data type of the switch variable. The
following code snippet shows the syntax of the switch statement:

switch(expression or variable name)
{
case Expr1:
statements;
break;
case Expr2:
statements;
break;
case Expr3:
statements;
break;
default:

statements;
}
The switch Statement
4.12 Java Programming Constructs NIIT
In the preceding code snippet, statements associated with the default keyword are
executed if the value of the switch variable does not match any of the case constants. The
break statement used in the case label causes the program flow to exit from the body of
the switch
statement. The following code shows the use of the switch statement:

class TestSwitchCase
{
public static void main(String args[])
{
char X='d';
switch(X)
{
case 'a':
System.out.println("The variable X is an
alphabet and value is:" + X );
break;
case 'b':
System.out.println("The variable X is an
alphabet and value is:" + X );
break;
case 'c':
System.out.println("The variable X is an
alphabet and value is:" + X );
break;
case 'd':

System.out.println("The variable X is an
alphabet and value is:" + X );
break;
}
}
}
In the preceding code, X is a character type variable and is initialized with value, d. The
switch construct compares the value of the
X variable successively against the list of
character constants in case constructs. Since
X has the value, d, therefore the first, second,
and third case constructs are not executed and the case with value,
d is executed.
NIIT Java Programming Constructs 4.13
N
ot
e
The following figure shows the output of the preceding code.


Using the switch-case Construct


The data type of a variable in the switch statement can only be a byte, char, short,
or
int. The switch statement cannot take a variable of double or float data type.

The break Statement
The break statement causes the program flow to exit from the body of the switch
statement. Control goes to the first statement following the end of the statement. If the

break statement is not used inside a case construct, the control passes to the next case
statement and the remaining statements, in the switch statement, are executed.

4.14 Java Programming Constructs NIIT

Problem Statement
The Certified Careers Institute is granting scholarship to those students who passed in
each subject and scored more than 175 marks out of 200 marks. Steve is a Java developer
in the institute. He is assigned the task of developing the Java application that enables the
user to select the eligible students. Before creating the application for all the students, he
tests the application for a specific student David. David has passed each subject and
scored 180 marks. Help Steve to code the application for David.
Solution
You can solve the preceding problem either by using:
 The notepad editor
 NetBeans IDE
Using the Notepad Editor
To solve the preceding problem by using the notepad editor, Steve needs to perform the
following tasks:
1. Code the application.
2. Compile and execute the application.
Task 1: Coding the Application
Steve has to create the Student class in which the printStatus()method checks if
David is applicable for scholarship. He needs to write the following code in the notepad
editor to create the
Student class and save it as Student.java file:

class Student
{
boolean allpass;

int totalmarks;
Student()
{
allpass = true;
totalmarks = 180;
}
void printstatus()
{
Activity 1: Implementing Constructs
NIIT Java Programming Constructs 4.15
if((allpass != false) && (totalmarks > 175))
System.out.println("Scholarship granted");
else
System.out.println("Scholarship not granted");
}
public static void main(String args[])
{
Student std1 = new Student();
System.out.println("Scholarship status of David:");
std1.printstatus();
}
}
Task2: Compiling and Executing the Application
To compile and execute the application, Steve needs to perform the following steps:
1. Open the Command Prompt window.
2. Type the following command in the Command Prompt window to compile the
Student class:
javac Student.java
3. Press the Enter key.
4. Type the following command in the Command Prompt window to execute the

application:
java Student
5. Press the Enter key. The output is displayed in the Command Prompt window, as
shown in the following figure.

Displaying Grant of Scholarship

6. Close the Command Prompt window.
7. Close the notepad editor.
4.16 Java Programming Constructs NIIT
Using NETBeans IDE
To solve the preceding problem by using NETBeans IDE, you need to perform the
following tasks:
1. Code the application.
2. Compile and execute the application.
Task 1: Coding the Application
To create a Java application by using Netbeans IDE, you need to perform the following
steps:
1. Select startÆAll ProgramsÆNetBeans 5.5.1ÆNetBeans IDE. The NetBeans IDE
5.5.1 window appears, as shown in the following figure.

The NetBeans IDE 5.5.1 Window

2. Select FileÆNew Project. The New Project window appears.
3. Ensure that the General option is selected in the Categories section of the Choose
Project page.
4. Select the Java Application option in the Projects section of the Choose Project
page.
5. Click the Next button. The Name and Location page is displayed.
6. Type Scholarship in the Project Name text box.

NIIT Java Programming Constructs 4.17
N
ot
e
7. Type <Drive Letter>:\JavaProjects in the Project Location text box.


Ensure that the JavaProjects folder exists in the specified drive. You can click the
Browse button to select the desired location where you want to save the project.

8. Ensure that the Set as Main Project check box is selected.
9. Ensure that the Create Main Class check box is selected.
10. Type scholarship.Student in the text box adjacent to the Create Main Class check
box.
11. Click the Finish button. The NetBeans IDE 5.5.1 – Scholarship window is
displayed.
12. Ensure that the Student.java tab is selected.
13. Replace the existing code with the following code snippet:

package scholarship;
class Student
{
boolean allpass;
int totalmarks;
Student()
{
allpass = true;
totalmarks = 180;
}
void printstatus()

{
if((allpass != false) && (totalmarks > 175))
System.out.println("Scholarship granted");
else
System.out.println("Scholarship not granted");
}
public static void main(String args[])
{
Student std1 = new Student();
System.out.println("Scholarship status of David:");
std1.printstatus();
}
}

4.18 Java Programming Constructs NIIT
Task 2: Compiling and Executing the Application
To compile and execute the application in NetBeans IDE, you need to perform the
following steps:
1. Select BuildÆCompile “Student.java” to compile the file.
2. Select RunÆRun FileÆRun “Student.java” to execute the code. The output is
displayed in the output window as shown in the following figure.

The Output Displayed in the Output Window

3. Select FileÆClose “Student” to close the application.
4. Select FileÆExit to close the NetBeans IDE.

NIIT Java Programming Constructs 4.19

A looping statement causes a section of a program to be executed a certain number of

times. The repetition continues while the condition set in the looping statement remains
true. When the condition becomes false, the loop ends and the control passes to the
statement following the loop.


The for loop is a looping statement iterating for a fixed number of times. The for loop
consists of the
for keyword followed by parentheses containing three expressions, each
separated by a semicolon. These three expressions are the initialization expression, the
test expression, and the iteration expression. The for loop is used when the number of
iterations is known in advance. For example, it can be used to determine the square of
each of the first ten natural numbers. The following code snippet shows the syntax of the
for loop:

for(Initialization Expr; Test Expr; IterationExpr)
{
statement_1
statement_2


}
In the preceding code snippet, the initialization expression is executed only once, when
the control is passed to the for loop for the first time. It gives the loop variable an initial
value. The condition in the test expression is executed each time the control passes to the
beginning of the loop in each loop iteration. The body of the loop is executed only after
the condition has been checked. If the condition evaluates to true, the loop is executed
otherwise the control passes to the statement following the body of the loop.
Using Looping Statements
The for Loop
4.20 Java Programming Constructs NIIT

The iteration expression is always executed when the control returns to the beginning of
the loop in each loop iteration, as shown in the following figure.

The for Loop
The following code shows the use of the for loop:

//TestForLoop.java
class TestForLoop
{
public static void main(String args[])
{
for(int i=1;i<6;i=i+1) /* i is the initialization
expression, which is checked to be less that 6. i=i+1 is
the iteration expression.*/
{
System.out.println("The value of i is:" + i);
// The statement is executed till the condition is true
}
}
}
NIIT Java Programming Constructs 4.21
In the preceding code, the i variable is initialized with the value 1 for the first time and
incremented by
1 in each iteration of the loop. The loop executes till the value of i
becomes
6.
The following figure shows the output of the preceding code.

Using the for Loop
The Enhanced For Loop

The enhanced for loop allows iterating through an array or collection without
creating an iterator or without having beginning and end conditions for a counter
variable. It can be used when you want to step through the elements of the array in
first-to-last order, and you do not need to know the index of the current element.

The syntax for enhanced for loop is:

for(declaration:expression)
where, declaration refers to the newly declared block variable and expression refers to the
array variable or a method call that returns an array. The colon in the syntax can be read
as “in”.
The following code shows the use of the enhanced for loop:

public class EnhanceDemo {
public static void main(String[] args) {
int myArr[] = {13,22,79,80};
for (int a : myArr) {
System.out.println(a);
}
}
}
4.22 Java Programming Constructs NIIT
The following figure shows the output of the preceding code.

Using the Enhanced for Loop


The while loop executes a statement or a block of statements as long as the evaluating
condition remains true. The while loop consists of the while keyword followed by
parenthesis containing an evaluating condition, which is a boolean expression. The

boolean expression must return a
boolean value that can be true or false. The following
code snippet shows the syntax of the while loop:

while(boolean expression)
{
statements;
}
In the preceding code snippet, the statements in the while loop are executed as long as the
boolean expression condition is
true. When the condition returns false, the statement
immediately following the while block is executed. The following code shows the use of
while loop by generating the Fibonacci series:

class TestWhileLoop
{
public static void main(String args[])
{
int num1 = 1, num2 = 1;
System.out.println("The Fibonacci series between 1 and 100:");
System.out.println(num1);
while (num2 < 100)
{
The while Loop
NIIT Java Programming Constructs 4.23
System.out.println(num2);
num2 += num1; // adding the value of num1 to num2
num1 = num2 - num1; // reassigning num1 to the difference
between num2 and num1
}

}
}
In the preceding code, the Fibonacci series between 1 and 100 is generated. In this series,
each number is the sum of its two preceding numbers. The series starts with
1. The num2
variable has value
1 outside the while loop. The while loop checks the value of num2 and
finds it less than
100. Therefore, the condition in the while loop is set to true and control
enters the body of the loop. In each loop iteration, the
num2 variable is incremented by
adding the value of the
num1 variable with the value of num2. When the value of num2
exceeds
100, the control comes out of the while loop.
The following figure shows the output of the preceding code.

Using the while Loop

4.24 Java Programming Constructs NIIT


In the while loop, the condition is evaluated at the beginning of the loop. If the condition
is false, the body of the loop is not executed. If the body of the loop needs to be executed
at least once, then the do-while loop should be used. The do-while construct places the
test condition at the end of the loop. The
do keyword marks the beginning of the loop and
braces form the body of the loop. Finally, the
while keyword provides the condition that
checks whether the loop will be executed again or not and ends the body of the loop. The

following code snippet shows the syntax of the do-while loop:

do
{
statements;
}
while(Bool_Expr);
The following code shows the use of the do-while loop:

class TestDoWhile
{
public static void main(String args[])
{
int num = 100;
do
{
System.out.println("Inside the do-while loop");
System.out.println("The value of variable num is:"
+ num);
}
while(num<100);
}
}
In the preceding code, the value assigned to the num variable is 100. The control enters
into the do-while construct without testing the value of the
num variable and executes the
statement inside the do-while loop. The while construct then checks the value of
num and
since the value is not less than
100 the control comes out of the do-while loop.

The do-
w
hile Loop
NIIT Java Programming Constructs 4.25
The following figure shows the output of the preceding code.

Using the do-while Loop
The preceding output shows that the body of the loop is executed once even if the
condition is false. If you write the same code in the while loop, the loop does not execute
even once.
The continue Statement
In the while and do-while loops, the continue statement returns the control to the
conditional expression that controls the loop. It skips the statements following the
continue statement in the loop body. In the for loop, control goes to the iteration
expression first and then to the conditional expression. In the while and do-while loops,
the control goes to the checking condition. The following code shows the use of the
continue keyword in a while loop to generate the Fibonacci series between 1 and 100:

class Fibonacci
{
public static void main(String args[])
{
int num1 = 1, num2 = 1;
System.out.println("The Fibonacci series between 1 and
100:");
System.out.println(num1);
while (num2 < 100)
{
if(num2 > 20 && num2 < 40)
{

//if the number in the Fibonacci series is between 20 and 40,
the following statement is displayed

System.out.println("Continue statement found. ");

×