1 / 47

Lec . 01: Java fundamentals

Lec . 01: Java fundamentals. Sample Programs. Your first Java console application. Your first Java console application ( 控制台應用程 式 ). class Example { public static void main(String args []) { System.out.println ("Java drives the Web."); } }. Your first Java console application. /*

mulan
Télécharger la présentation

Lec . 01: Java fundamentals

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lec. 01: Java fundamentals Java Programming Sample Programs

  2. Your first Java console application Java Programming

  3. Your first Java console application(控制台應用程式) • class Example { • public static void main(String args[]) { • System.out.println("Java drives the Web."); • } • } Java Programming

  4. Your first Java console application • /* • This is a simple Java program. • Call this file Example.java. • */ • class Example { • // A Java console-mode application • // begins with a call to main(). • public static void main(String args[]) { • System.out.println("Java drives the Web."); • } // end of main method • } // end of Example class Java Programming

  5. Creating Java source program • A Java source program can be created by using any text editor, Value Added Text Editor or IDE package. • DO NOT use word processor such as Microsoft Word. • A source program is a compilation unit which may contain one or more classes, interfaces and/or enum definitions. • Conventionally, each source program contains exact one class, interface or enum definition. • The extension file name of the source program file must be java. • Conventionally, use the name of the class, interface or enum definition as the file name. Java Programming

  6. Compiling Java program • To compile the Example.java, execute the compiler, javac, specifying the name of the source file on the command line as follows: javac Example.java • The javaccreates a file called Example.class that contains the bytecode version of the program. • The extension file name of the bytecode file generated by javac must be class. • If there are more than one class in a source file, javac generates a bytecode file for each class. • The bytecode file name is the same as the class name of the corresponding class. Java Programming

  7. Executing Java program • The java command starts a Java console application by starting a Java runtime environment, loading a specified class, and calling that class's main method , as follows java Exeample • The bytecode file which can be executed by java must be associated with a class containing the method named main. Java Programming

  8. Line 1 to 4 of the sample program • The line 1 to 4 of the sample program are inline comments(行內註解 區塊註解)used to describe or explain the operation of the program to anyone who is reading its source code. • The contents of a comment are ignored by the compiler. • The comments, starting with /* and ending with */, are called multiline comments. • Any content enclosed by /* and */ are treated as comments. Java Programming

  9. Line 5 of the sample program • Line 5 is the heading of a class including the keywordclass and the class name. • A keyword is an identifier with a given meaning in Java language. • A class is Java’s basic unit of encapsulation. • A class definition begins with the opening curly brace ({) and ends with the closing curly brace (}). • The elements between the two braces are members, attributes and behaviors, of the class. Java Programming

  10. Line 6 & 7 of the sample program • Line 6 and 7 are two single-line comments (單行註解)starting with double slashes (//) and ending at the end of the line. • A single-line comment can place anywhere within a source program. Java Programming

  11. Line 8 of the sample program • Line 8 is the method heading of the method named main. • A method heading consists of • Access control: public • Type of method: static • Data type of the returned value: void • Signature of the method • Method name: main • Parameter list: String args[], which is enclosed by a pair of parentheses • The definition, i.e. the instruction set and local variables, of a method is enclosed by a pair of curly braces. Java Programming

  12. More in line 8… • The keyword public is a access modifier(修飾字) determining how other codes can access the members of the class. • When a member of a class is preceded by public, then that member can be accessed by codes inside or outside the class in which it is declared. • The opposite of public is private, which prevents a member from being used by codes defined outside of its class. • The keyword static allows mainmethodto be called before an object of the class has been created. • The keyword void specifies that main method does not return a value after it completes the execution. Java Programming

  13. More in line 8… • Any information that you need to pass to a method is received by variables, called parameters(參數), specified within the pair of parentheses that follow the name of the method. • If no parameters are required for a given method, you still need to include the empty parentheses. • “String args[ ] “ declares a parameter named args which is an array of String objects. • Arrays are collections of similar objects. • String is a class defined in Java class library (JCL) representing a sequence of characters. • Using J2SE API to browse java.lang.String class Java Programming

  14. Line 9 of the sample program • Line 9 sends the message println to an object out, which is defined in java.lang.System class, representing the output stream that is connected to the console. • In Java, a stream means a channel through which data can be transmitted between a program and data source/destination. • In Java, each stream is an object consisting of all the necessary methods to handle data transmission. • The “Java drives the Web” is the argument for message println. • When System.out receives the message, it activates the associated method to print the argument on the console followed by a new line. Java Programming

  15. Line 9 of the sample program • System is a predefined class in J2SE that provides access to the platform on which the JRE is installed. • Using J2SE API to browse java.lang.System class • out is a field defined in System. • out is an object of the java.io.PrintStream class. • Browsing the functions supported by the java.io.PrintStream class • The System.out.println( ) statement ends with a semicolon. • All statements in Java end with a semicolon. Java Programming

  16. Handling syntax errors (處理語法錯誤) • If you enter something incorrectly into your program, the compiler(編譯器)will report a syntax error message when it tries to compile it. • The Java compiler attempts to make sense out of your source code no matter what you have written. • For this reason, the error that is reported may not always reflect the actual cause of the problem. • Example • Missing the open curly brace after main() will cause the following error message. Java Programming Example.java:8: ';' expected public static void main(String args[]) ^ Example.java:11: class, interface, or enum expected } ^

  17. Second sample program Java Programming

  18. Second sample program • class Example2 { • public static void main(String args[]) { • int var1; • int var2; • var1 = 1024; • System.out.println("var1 contains " + var1); • var2 = var1/2; • System.out.print("var2 contains var1/2: "); • System.out.println(var2); • } • } Java Programming

  19. Second sample program /* This demonstrates a variable. A variable is a named memory location that can be assigned a value. The value of a variable can be changed during the execution of a program . */ • class Example2 { • public static void main(String args[]) { • int var1; // this declares a variable • int var2; // this declares another variable • var1 = 1024; // this assigns 1024 to var1 • System.out.println("var1 contains " + var1); • var2 = var1 / 2; • System.out.print("var2 contains var1 / 2: "); • System.out.println(var2); • } • } Java Programming

  20. Line 3 and 4 of the sample program • Line 3 and 4 declare two variables named var1 and var2. • Java is a strong type language(強類型語言) • This property makes Java robust. • Each variable must be declared with the type of value that the variable can store. • All operations are type-checked by the compiler or JVM for type compatibility. • The int is a primitive type(原始資料型態)provided by Java representing integers. • Java provides 8 different primitive data types. Java Programming

  21. Line 3 and 4 of the sample program • The syntax for declaring a variable(變數). <data-type> <variable-name>; • More than one variable with the same data type can be declared in a single statement by using commas to separate variable names. • Line 3 and 4 can be merged as follows. int var1, var2; Java Programming

  22. Line 5 of the sample program • In line 5, the content of variable var1 is changed by using the assignment operator(設定運算子). • Java provides 44 different operators to manipulate data such as addition, multiplication, shift and Boolean-AND. • In Java, the assignment operator is the single equal sign which copies the value on its right side into the variable on its left. • The left-side operand of an assignment operator must be a variable. Java Programming

  23. Line 6 of the sample program • In line 6 outputs the value of var1, which is 1024, preceded by the string "var1 contains ". • In this statement, the plus sign (+) causes the value of var1to be displayed after the string that precedes it. • Using the + operator, you can chain together as many items as you want within a single println statement. Java Programming

  24. Line 7 of the sample program • In line 7, the content of variable var2 is changed by using the assignment operator. • This line divides the value in var1by 2 and then stores that result in var2. • After the line executes, var2 will contain the value 512 and the value of var1 will be unchanged. Java Programming

  25. Line 8 of the sample program • In line 8, print is another message which can be sent to System.out object. • The difference between print and println is the former will not generate a new line. Java Programming

  26. Third sample program Java Programming

  27. Third sample program • class Example3 { • public static void main(String args[]) { • intvar; • double x; • var = 10; • x = 10.0; • System.out.println("Original value of var: " + var); • System.out.println("Original value of x: " + x); • System.out.println(); • var = var / 4; • x = x / 4; • System.out.println("var after division: " + var); • System.out.println("x after division: " + x); • } • } Java Programming

  28. Third sample program • /* This program illustrates the differences • between int and double. */ • class Example3 { • public static void main(String args[]) { • intvar; // this declares an int variable • double x; // this declares a floating-point variable • var = 10; // assign var the value 10 • x = 10.0; // assign x the value 10.0 • System.out.println("Original value of var: " + var); • System.out.println("Original value of x: " + x); • System.out.println(); // print a blank line • // now, divide both by 4 • var = var / 4; • x = x / 4; • System.out.println("var after division: " + var); • System.out.println("x after division: " + x); • } • } Java Programming

  29. Output of the sample program Original value of var: 10 Original value of x: 10.0 var after division: 2 x after division: 2.5 Fraction lost Fraction preserved Java Programming

  30. Practical problem: converting gallon to liter • Design a Java program which prints a table of conversions, beginning with 1 gallon and ending at 100 gallons, and after every 10 gallons, a blank line will be output. Java Programming

  31. Program for generating conversion table Java Programming

  32. Program for generating conversion table • class GalToLitTable { • public static void main(String args[]) { • double gallons, liters; • int counter; • counter = 0; • for(gallons = 1; gallons <= 100; gallons++) { • liters = gallons * 3.7854; • System.out.println(gallons + " gallons is " + liters + " liters."); • counter++; • if(counter == 10) { • System.out.println(); • counter = 0; • } • } • } • } Java Programming

  33. Program for generating conversion table • /* This program displays a conversion table of gallons to liters.*/ • class GalToLitTable { • public static void main(String args[]) { • double gallons, liters; • int counter; • counter = 0; // initializing the counter • for(gallons = 1; gallons <= 100; gallons++) { • liters = gallons * 3.7854; // convert to liters • System.out.println(gallons + " gallons is " + liters + " liters."); • counter++; // increase the counter by one • if(counter == 10) { // if 10 lines have been printed, print a blank line • System.out.println(); // output a blank line • counter = 0; // reset the line counter • } // end of a code block following if-construct • } // end of a code block following for-construct • } // end of main method • } //end of class Java Programming

  34. ++ operator • ++ operator is used to increase the content of its operand by 1. Java Programming

  35. Control statements used in the sample program • Inside a method, execution proceeds from one statement to the next, from top to bottom. • However, it is possible to alter execution flow via the use of the various program control statements supported by Java. • Two control statements used in the sample. • for-statement (line 6) • Repetitively executing a single statement if a given condition is satisfied • if-statement (line 10) • Executing a single statement if a given condition is satisfied Java Programming

  36. Code blocks • A code block, also called compound statement, is a grouping of two or more statements which are enclosed by a pair of curly braces. • A code block is a logical unit that can be used as a single statement can. Java Programming

  37. for-statement • for-statement is a Java construct used to create a loop. • A loop means a repetition. • Syntax form for(<init-exp>; <test-exp>; <post-exp>) statement; • The <init-exp> portion of the construct sets a loop control variable to an initial value. • The <test-exp> is a boolean expression that tests the loop control variable. • If the outcome of that test is true, the for loop continues to iterate; otherwise, the loop terminates. • An expression is a boolean expression if the result of evaluating the expression is either true or false. • The <post-exp> expression determines how the loop control variable is changed each time the loop iterates. Java Programming

  38. Flowchart for for-statement <init-exp> <test-exp> Java Programming true false statement <post-exp> Next statement

  39. Example of using for-statement • What is the content of the variable sum after executing the following for-statement? int sum, var; sum = 0; for(var = 1; var <= 10; var++) { sum = sum + var; } Java Programming

  40. Line 6 to 14 in the sample program • Line 6 uses a for-statement to print the conversion table for 1 gallon to 100 gallons. • The way of converting gallon to liter is the same for any number of gallons, so the conversion for printing the table can be done repetitively by simply changing the content of variable gallons. • The gallons is the loop control variable. • Since more than one statement need to be done for each loop, these statements are enclosed by a pair of curly braces to form a code block. • The for-statement only control a single statement. Java Programming

  41. if-statement • Syntax form of if-statement if(<condition>) statement; • If condition is true, then the statement is executed; otherwise, the statement is bypassed. • <condition> must be a boolean expression. • Java provides 6 relational operators and 4 local operators to form boolean expressions. • Relational operators: >, >=, <, <=, == and != • Logical operators: && (&) for AND, || (|) for OR, ^ for exclusive-OR and ! for NOT Java Programming

  42. Line 10 to 13 in the sample program • Line 10 is a if-statement with the condition “counter == 10”. • Since we need to perform 2 statements, line 11 and 12, when the content of counter is 10, we enclose these 2 statements by using a pair of curly braces to form a code block. • Only a single statement is controlled by a if-statement. • What will happen if you remove the open curly brace at line 10 and close curly brace at line 13? Java Programming

  43. Identifiers • A Java program is composed of many components including classes, methods, variables and statements. • To access components of a program, each component needs an identifier, i.e. name. • A legal identifier … • One or more characters consisting of only 26 letters (including both upper and lower cases), 10 digits, underscore( _ ) and dollar-sign ( $ ) • First character not a digit • Not a keyword • Keyword list referring Table 1-1 of the textbook • Case sensitive • Unique within a given context Java Programming

  44. Examples • Legal • MyClass, toDo, PI, pi, interestRate, MAX_SIZE, noGrade12, _test, $NewTWDollar, Main, Package • Illegal • 12x: starting with digit • main: a keyword • my-name: using the dash character Java Programming

  45. Naming conventions • Package names • Using only lower-case alphabets • To avoid duplications, all the packages developed by a vendor should under the root path which is resembled the reverse of the vendor’s domain name. • com.foo.util where foo.com is the domain of a vendor • Class names • Using descriptive noun or noun phrase • Capitalizing the first alphabet of each word • Example: JOptionPane, Calendar, ArrayList, Students, SchoolBus • Method names • Using descriptive verbs or verb clauses • Using lowercase alphabets for the first word • Capitalizing the first alphabet of each remaining word • Example: getName, setAddress, calculateSalary Java Programming

  46. Naming conventions • Variable names • Using descriptive word(s) • Using lowercase alphabets for the first word • Capitalizing the first alphabet of each remaining word • Example: commissionRate, homeAddress • Constant names • Using descriptive nouns or noun phrases • Capitalizing all the alphabets • Using underscore to separate internal words • Example: PI, MAX_RATE Java Programming

  47. You should … • Run all the sample programs given in the lecture. • Browse the J2SE APIs, especially for java.lang.System, java.lang.Integer, java.lang.Double and java.lang.String. Java Programming

More Related