1. Trang chủ
  2. » Giáo Dục - Đào Tạo

Tutorials object oriented programming wi

45 41 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 45
Dung lượng 192 KB

Nội dung

Java Arithmetic Operators The Java programming language has includes five simple arithmetic operators like are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo) The following table summarizes the binary arithmetic operators in the Java programming language The relation operators in Java are: ==, !=, , = The meanings of these operators are: Use op1 + op2 op1 - op2 op1 * op2 op1 / op2 op1 % op2 Returns true if op1 added to op2 op2 subtracted from op1 op1 multiplied with op2 op1 divided by op2 Computes the remainder of dividing op1 by op2 The following java program, ArithmeticProg , defines two integers and two doubleprecision floating-point numbers and uses the five arithmetic operators to perform different arithmetic operations This program also uses + to concatenate strings The arithmetic operations are shown in boldface public class ArithmeticProg { public static void main(String[] args) { //a few numbers int i = 10; int j = 20; double x = 10.5; double y = 20.5; //adding numbers System.out.println("Adding"); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); //subtracting numbers System.out.println("Subtracting"); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); //multiplying numbers System.out.println("Multiplying"); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y)); //dividing numbers System.out.println("Dividing"); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); //computing the remainder resulting //from dividing numbers System.out.println("Modulus"); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); } } Java Assignment Operators It's very common to see statement like the following, where you're adding something to a variable Java Variables are assigned, or given, values using one of the assignment operators The variable are always on the left-hand side of the assignment operator and the value to be assigned is always on the right-hand side of the assignment operator The assignment operator is evaluated from right to left, so a = b = c = 0; would assign to c, then c to b then b to a i = i + 2; Here we say that we are assigning i's value to the new value which is i+2 A shortcut way to write assignments like this is to use the += operator It's one operator symbol so don't put blanks between the + and = i += 2; // Same as "i = i + 2" The shortcut assignment operator can be used for all Arithmetic Operators i.e You can use this style with all arithmetic operators (+, -, *, /, and even %) Here are some examples of assignments: //assign to //variable a int a = 1; //assign the result //of + to b int b = + 2; //assign the literal //"Hello" to str String str = new String("Hello"); //assign b to a, then assign a //to d; results in d, a, and b being equal int d = a = b; Java Increment and Decrement Operators There are Increment or decrement operators -> ++ and These two operators are unique in that they can be written both before the operand they are applied to, called prefix increment/decrement, or after, called postfix increment/decrement The meaning is different in each case Example x = 1; y = ++x; System.out.println(y); prints 2, but x = 1; y = x++; System.out.println(y); prints Source Code //Count to ten class UptoTen { public static void main (String args[]) { int i; for (i=1; i b) { max = a; } else { max = b; } Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?: Using the conditional operator you can rewrite the above example in a single line like this: max = (a > b) ? a : b; Java If-Else Statement The if-else class of statements should have the following form: if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition) { statements; } else if (condition) { statements; } else { statements; } All programming languages have some form of an if statement that allows you to test conditions All arrays have lengths and we can access that length by referencing the variable arrayname.length We test the length of the args array as follows: Source Code // This is the Hello program in Java class Hello { public static void main (String args[]) { /* Now let's say hello */ System.out.print("Hello "); if (args.length > 0) { System.out.println(args[0]); } } } Compile and run this program and toss different inputs at it You should note that there's no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all To invoke the class, you can create the new instance of the class: // To create a new instance class Simple sim = new Simple(); // To access the methods of the class sim.addNumbers(5,1,2) // To show the result of the addNumbers System.out.println("The result is " + Integer.toString(addNumbers(5,1,2))); The complete listing of class declaration: class simple { // Constructor simple(){ p = 1; q = 2; r = 3; } int p,q,r; public int addNumbers(int var1, int var2, int var3) { return var1 + var2 + var3; } public void displayMessage() { System.out.println("Display Message"); } } class example1{ public static void main(String args[]) { // To create a new instance class Simple sim = new Simple(); // To show the result of the addNumbers System.out.println("The result is " + Integer.toString(addNumbers(5,1,2))); // To display message sim.displayMessage(); } } Interfaces There is one thing in Java source code that is neither a class nor a member of a class That's an interface An interface defines methods that a class implements In other words it declares what certain classes However an interface itself does nothing All the action at least, happens inside classes A class may implement one or more interfaces This means that the class subscribes to the promises made by those interfaces Since an interface promises certain methods, a class implementing that interface will need to provide the methods specified by the interface The methods of an interface are abstract they have no bodies Generally, a class implementing an interface will not only match the method specifications of the interface, it will also provide bodies implementations for its methods For example, a ScoreCounter class might meet the contract specified by the Counting interface: interface Counting { abstract void increment(); abstract int getValue(); } So might a Stopwatch, although it might have a totally different internal representation Both would have increment() and getValue() methods, but the bodies of these methods might look quite different For example, a ScoreCounter for a basketball game might implement increment() so that it counts by points each time, while a Stopwatch might call its own increment() method even if no one else does A class that implements a particular interface must declare this explicitly: class ScoreCounter implements Counting { } If a class implements an interface, an instance of that class can also be treated as though its type were that interface For example, it can be labeled with a name whose declared type is that interface For example, an instance of class ScoreCounter can be labeled with a name of type Counting It will also answer true when asked whether it's an instanceof that interface type: if myScoreCounter is a ScoreCounter, then myScoreCounter instanceof Counting is true Similarly, you can pass or return a ScoreCounter whenever a Counting is required by a method signature The generality of interfaces and the inclusion of multiple implementations within a single (interface) type is an extremely powerful feature For example, you can use a name of type Counting to label either an instance of ScoreCOunter or an instance of Stopwatch (and use its increment() and getValue() methods) without even knowing which one you've got Catching Exceptions An exception is a point in the code where something out of the ordinary has happened and the regular flow of the program needs to be interrupted; an exception is not necessarily an error A method which has run into such a case will throw an exception using the throw(ExceptionClass) method When an exception is thrown it must be caught by a catch statement that should sit right after a try statement // This is the Hello program in Java class Hello { public static void main (String args[]) { /* Now let's say hello */ System.out.print("Hello "); System.out.println(args[0]); } } If you run the program without giving it any command line arguments, then the runtime system generates an exception something like, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Hello.main(C:\javahtml\Hello.java:7) Since we didn't give Hello any command line arguments there wasn't anything in args[0] Therefore Java kicked back this not too friendly error message about an "ArrayIndexOutOfBoundsException." we can fix this problem by testing the length of the array before we try to access its first element (using array.length) This works well in this simple case, but this is far from the only such potential problem What is an Exception ? Let us see what happens when an exception occurs and is not handled properly When you compile and run the following program public class Test{ public static void main(String str[]){ int y = 0; int x = 1; // a division by occurs here int z = x/y; System.out.println("after didvision"); } } The execution of the Test stops and this is caused by the division by zero at - x/y - an exception has been thrown but has not been handled properly How to handle an Exception ? To handle an Exception, enclose the code that is likely to throw an exception in a try block and follow it immediately by a catch clause as follows public class Test{ public static void main(String str[]){ int y = 0; int x = 1; // try block to "SEE" if an exception occurs try{ int z = x/y; System.out.println("after didvision"); // catch clause below handles the // ArithmeticException generated by // the division by zero } catch (ArithmeticException ae) {System.out.println(" attempt to divide by 0");} System.out.println(" after catch "); } } The output of the above program is as follows attempt to divide by after catch the statement - System.out.println("after didvision") - is NOT executed, once an exception is thrown, the program control moves out of the try block into the catch block The goal of exception handling is to be able to define the regular flow of the program in part of the code without worrying about all the special cases Then, in a separate block of code, you cover the exceptional cases This produces more legible code since you don't need to interrupt the flow of the algorithm to check and respond to every possible strange condition The runtime environment is responsible for moving from the regular program flow to the exception handlers when an exceptional condition arises In practice what you is write blocks of code that may generate exceptions inside trycatch blocks You try the statements that generate the exceptions Within your try block you are free to act as if nothing has or can go wrong Then, within one or more catch blocks, you write the program logic that deals with all the special cases To start a section of code which might fail or not follow through you start a try clause: try { // Section of code which might fail } The try statement is needed in case of an exception If the read fails in some way it will throw an exception of type java.io.IOException That exception must be caught in this method, or the method can declare that it will continue throwing that message Exception handling is a very powerful tool, you can use it to catch and throw exceptions and thus group all your error handling code very well and make it much more readable in larger more complex applications After the try section there must exist one or more catch statements to catch some or all of the exceptions that can happen within the try block Exceptions that are not caught will be passed up to the next level, such as the function that called the one which threw the exception, and so on try { // Section of code which might fail } catch (Exception1ThatCanHappen E) { // things to if this exception was thrown } catch (Exception2ThatCanHappen E) { // things to if this exception was thrown } Here's an example of exception handling in Java using the Hello World program above: Source Code // This is the Hello program in Java class ExceptionalHello { public static void main (String args[]) { } /* Now let's say hello */ try { System.out.println("Hello " + args[0]); } catch (Exception e) { System.out.println("Hello whoever you are"); } } You may or may not print an error message If you write an exception handler and you don't expect it to be called, then by all means put a System.out.println("Error: " + e); This has the folowing advantages over handling your errors internally:     You can react to an error in custom defined way A read error does not mean that the program should crash You can write code with no worry about failure which will be handled by the users of your class You can group your error handling code much better You can make your application more transactional focused with nested try catch blocks: A simple Java code which demonstrates the exception handling in Java Refer to the java API document to see all exception types that can be handled in Java Source Code public class excep2 { public static void main(String args[]) { int i =0 ; //Declare an array of strings String Box [] = {"Book", "Pen", "Pencil"}; while(i

Ngày đăng: 08/05/2019, 19:53

w