Ngôn ngữ lập trình Java Tài liệu lập trình java căn bản đến nâng cao Java không còn là một ngôn ngữ xa lạ với cộng đồng lập trình. Với việc có lợi thế khi được sinh ra với tiêu chí “Write Once, Run Anywhere” (WORA) – tức là “Viết một lần, thực thi khắp nơi”, cùng với việc liên tiếp cải tiến tốc độ biên dịch chương trình, để từng bước thu hẹp khoảng cách về thời gian biên dịch với các ngôn ngữ C, C++, … Java đã thực sự thể hiện vai trò quan trọng của mình trong giới chuyên môn
Trang 1In 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
Trang 3Conditional 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 aswhich 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-elsestatement is followed by a boolean expression The following code snippet shows the syntax of the if-else statement:
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
Trang 4Relational 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
Trang 5The 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
Trang 6The 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
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%"
Trang 7The 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:
System.out.println("Loan can be offered."); }
Trang 8In 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
preLoanRequest data member value to true
System.out.println("Loan can be offered."); }
else
{
Trang 9System.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:
Trang 10For 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:
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
Trang 11The 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)
Trang 12In 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:
Trang 13The 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
Trang 14scored 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:
Trang 15if((allpass != false) && (totalmarks > 175)) System.out.println("Scholarship granted");
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
Trang 16Using 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
Trang 177 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:
Student std1 = new Student();
System.out.println("Scholarship status of David:");
std1.printstatus();
}
}
Trang 18Task 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
Trang 19A 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)
Using Looping Statements
The for Loop
Trang 20The 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:
{
System.out.println("The value of i is:" + i); // The statement is executed till the condition is true }
}
}
Trang 21In 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) {
Trang 22The 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:
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
Trang 23System.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 num2variable 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 num2exceeds 100, the control comes out of the while loop
The following figure shows the output of the preceding code
Using the while Loop
Trang 24In 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:
System.out.println("Inside the do-while loop");
System.out.println("The value of variable num is:"
The do-while Loop
Trang 25The 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 ");
Trang 26num2 += num1;
num1 = num2 - num1;
continue; //statements after continue are skipped }
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
The following figure shows the output of the preceding code
The continue Statement
Trang 27Methods are used to access the variables that are defined in a class In addition to the simple methods discussed earlier, you can use methods that need some extra information for execution This information required to execute the method is passed to it by using arguments Arguments are also known as parameters of the methods
Consider an example of a library One of the methods of an object of the Librarian class
is issueBook() The librarian cannot issue a book until you specify the book you want Therefore, the issueBook() method of the Librarian class must take an argument that is the name of the book you want
A parameterized method is a method that uses parameters to process the data and generate
an output The output of a parameterized method is not static and depends on the value of the parameters passed Parameters in a parameterized method allow the method to be generalized The following code snippet shows the sum() method without parameters: void sum()
{
s = 10 + 20;
System.out.println("The sum is:" + s); }
In the preceding code snippet, the sum() method returns the sum of two numbers, 10 and
20 The sum() method always produces the same output as numbers 10 and 20 are fixed
in the method However, if you want the sum() method to be generalized, which means that it can produce the sum of any two numbers, you should use parameterized methods You can pass the value of two numbers as parameters to the sum() method, the sum of which is required You can use the following code snippet to define the sum() method that accepts two integers as parameters:
void sum(int num1, int num2)
Enhancing Methods of a Class
Defining Parameterized Methods