wwwp.nus.sg/~cs1010/ UNIT 20 C to Java

49 Slides577.41 KB

http://www.comp.nus.edu.sg/ cs1010/ UNIT 20 C to Java

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 2 Unit 20: C to Java Objectives: Learning about the structure of a Java program Using selection and repetition statements in Java Using classes such as Scanner, Math, String, DecimalFormat Learning how to use an array in Java With the above, able to convert some C programs written in CS1010 module to Java Reference: CS1020 website http://www.comp.nus.edu.sg/ cs1020

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 3 Unit 20: C to Java (1/2) 1. Introduction 2. Hello World! 3. Java Constructs 3.1 Program Structure 3.2 Temperature Conversion 3.3 Importing Packages 3.4 Input: Using Scanner Class 3.5 Output: Using System.out Class (with DecimalFormat class) 3.6 Using Math Class 3.7 User-defined Constants 3.8 Java Naming Convention 3.9 Writing Java Methods

NUS CS1010 (AY2014/5 Semester 1) Unit 20: C to Java (2/2) 3. Java Constructs (continued ) 3.10 Boolean Data Type 3.11 Selection Statements 3.12 Repetition Statements 3.13 Arrays 4. API 5. Conclusion Unit20 - 4

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 5 1. Introduction (1/3) Java is the programming language used in CS1020. As an Object-Oriented Programming (OOP) language, Java supports OOP concepts such as encapsulation, inheritance and polymorphism. It also has exceptions handling (error handling) for better program robustness. In this unit, we will NOT discuss such OOP features. We will focus on non-OOP features in Java and compare the syntax of Java with that of C. However, even if we limit ourselves to non-OOP features here, certain OOP keywords such as ‘public’ and ‘static’ still creep up in our example Java programs. They require understanding of OOP concepts, which will be explained in CS1020. Here, we use them as a necessity.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 6 1. Introduction (2/3) When? C Created in 1972 Java Created in 1995 Who? Dennis Ritchie James Gosling Where? Bell Laboratories Sun Microsystems (now merged with Oracle)

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 7 1. Introduction (3/3) Type C Java Imperative Imperative and objectoriented Compilation gcc helloworld.c a.out (executable code) javac HelloWorld.java HelloWorld.class (bytecode) Execution java HelloWorld a.out Portibility of No, need to recompile for compiled each architecture. code Yes, bytecode is “Write-Once, Run-Anywhere”.

NUS CS1010 (AY2014/5 Semester 1) 2. Hello World! (1/2) #include #include stdio.h stdio.h hello world.c int int main(void) main(void) {{ printf("Hello printf("Hello World!\n"); World!\n"); return return 0; 0; }} import import java.lang.*; java.lang.*; Unit20 - 8 C programs: extension .c Java programs: extension .java C: Include header file stdio.h to use printf(). Java: Import java.lang.* package to use System.out.print()/println(). C: Must have main() function. Java: Must have main() method. HelloWorld.java public public class class HelloWorld HelloWorld {{ } public public static static void void main(String[] main(String[] args) args) {{ System.out.println("Hello System.out.println("Hello World!"); World!"); }}

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 9 2. Hello World! (2/2) C happytan happytan gcc gcc hello world.c hello world.c happytan happytan a.out a.out Hello Hello World! World! Compiler produces a.out gcc hello world.c Java Executable code happytan happytan javac javac HelloWorld.java HelloWorld.java happytan happytan java java HelloWorld HelloWorld Hello Hello World! World! Compiler javac HelloWorld.java produces Bytecode HelloWorld.class

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 10 3. Java Every Java program is a class. In OOP, a class is a template for creating objects (Analogy in C: structure definition in C is a template for creating structure variables) Such a class defines its object attributes and methods. We call it a service class. It does not contain a main() method. (We will learn how to write service classes in CS1020.) (Note: What we call functions in C, we call them methods in Java.) However, in this unit we are not writing service classes. We are writing classes that do not contain definition of any object attributes and methods. Instead, our classes are application (or client) classes that use other service classes. Such a class must contain the main() method.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 11 3.1 Java: Program Structure For the moment just stick to the following program structure: import import java.lang.*; java.lang.*; public public class class ClassName ClassName {{ }} public public static static void void main(String[] main(String[] args) args) {{ // // Body Body of of main() main() method method }} java.lang is a package that contains the definition of methods such as System.out.print() and System.out.println(). As java.lang is a default package, importing it is optional. The filename must be the same as the class name. Hence, the above program must be named ClassName.java (Assuming the file contains one class, and the class is public.)

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 12 3.2 Java: Temperature Conversion temperature convert.c #include #include stdio.h stdio.h int int main(void) main(void) {{ float float fah, fah, cel; cel; // // degrees degrees Fahrenheit Fahrenheit and and Celsius Celsius printf("Enter printf("Enter temperature temperature in in Fahrenheit: Fahrenheit: "); "); scanf("%f", scanf("%f", &fah); &fah); cel cel (fah (fah -- 32) 32) ** 5/9; 5/9; printf("Temperature printf("Temperature in in Celsius Celsius %f\n", %f\n", cel); cel); }} Enter .: 123.5 . Celsius 50.833332 return return 0; 0; import import java.util.*; java.util.*; TemperatureConvert.java public public class class TemperatureConvert TemperatureConvert {{ public public static static void void main(String[] main(String[] args) args) {{ Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); float float fah, fah, cel; cel; // // degrees degrees Fahrenheit Fahrenheit and and Celsius Celsius System.out.print("Enter System.out.print("Enter temperature temperature in in Fahrenheit: Fahrenheit: "); "); fah fah sc.nextFloat(); sc.nextFloat(); }} }} cel cel (fah (fah -- 32) 32) ** 5/9; 5/9; System.out.println("Temperature System.out.println("Temperature in in Celsius Celsius "" cel); cel);

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 13 3.3 Importing Packages Java comes with many built-in service classes with their methods, available for programmers to use. To use the methods from a service class, you need to import the respective package that contains that class. Examples: To use System.out class import java.lang.*; (default) To use Scanner class import java.util.*; ‘*’ is wildcard character, indicating all classes in that package; you may specifically import just that particular class of the package import java.util.Scanner; import import java.util.*; java.util.*; // // or or import import java.util.Scanner; java.util.Scanner; public public class class TemperatureConvert TemperatureConvert {{ public public static static void void main(String[] main(String[] args) args) {{ Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); . .

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 14 3.4 Input: Using Scanner Class (1/2) Scanner class (belongs to package java.util) provides methods to read inputs For interactive input, first, create a Scanner object to read data from System.in (keyboard) Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); Then, use the appropriate Scanner methods to read the input data. Some examples: nextInt(): To return integer read nextFloat(): To return float value read nextDouble(): To return double value read next(): To return a string (delimited by whitespace) read nextLine(): To return a string (delimited by newline) read

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 15 3.4 Input: Using Scanner Class (2/2) int, double are primitive data types (just like in C) String is a class in Java, in java.lang package. InputExamples.java Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); int int aa sc.nextInt(); sc.nextInt(); double double bb sc.nextDouble(); sc.nextDouble(); String String str1 str1 sc.next(); sc.next(); String String str2 str2 sc.nextLine(); sc.nextLine(); User’s inputs: 123 4.56 This is a test. Values read: a 123 b 4.56 str1 "This" str2 " is a test."

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 16 3.5 Output: Using System.out Class (1/4) System.out class (belongs to package java.lang) provides methods to print outputs 3 methods: System.out.print() System.out.println() System.out.printf() System.out.printf() is a relatively new method aiming to emulate the printf() function in C.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 17 3.5 Output: Using System.out Class (2/4) int int aa 123, 123, bb 456; 456; double double xx 78.9; 78.9; String String str str "Hello "Hello world!"; world!"; System.out.print("a System.out.print("a "" System.out.println("; System.out.println("; bb System.out.print("x System.out.print("x "" System.out.println("str System.out.println("str System.out.printf("a System.out.printf("a System.out.printf("x System.out.printf("x System.out.printf("str System.out.printf("str Output: Note the difference in the display of x’s value. a x a x a); a); "" xx "" OutputExamples1.java b); b); "" and and "); "); str); str); %d; %d; bb %d\n", %d\n", a, a, b); b); %f %f and and ", ", x); x); %s\n", %s\n", str); str); 123; b 456 78.9 and str Hello world! 123; b 456 78.900000 and str Hello world!

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 18 3.5 Output: Using System.out Class (3/4) What if you want to print a real number with a specific number of decimal places? Example: 2.37609 to display as 2.38? One way: using System.out.printf() double double yy 2.37609; 2.37609; System.out.printf("y System.out.printf("y %.2f\n", %.2f\n", y); y); How about System.out.print() or System.out.println()? Use the DecimalFormat class (in java.text package)

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 19 3.5 Output: Using System.out with DecimalFormat (4/4) DecimalFormat DecimalFormat DecimalFormat DecimalFormat DecimalFormat DecimalFormat DecimalFormat DecimalFormat DecimalFormat DecimalFormat df1 df1 df2 df2 df3 df3 df4 df4 df5 df5 new new new new new new new new new new OutputExamples2.java DecimalFormat("000.00"); DecimalFormat("000.00"); DecimalFormat("###.##"); DecimalFormat("###.##"); Many other DecimalFormat("0.0%"); DecimalFormat("0.0%"); format patterns DecimalFormat("0,000"); DecimalFormat("0,000"); available. DecimalFormat("#,###"); DecimalFormat("#,###"); double double yy 2.37609, 2.37609, zz 36.9; 36.9; int int aa 1234567, 1234567, bb 89; 89; System.out.println("y System.out.println("y System.out.println("y System.out.println("y System.out.println("y System.out.println("y System.out.println("a System.out.println("a System.out.println("a System.out.println("a Output: y y y a a "" "" "" "" "" df1.format(y) df1.format(y) df2.format(y) df2.format(y) df3.format(y) df3.format(y) df4.format(a) df4.format(a) df5.format(a) df5.format(a) "; "; "; "; "; "; "; "; "; "; zz zz zz bb bb 002.38; z 036.90 2.38; z 36.9 237.6%; z 3690.0% 1,234,567; b 0,089 1,234,567; b 89 "" "" "" "" "" df1.format(z)); df1.format(z)); df2.format(z)); df2.format(z)); df3.format(z)); df3.format(z)); df4.format(b)); df4.format(b)); df5.format(b)); df5.format(b));

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 20 3.6 Using Math Class (1/3) You have written C programs that use math functions in math.h Java provides the service class Math (in java.lang package) The Math class provides many math methods, and also some constants such as PI. Unlike in C where you need to compile a program that uses Math functions with the –lm option, no special option is required when you compile a Java program that uses Math methods.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 21 3.6 Using Math Class (2/3) #include #include stdio.h stdio.h #include #include math.h math.h #define #define PI PI 3.14159 3.14159 area of circle.c int int main(void) main(void) {{ double double radius, radius, area; area; printf("Enter printf("Enter radius: radius: "); "); scanf("%lf", scanf("%lf", &radius); &radius); area area PI PI ** pow(radius, pow(radius, 2); 2); printf("Area printf("Area %.3f\n", %.3f\n", area); area); }} return return 0; 0; Enter radius: 20.5 Area 1320.253

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 22 3.6 Using Math Class (3/3) import import import import java.util.*; java.util.*; java.text.*; java.text.*; public public class class AreaOfCircle AreaOfCircle {{ AreaOfCircle.java Enter radius: 20.5 Area 1320.254 public public static static void void main(String[] main(String[] args) args) {{ DecimalFormat DecimalFormat df df new new DecimalFormat("#.###"); DecimalFormat("#.###"); Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); double double radius, radius, area; area; System.out.print("Enter System.out.print("Enter radius: radius: "); "); radius radius sc.nextDouble(); sc.nextDouble(); area area Math.PI Math.PI ** Math.pow(radius, Math.pow(radius, 2); 2); }} }} System.out.println("Area System.out.println("Area "" df.format(area)); df.format(area)); Constant PI defined in Math class. Method pow() in Math class. Area is slightly different from that in area of circle.c due to different values of PI.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 23 3.7 User-defined Constants (1/3) #include #include stdio.h stdio.h #define #define SGD TO MYR SGD TO MYR 2.5569 2.5569 currency.c int int main(void) main(void) {{ double double sing dollar, sing dollar, ringgit; ringgit; printf("Enter printf("Enter currency: currency: S "); S "); scanf("%lf", scanf("%lf", &sing dollar); &sing dollar); ringgit ringgit SGD TO MYR SGD TO MYR ** sing dollar; sing dollar; printf("That's printf("That's %.2f %.2f ringgit.\n", ringgit.\n", ringgit); ringgit); }} return return 0; 0;

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 24 3.7 User-defined Constants (2/3) import import import import java.util.*; java.util.*; java.text.*; java.text.*; Currency.java public public class class Currency Currency {{ private private static static final final double double SGD TO MYR SGD TO MYR 2.5569; 2.5569; public public static static void void main(String[] main(String[] args) args) {{ DecimalFormat DecimalFormat df df new new DecimalFormat("0.00"); DecimalFormat("0.00"); Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); double double singDollar, singDollar, ringgit; ringgit; System.out.print("Enter System.out.print("Enter currency: currency: S "); S "); singDollar singDollar sc.nextDouble(); sc.nextDouble(); }} }} ringgit ringgit SGD TO MYR SGD TO MYR ** singDollar; singDollar; System.out.println("That's System.out.println("That's "" df.format(ringgit) df.format(ringgit) "" ringgit."); ringgit.");

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 25 3.7 User-defined Constants (3/3) private private static static final final double double SGD TO MYR SGD TO MYR 2.5569; 2.5569; The keyword final indicates that the value assigned is final, that is, it cannot be altered. The keyword private indicates that constant SGD TO MYR can only be used in this program. If you want to allow SGD TO MYR to be used by other programs, declare it as public instead. (Just like the PI constant in the Math class which is a public constant) Other programs can then use this constant by referring to it as Currency.SGD TO MYR, just like Math.PI The keyword static is not within the scope of this unit.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 26 3.8 Java Naming Convention (1/2) Java has a rather comprehensive naming convention on naming of classes, objects, methods, constants, etc. CS1020 “Online” web page, “Java Style Guides” for some links: http://www.comp.nus.edu.sg/ cs1020/2 resources/online.html Some definitions: upper camel case, lower camel case Upper camel case: First letter of each word is capitalised, the rest are in lower case Examples: ThisIsAnExample, AreaOfCircle, TemperatureConvert Lower camel case: Same as upper camel case, except that the first letter of the first word is in lower case Examples: thisIsAnExample, singDollar, maxValue

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 27 3.8 Java Naming Convention (2/2) Names of classes should be in upper camel case Examples: AreaOfCircle, TemperatureConvert, Currency Names of variables, methods, parameters and objects should be in lower camel case: Examples: singDollar, studentName, printArray() , bankAcct Names of constants should be in all upper case, with underscore ( ) separating words: Examples: PI, SGD TO MYR

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 28 3.9 Writing Java Methods (1/6) What we call functions in C are called methods in Java. There are two kinds of methods in Java: instance methods and class methods. Instance methods: An instance method requires an object to apply (pass message) to. Class methods: A class method does not require an object to apply (pass message) to. As we are not doing OOP here, we will write only class methods here. Class methods are distinguished from instance methods by the presence of the keyword static.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 29 3.9 Writing Java Methods (2/6) If a is the length of the square, what is the area of the circle? Let radius of circle be r Pythagoras’ theorem r2 (a/2)2 (a/2)2 a a2/2 Hence, area of circle, C, is a/2 r a/2 C p a2/2

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 30 3.9 Writing Java Methods (3/6) #include #include stdio.h stdio.h #define #define PI PI 3.14159 3.14159 square and circle.c double double compute area(double); compute area(double); int int main(void) main(void) {{ double double length; length; // // length length of of the the square square double // double area; area; // area area of of the the circle circle printf("Enter printf("Enter length length of of square: square: "); "); scanf("%lf", scanf("%lf", &length); &length); area area compute area(length); compute area(length); printf("Area printf("Area of of circle circle %.3f\n", %.3f\n", area); area); }} return return 0; 0; double double compute area(double compute area(double length) length) {{ return return PI PI ** (length (length ** length)/2; length)/2; }}

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 31 3.9 Writing Java Methods (4/6) import import import import java.util.*; java.util.*; java.text.*; java.text.*; SquareAndCircle.java public public class class SquareAndCircle SquareAndCircle {{ public public static static void void main(String[] main(String[] args) args) {{ DecimalFormat DecimalFormat df df new new DecimalFormat("#.###"); DecimalFormat("#.###"); Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); double double length; length; // // length length of of the the square square double // double area; area; // area area of of the the circle circle System.out.print("Enter System.out.print("Enter length length of of square"); square"); length length sc.nextDouble(); sc.nextDouble(); area area computeArea(length); computeArea(length); System.out.println("Area System.out.println("Area of of circle circle "" df.format(area)); df.format(area)); }} // // continue continue on on next next page page

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 32 3.9 Writing Java Methods (5/6) public public class class SquareAndCircle SquareAndCircle {{ SquareAndCircle.java public public static static void void main(String[] main(String[] args) args) {{ . . . area area computeArea(length); computeArea(length); . . . }} }} public public static static double double computeArea(double computeArea(double length) length) {{ return return Math.PI Math.PI ** (length (length ** length)/2; length)/2; }} Almost like function in C; function prototype not needed Add keywords public (change to private if you don’t want to share this method) and static (not in scope here)

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 33 3.9 Writing Java Methods (6/6) In C, for a function to pass back more than one value to the caller, we use pointer parameters. There are no pointers in Java. In Java, we create an object to hold the values, and pass the reference of the object to the method. This is outside the scope of this unit.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 34 3.10 Boolean Data Type (1/2) Java provides the boolean data type, which is absent in ANSI C BooleanType.java public public class class BooleanType BooleanType {{ }} public public static static void void main(String[] main(String[] args) args) {{ Scanner Scanner sc sc new new Scanner(System.in); Scanner(System.in); System.out.print("Enter System.out.print("Enter a: a: "); "); int int aa sc.nextInt(); sc.nextInt(); boolean boolean bb (a (a 0); 0); System.out.println("(a System.out.println("(a 0) 0) is is "" b); b); }} Enter a: 20 (a 0) is true Enter a: -3 (a 0) is false

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 35 3.10 Boolean Data Type (2/2) C In ANSI C, zero represents false and any other value represents true. if if (a%2 (a%2 0) 0) printf("a printf("a is is else else printf("a printf("a is is even\n"); even\n"); odd\n"); odd\n"); if if (a%2) (a%2) printf("a printf("a is is odd\n"); odd\n"); else else printf("a printf("a is is even\n"); even\n"); This is not the case for Java. Java if if (a%2 (a%2 0) 0) System.out.println("a System.out.println("a is is else System.out.println("a else System.out.println("a is is if if (a%2) (a%2) else else even"); even"); odd"); odd"); System.out.println("a System.out.println("a is is odd"); odd"); System.out.println("a System.out.println("a is is even"); even"); Compilation error!

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 36 3.11 Selection Statements (1/2) Selection statements in Java – ‘if-else’ and ‘switch’ – are the same as those in C if if ((age ((age 1) 1) (age (age 120)) 120)) System.out.println("Invalid System.out.println("Invalid age."); age."); else else if if (age (age 18) 18) System.out.println("Eligible System.out.println("Eligible for for driving driving licence."); licence."); System.out.println("Enter System.out.println("Enter marks marks (0-100): (0-100): "); "); int int marks marks sc.nextInt(); sc.nextInt(); Grade.java char char grade; grade; switch switch (marks/10) (marks/10) {{ case case 8: 8: case case 9: 9: case case 10: 10: grade grade 'A'; 'A'; break; break; case case 7: 7: grade grade 'B'; 'B'; break; break; case case 6: 6: grade grade 'C'; 'C'; break; break; case case 5: 5: grade grade 'D'; 'D'; break; break; default: default: grade grade 'F'; 'F'; }}

NUS CS1010 (AY2014/5 Semester 1) 3.11 Selection Statements (2/2) Short-circuit evaluation applies in Java as in C if if ((count ((count ! ! 0) 0) && && (sum/count (sum/count 0.5)) 0.5)) {{ . . }} If count is zero, the second boolean expression (sum/count 0.5) will not be evaluated. Unit20 - 37

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 38 3.12 Repetition Statements Repetition statements in Java – ‘while’, ‘do-while’ and ‘for’ – are also the same as those in C int int ii 1, 1, sum sum 0; 0; while while (sum (sum 1000) 1000) {{ sum sum i; i; i ; i ; }} do do {{ age age sc.nextInt(); sc.nextInt(); }} while while ((age 1) ((age 1) (age 120)); (age 120)); for for (( int int i 0; i 0; i 10; i 10; i i )) {{ System.out.println(i); System.out.println(i); }} System.out.println(i); System.out.println(i); Java allows loop variable to be declared in the ‘for’ block; however, the scope of variable i is bound within the block. Compilation error as variable i is not recognised outside the ‘for’ block.

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 39 3.13 Arrays (1/4) In Java, an array is an object, and has a public attribute length which is the number of elements of the array. Declaration: C Java int int arr[8]; arr[8]; int[] int[] arr arr new new int[8]; int[8]; Initialisation: C Java double double arr[] arr[] {{ 1.2, 1.2, 3.5, 3.5, 2.7 2.7 }; }; double[] double[] arr arr {{ 1.2, 1.2, 3.5, 3.5, 2.7 2.7 }; };

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 40 3.13 Arrays (2/4) public class ArrayDemo1 { public static void main(String[] args) { int[] arr; // create a new integer array with 3 elements // arr now refers (points) to this new array arr new int[3]; ArrayDemo1.java Length arr[0] arr[1] arr[2] // using the 'length' attribute System.out.println("Length " arr.length); arr[0] 100; arr[1] arr[0] - 37; arr[2] arr[1] / 2; for (int i 0; i arr.length; i ) { System.out.println("arr[" i "] " arr[i]); } } } 3 100 63 31

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 41 3.13 Arrays: Passing Array to a Method (3/4) public class ArrayDemo2 { ArrayDemo2.java public static void main(String[] args) { int[] arr new int[3]; System.out.println("Length " arr.length); arr[0] 100; arr[1] arr[0] - 37; Length 3 arr[2] arr[1] / 2; a[0] 100 printArray(arr); a[1] 63 } a[2] 31 public static void printArray(int[] a) { for (int i 0; i a.length; i ) { System.out.println("a[" i "] " a[i]); } } }

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 42 3.13 Arrays: Passing Array to a Method (4/4) ArrayDemo3.java import java.util.*; public class ArrayDemo3 { public static void main(String[] args) { int[] arr new int[3]; scanArray(arr); System.out.println("Sum " sumArray(arr)); } public static void scanArray(int[] a) { Scanner sc new Scanner(System.in); System.out.print("Enter " a.length " values: "); for (int i 0; i a.length; i ) a[i] sc.nextInt(); } public static int sumArray(int[] a) { int sum 0; for (int i 0; i a.length; i ) Enter Sum sum a[i]; return sum; } } 3 values: 16 32 8 56

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 43 4. API (1/4) The service classes we have used (Scanner, String, Math, DecimalFormat) are all parts of the Java API (Application Programming Interface) API: an interface for other programs to interact with a program without having direct access to the internal data of the program Documentation, SE7: http://docs.oracle.com/javase/7/docs/api/ You may also access the above link through CS1020 website Resources Online (http://www.comp.nus.edu.sg/ cs1020/2 resources/online.html) For Java programmers, it is very important to refer to the API documentation regularly! The API consists of many classes (hundreds of them!) You will learn more about them in CS1020

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 44 4. API: Scanner Class (2/4) nextInt() nextFloat() nextDouble() next() nextLine() hasNextInt() hasNextFloat() And many more

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 45 4. API: Math Class (3/4) abs() ceil() floor() hypot() max() min() pow() random() sqrt() And many more

NUS CS1010 (AY2014/5 Semester 1) 4. API: String Class (4/4) Ubiquitous Has a rich set of methods to manipulate strings charAt() concat() equals() indexOf() lastIndexOf() length() toLowerCase() toUpperCase() substring() trim() And many more Unit20 - 46

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 47 5. Conclusion We have attempted to confine this unit to nonOOP aspects of Java The aim is to allow you to understand the basic Java (non-OOP) constructs and To convert some of the C programs you have written in CS1010 to Java programs

NUS CS1010 (AY2014/5 Semester 1) Unit20 - 48 Summary In this unit, you have learned about The program structure of Java The non-OOP aspects of Java programming Variables, constants, methods, selection and repetition statements Using classes (Scanner, String, Math, DecimalFormat) and packages Java naming convention Declaration and use of arrays API: The Java documentation

NUS CS1010 (AY2014/5 Semester 1) End of File Unit20 - 49

Related Articles

Back to top button