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

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

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

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

Objectives 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 Chapter Java Programming Constructs Using Conditional Statements 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 Using the if-else 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. NIIT Java Programming Constructs 4.3 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= op1>=op2 Returns true if the value of the op1 operand is greater than or equal to the value of the op2 operand. = 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. 4.10 Java Programming Constructs NIIT Passing Arguments at the Command Line Command-line arguments are used to provide information that a program needs at startup. The main() method in Java is the first method to be executed, therefore the command-line arguments are passed to the main() method. The main() method stores the command-line arguments in the String array object. In Java, the syntax for command-line argument is: public static void main(String args[]) { //statements } //End of main() method In the preceding syntax, each of the elements in the array named args[] is a reference to the command-line arguments each of which is a String object. You can use the following code to print the values passed as a command line argument to the main() method: class Display { public static void main(String args[]) { int i; if(args.length == 0) { System.out.println("Error: No arguments are passed."); System.exit(0); } for(i=0;ijava class file argument1 argument2 argument3… NIIT Java Programming Constructs 4.39 Consider the following example: c:\java>java Display Hello World The following figure shows the output of the preceding code. Using Command Line Arguments 4.40 Java Programming Constructs NIIT Creating Nested Classes Nested classes are the classes defined within classes. The scope of a nested class is limited to the class that encloses it. Nested Classes A nested class is a class defined as a member of another class. The scope of nested class is bounded by the scope of its enclosing class. If a class A is defined in class B, then class A is known only to class B and not known to any other class outside class B. The nested class has access to the members of its enclosing class including private members. However, the enclosing class does not have any access to the members of the nested class. Nested classes are of two types: „ Static: A nested class declared as static is called the static nested class. „ Inner: A non-static nested class is called the inner class. Static Nested Class A static nested class cannot access the members of its enclosing class directly because it is declared as static. Therefore, it has to access the members of its enclosing class through an object of the enclosing class. The following code snippet shows the declaration of a static nested class: class EnclosingClass{ { //statements static AstaticNestedClass { //statements } } Inner Class An inner class is a non-static nested class, whose instance exists inside the instance of its enclosing class. An inner class can directly access the variables and methods of its enclosing class. For example, consider a Company class, which contains the HR class within itself. NIIT Java Programming Constructs 4.41 The following figure shows a nested class. Nested Class You can use the following code to define the Company class and HRClass as the inner class that can access the data members of the Company class: class Company { int totalEmployee = 100; void innerTest() { HRClass HRC = new HRClass(); HRC.display(); } class HRClass // nested class { int HREmployee = 20; void display() { System.out.println("The Employee strength of Global System,Inc. is:" + totalEmployee); // displaying data member of the enclosing class System.out.println("The Employee strength of the HR Department of Global System,Inc. is:" + HREmployee); } } } class InnerClassDemo { public static void main(String args[]) { Company GSI = new Company(); GSI.innerTest(); } } 4.42 Java Programming Constructs NIIT The following figure shows the output of the preceding code. Using Inner Class NIIT Java Programming Constructs 4.43 Activity 2: Implementing Nested Classes Problem Statement The Fun Seasons Corp. departmental store is conducting interviews for the post of salesman. Various applicants are applying for the required post by filling an application form. The departmental store performs the selection process of the applicants and the selected applicants are chosen as candidates. John David, the programmer hired by the departmental store, is assigned the task of developing the Java application. He needs to create an application that accepts the applicant ID, in the "A#####" format, and educational status, such as Graduate and PostGraduate, as command-line arguments. Help John David write a code for the selection procedure. Solution To solve the problem, John David needs to use nested class. John David can create an Applicant class and a Candidate class as a nested class of the Applicant class. The Candidate class is the inner class and can access the members of the Applicant class. The Candidate class has the selection procedure of an applicant and displays the status of an applicant. The selection procedure is based on the age of the applicant. If the age of an applicant is below 25 years, the applicant is a candidate. 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, you need to perform the following tasks: 1. Code the application. 2. Compile and execute the application. Task 1: Coding the Application You need to write the following code in the notepad editor to create the Applicant class and the nested Candidate class and save it as ApplicantStatus.java file: class Applicant { String applicantID; 4.44 Java Programming Constructs NIIT String education; int age; Applicant(String id, String edu, int x) { applicantID = id; education = edu; age = x; } void printstatus() { Candidate cd = new Candidate(); cd.displaystatus(); } class Candidate { String candidateStatus = null; void setstatus() { if(age> v. Bitwise XOR f. ^ vi. Arithmetic Assignment g. += vii. Unary Increment 2. The if decision construct is used when there are multiple values for the same variable. (True/False). 3. Predict the output of the following code snippet: int n=5, d=4; int remainder = n % d; 3C.26 Java Fundamentals if (remainder != 0) System.out.println(n + " is not completely divisible by " + d); else System.out.println(n + " is completely divisible by " + d); a. b. 4. NIIT is not completely divisible by is completely divisible by Which of the following is a looping statement used in Java? a. if-else b. switch-case c. do-while d. continue Java Programming Constructs 4.51 Summary In this chapter, you learned that: „ Conditional statements are used to allow selective execution of statements. The conditional statements in Java are: z if-else z switch-case „ Looping statements are used when you want a section of a program to be repeated a certain number of times. Java offers the following looping statements: z for z while z do-while „ The for loop checks the validity of a condition first and then executes the body of the loop. „ The while loop checks for a condition before executing the body of the loop. „ In the do-while loop, first the body of the loop is executed and then the conditional expression is evaluated. „ The break and continue statements are used to control the program flow within a loop. „ The relational opearator is used to compare the values of two operands, such as >=, ==, !=, , and [...]... compile the Student class: javac Student .java 3 4 Press the Enter key 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 7 NIIT Close the Command Prompt window Close the notepad editor Java Programming Constructs 4.15... section of the Choose Project page Select the Java Application option in the Projects section of the Choose Project page Click the Next button The Name and Location page is displayed Type Scholarship in the Project Name text box 4.16 Java Programming Constructs NIIT 7 Type :\JavaProjects in the Project Location text box Note Ensure that the JavaProjects folder exists in the specified drive... the switch statement, are executed NIIT Java Programming Constructs 4.13 Activity 1: Implementing Constructs 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... System.out.println("Scholarship status of David:"); std1.printstatus(); } } NIIT Java Programming Constructs 4.17 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... Therefore, the Java complier decides the execution of the multiply() overloaded method by checking the type of arguments passed to it 4.32 Java Programming Constructs NIIT The following figure shows the output of the preceding code Overloading Methods Note The return type of a method is not a part of its signature Variable-Length Arguments In addition to the concepts of arrays and method overloading, Java provides... System.out.println("Number of arguments:" +a.length + "Contents."); NIIT Java Programming Constructs 4.33 for(int x:a) { System.out.print(x+" "); System.out.println(); } } public static void main(String args[]) { display(); display(10); display(10,20); } } The following figure shows the output of the preceding code Usage of Variable-Length Argument 4.34 Java Programming Constructs NIIT Passing Arguments to a Method... programming languages that do not support overloading, you give three different names for the methods that essentially do the same task However, Java supports method overloading and you can give the same name to different methods You can use the NIIT Java Programming Constructs 4.31 following declarations to overload the multiply() method with different types of parameters: public void multiply(int... 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() { 4.14 Java Programming Constructs NIIT if((allpass != false) && (totalmarks > 175)) System.out.println("Scholarship granted"); else System.out.println("Scholarship... control passes to the statement following the body of the loop NIIT Java Programming Constructs 4.19 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... made to the formal parameters affect the actual parameters In Java, both methods, call-by-value and call-by-reference are used depending upon what the type of data that is passed to the method You can also pass arguments to the main() method of the Java program at the command line during the run-time of a program Passing Arguments by Value In Java, when arguments of primitive data type, such as int and . 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. 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. 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

Ngày đăng: 20/09/2015, 08:34

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan