1 / 50

Java Workshop Part #1

Java Workshop Part #1. Basics of Java and Object-Oriented Programming (OOP). Objectives. Basics of Java: Start writing Java programs Translate basic C programs learned in CS1010 into Java programs Basics of Object-Oriented Programming (OOP) Learning basic OOP concepts

ronia
Télécharger la présentation

Java Workshop Part #1

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. Java Workshop Part #1 Basics of Java and Object-Oriented Programming (OOP)

  2. Objectives • Basics of Java: • Start writing Java programs • Translate basic C programs learned in CS1010 into Java programs • Basics of Object-Oriented Programming (OOP) • Learning basic OOP concepts • Writing user-defined own classes Introductory Java Workshop - Part I

  3. 1. Overview Introductory Java Workshop - Part I • Procedural Programming • Focus on specifying the steps the program must take to solve a problem. • E.g., pasta cooking • Prepare a liter of water • Add water into the pot • Boil water • Prepare 2 cups of pasta • Add pasta into the pot • Keep water boiling • Retrieve pasta

  4. 1. Overview Introductory Java Workshop - Part I • Object-oriented Programming • Focus on modeling the data and tools as objects and solving a problem by interacting with such objects. • E.g., pasta cooking (ver 1.) • Create pot • Prepare water (amount: 1 liter) • Pot:take_in water • Pot: heat_up • Prepare pasta (amount: 2 cups) • Pot: take_in pasta • Pot: heat_up • Pot: dispense

  5. 1. Overview Introductory Java Workshop - Part I • The better the data/tools are modeled and implemented, the easier it is to solve the problem. • E.g., pasta cooking (ver 2.) • Create pot • Prepare water (amount: 1 liter) • Prepare pasta (amount: 2 cups) • pot: cook water pasta • pot: dispense • E.g, check whether a number appears in a set of numbers • Unsorted array O(n) • Sorted array O(logn) • Hashtable O(1)

  6. 2. Java: Brief History & Background • Developed by James Gosling: • in 1995 • at Sun Microsystems (acquired by Oracle in 2010) • Use Cand C++ as the foundation • "Cleaner" in syntax • Less low-level functionality • Shield the user from low-level machine interaction • More uniform object model • Some selling points: • Write Once, Run Everywhere™ • Compiled binary can be executed across different platforms • Extensive and well documented standard library Introductory Java Workshop - Part I

  7. 2. Compile Once, Run Anywhere? How? • Normal executable files are directly dependent on the OS / Hardware • Hence, an executable file is usually not executable on different platforms • E.g: The a.out file compiled on sunfire is not executable on a different machine • Java overcomes this by running the executable on an uniform hardware environment simulated by software • The hardware environment is know as the Java Virtual Machine (JVM) • So, we only need a specific JVM for a particular platform to execute all Java bytecodeswithout recompilation Introductory Java Workshop - Part I

  8. 2. Recap: Run Cycle for C Programs vim hello_world.c hellow_world.c a.out gcc -Wall hello_world.c a.out output Introductory Java Workshop - Part I • Writing/Editing Program • Use an editor, e.g.: vim • Source code must have a .c extension • e.g.: hello_world.c • Compiling Program • Use a C compiler, e.g.: gcc • e.g.: gcc -Wall hello_world.c • Default executable file: a.out • Executing Binary • Type name of executable file • e.g.: a.out

  9. 2. Run Cycle for Java Programs vim HelloWorld.java HelloWorld.java HelloWorld.class javac HelloWorld.java java HelloWorld output • Writing/Editing Program • Use an text editor, e.g.: vim • Source code must have a .java extension • e.g.: HelloWorld.java • Compiling Program • Use a Java compiler, e.g.: javac • e.g.: javac HelloWorld.java • Compiled binary has .class extension: • e.g.: HelloWorld.class • Executing Binary • Run on a Java Virtual Machine (JVM) • e.g.: java HelloWorld(leave out the .class extension) Introductory Java Workshop - Part I

  10. 2. Java Execution Illustration a.out Normal executable (e.g.: C programs) are tied to a specific platform (OS + Hardware) Windows 7 on Core 2 HelloWorld.class Java Virtual Machine Windows 7 on Core 2 JVM provides a uniform environment for Java bytecode execution. HelloWorld.class Java Virtual Machine MacOS on PowerPC Introductory Java Workshop - Part I

  11. 3. Basics of Java • To cover the elementary language components: • Basic program structure • Import package • Input/Output • User-defined methods • Programming exercises • Hello World • Distance Conversion Introductory Java Workshop - Part I

  12. 3. Demo #1: A Hello World Program #include <stdio.h> int main(void) { printf("Hello World!\n"); return0; } C program hello_world.c import java.lang.*; // optional classHelloWorld{ public static void main(String[] args) { System.out.println("Hello World!"); } } Java program HelloWorld.java Introductory Java Workshop - Part I

  13. 3. import java.lang.*; • Library in Java is known as package • Packages are organized into hierarchical grouping • E.g., the “System.out.println()” is defined in the package “java.lang.System” • i.e. “lang” (language) is a group of packages under “java” (the main package) and “system” is a package under “lang” • To use a predefined library, the appropriate package should be imported: • Using the “importXXXXXX;” statement • All packages under a group can be imported with a “*” (the wildcard character) • Packages under “java.lang” are imported by default: • i.e. the import statement in this example is optional Introductory Java Workshop - Part I

  14. 3. class HelloWorld import java.lang.*; // optional classHelloWorld{ public static void main(String[] args) { … • Class • The methods (functions) are enclosed in a "class" • The idea of class will be explained later • Each source code file contains one or more classes • Each class will be compiled into a separate XXXX.classbytecode • The “XXXX” is taken from the class name (“HelloWorld” in this example) • The words in a class name should be InitialCapitalized. Introductory Java Workshop - Part I

  15. 3. public static void main(String[] args) … classHelloWorld{ public static void main(String[] args) { … • public and static • Modifiers for setting access levels and achieving many other functionalities. (To be detailed later) • void • Return type for methods that do not return any value. • String[] args • A string array for passing in command line arguments Introductory Java Workshop - Part I

  16. 3. System.out.println() … public static void main(String[] args) { System.out.println("Hello World!"); } … printf("Hello World!\n"); Print a string onto screen with an "\n" Introductory Java Workshop - Part I

  17. 4. Ex #1: Hello World! vim HelloWorld.java HelloWorld.java HelloWorld.class javac HelloWorld.java import java.lang.*; // optional classHelloWorld{ public static void main(String[] args) { System.out.println("Hello World!"); } } java HelloWorld Beginners’ common mistake: Class name not identical to program’s file name. output HelloWorld.java Introductory Java Workshop - Part I Type in, compile and run this program:

  18. 5. Demo #2: Fahrenheit to Celsius import java.util.Scanner; // or import java.util.*; classFtoC { public static void main(String[] args) { doublefahrenheit, celsius; Scanner sc = new Scanner(System.in); System.out.print("Enter temperature in Fahrenheit: "); fahrenheit = sc.nextDouble(); celsius = (5.0/9) * (fahrenheit – 32); System.out.println("Celsius: " + celsius); } } FtoC.java Introductory Java Workshop - Part I

  19. 5. More about printing System.out.print("Enter temperature in Fahrenheit: "); System.out.println("Celsius: " + celsius); System.out.printf("Celsius: %f\n",celsius); • Print a string onto screen as it is (no "\n" added) • Strings in Java can be concatenated using + • Numbers / variables are automatically converted to strings when concatenated • printf() is also available in the same package Introductory Java Workshop - Part I

  20. 5. Reading Input: Key Points (1/2) • The statement Scannersc = newScanner(System.in); • Declares a variable “sc” of Scanner type • The initialization “newScanner(System.in)” • Constructs a Scanner object • We will discuss more about object later • Attaches it to the standard input “System.in” (which is the keyboard) • This Scanner object sc will receive input from this source • Scanner can attach to a variety of input sources; this is just a typical usage Introductory Java Workshop - Part I

  21. 5. Reading Input: Key Points (2/2) • After proper initialization, a Scanner object provides functionality to read value of various types from the input source • fahrenheit= sc.nextDouble(); • nextDouble() returns a double value read interactively • The Scanner object sc converts the input into the appropriate data type (double value in this case) and returns it Introductory Java Workshop - Part I

  22. 6. Exercise #2: Distance (1/2) // Converts distance in miles to kilometres. #include <stdio.h> #define KMS_PER_MILE 1.609/* conversion constant */ int main(void) { double miles, kms; printf("Enter distance in miles: "); scanf("%lf", &miles); kms = KMS_PER_MILE * miles; printf("That equals %9.2f km.\n", kms); return0; } mile_to_km.c • How do use define a constant in Java? (We haven’t covered that.) • Just use 1.609 in your program for the time being. We will show you how to define a constant. In CS1010 Week 2 Example 3, we show a C program to convert miles to kilometers. Convert it to Java. Introductory Java Workshop - Part I

  23. 6. Exercise #2: Distance (2/2) static: It belongs to the class, not individual objects in the class. // Converts distance in miles to kilometres. import java.util.*; class MileToKm { public static void main(String[] args) { double miles, kms; Scanner sc = new Scanner(System.in); System.out.print("Enter distance in miles: "); miles = sc.nextDouble(); kms = 1.609 * miles; System.out.printf("That equals %9.2f km.\n", kms); } } public static final double KMS_PER_MILE = 1.609; final: It cannot change its value. kms = KMS_PER_MILE * miles; MileToKm.java  Introductory Java Workshop - Part I

  24. 7. Demo #2 Modularized import java.util.Scanner; // or import java.util.*; classFtoCModularized { public static void main(String[] args) { doublefahrenheit, celsius; Scanner sc = new Scanner(System.in); System.out.print("Enter temperature in Fahrenheit: "); fahrenheit = sc.nextDouble(); celsius = convert(fahrenheit); System.out.println("Celsius: " + celsius); } public static double convert(doublefahrenheit){ return(5.0/9) * (fahrenheit – 32); } } FtoCModularized.java Introductory Java Workshop - Part I User-defined methods

  25. 8. Ex #3: Distance Modularized (1/2) … public static void main(String[] args) { double miles, kms; Scanner sc = new Scanner(System.in); System.out.print("Enter distance in miles: "); miles = sc.nextDouble(); kms = convert(miles); System.out.printf("That equals %9.2f km.\n", kms); } public static void convert(double miles){ return KMS_PER_MILE * miles; } … Revise your program to include a function convert() which takes in the distance in miles and return it in kilometers. Introductory Java Workshop - Part I

  26. 8. Ex #3: Distance Modularized (2/2) // Converts distance in miles to kilometres. import java.util.*; classMileToKmModularized { public static final double KMS_PER_MILE = 1.609; public static void main(String[] args) { double miles, kms; Scanner sc = new Scanner(System.in); System.out.print("Enter distance in miles: "); miles = sc.nextDouble(); kms = convert(miles); System.out.printf("That equals %9.2f km.\n", kms); } public static void convert(double miles){ return KMS_PER_MILE * miles; } }  Revise your program to include a function convert() which takes in the distance in miles and return it in kilometers. Introductory Java Workshop - Part I

  27. 9. API • The Scanner class you have seen is part of the Java API • 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/ • For Java programmers, it is very important to refer to the API documentation regularly! • The API consists of many classes • You do not need to know all the classes (there are easily a few thousand classes altogether!) • You will learn some more classes in this course Introductory Java Workshop - Part I

  28. 9. The Scanner class (1/2) • From the API documentation Introductory Java Workshop - Part I

  29. 9. The Math class (1/2) • From the API documentation Introductory Java Workshop - Part I

  30. 9. The Math class (2/2) Introductory Java Workshop - Part I • Package: java.lang (default) • Some useful Math methods: • abs(), ceil(), floor(), max(), min(), pow(), random(),sqrt(), gcd() • Note the presence of many overloaded methods • double abs(double a), float abs(float a), int abs(int a), etc. • Overloading methods: 2 or more methods within the same class with the same name but different parameters • Very useful feature of Java • Hence, you may use abs() like this: intnum = Math.abs(-40); double x = Math.abs(-3.7);

  31. 9. Static/ Non-static methods Math class Scanner class • Method with the modifier staticis called a static (or class) method, otherwise it is a non-static (or instance) method. • Static method can be called without an instance • Example: Math.sqrt(3.14); • Non-static method needs to be called from an instance • Example: • Scanner sc = new Scanner(System.in); • int input = sc.nextInt(); Introductory Java Workshop - Part I

  32. 9. Class / Instance Attributes • A class attribute (or class member) can be accessed without creating an instance • Example: Math.PI Introductory Java Workshop - Part I • The Math class also has two class attributes

  33. 10. Demo #3: The Math class TestMath.java importjava.util.*; classTestMath { public static void main(String[] args) { doubleareaSquare, radius, areaCircle; Scanner sc = new Scanner(System.in); System.out.print("Enter area of a square: "); areaSquare = sc.nextDouble(); radius = Math.sqrt(areaSquare)/2; areaCircle = Math.PI * Math.pow(radius,2); System.out.printf("Area of circle = %.4f\n", areaCircle); } } Introductory Java Workshop - Part I

  34. 11. Object-Oriented Programming • We’ll introduce some OOP concepts by defining our own class, from which we can create instances (objects) • A class is a template, so whatever properties (attributes) we want for objects in that class, we need to define them. • a.k.a. data members or fields • They can be class attributes or instance attributes – to be explained later • After defining the attributes, we want to define behaviours that we can perform on objects of the class. These behaviours are implemented as methods • Again, there are class methods and instance methods Introductory Java Workshop - Part I

  35. 11. Defining our own class: Ball (1/5) • Let’s create a new class called Ball • Obviously, we want to create ball objects out of it • Let’s start with something simple, and add more complexity gradually. • We may start with 1 instance attribute: • Radius of the ball, which is of type double (e.g.: 6.5, 12.8) • Some Ball objects we may create: Introductory Java Workshop - Part I

  36. 11. Defining our own class: Ball (2/5) • Sometimes, we want to have some class attributes in a class, shared by all instances (objects) of that class • Let’s have one class attribute for illustration purpose • The number of ball objects created in a program run • Next, for behaviours, a class in general consists of at least these 3 types of methods • Constructors: to create an instance • Accessors: to access (retrieve) values of the attributes • Mutators: to mutate (modify) values of the attributes • The definition of the Ball class is in Ball.java • This program has no main() method, because it is not an application program Introductory Java Workshop - Part I

  37. 11. Defining our own class: Ball (3/5) Only accessible by the methods in this class class Ball { /************** Data members **********************/ private static int quantity = 0; privatedouble radius; /************** Constructors **********************/ // Default constructor creates a radius 10.0 ball public Ball() { this(10.0); } // Alternative constructor creates a ball of any radius public Ball(double radius) { setRadius(radius); quantity++; } Class attribute Instance attributes Accessible by all method Shorthand for the constructors in this class Ball.java Ball ball1 = new Ball(); // Create ball objects with Ball ball2 = newBall(15); // two different constructors Introductory Java Workshop - Part I

  38. 11. Defining our own class: Ball (4/5) /**************** Accessors ***********************/ public static intgetQuantity() { return quantity; } public double getRadius() { return radius; } /**************** Mutators ************************/ public void setRadius(double radius) { this.radius = radius; } Class method The rest are all instance methods. Refer to the object on which this method is called. Ball.java Ball.getQuantity(); // Return the number of balls created ball1.setRadius(5); // Change the radius of ball1 to 5 ball2.setRadius(15); // Change the radius of ball2 to 15 Introductory Java Workshop - Part I

  39. 11. Defining our own class: Ball (5/5) /***************** Overriding methods ******************/ // Overriding toString() method public StringtoString() { return"[" + getRadius() + "]"; } // Overriding equals() method public booleanequals(Object obj) { if (objinstanceof Ball) { Ball ball = (Ball) obj; return this.getRadius() == ball.getRadius(); } else return false; } } The default version only returns the object id "Ball@xxxxx" while this version returns the radius. The default version checks whether two objects are the same object while this version compares the radius. Ball.java Introductory Java Workshop - Part I Default toString() and equals() are not customized and hence should be overridden.

  40. 12. Writing a client program javac Ball.java javac TestBall.java java TestBall After defining Ball class in Ball.java, we can now write an application program to test out the Ball class The application program is TestBall.java in the next slide. Application program contains a main() method. The Ball class is also known as the service class, while TestBall is the client (or driver). We say TestBalluses, or depends on, Ball. Ball.java and TestBall can be compiled independently. Only TestBall can be executed. Introductory Java Workshop - Part I

  41. 12. A client program for Ball (1/2) TestBall.java importjava.util.*; classTestBall { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter radius: "); Ball myBall1 = new Ball(sc.nextDouble()); // Read input and create Ball object System.out.println(); System.out.print("Enter radius: "); Ball myBall2 = new Ball(sc.nextDouble()); // Read input and create Ball object System.out.println(); System.out.println(Ball.getQuantity() + " balls are created."); System.out.println("1st ball: " + myBall1); System.out.println("2nd ball: " + myBall2); // Testing == System.out.println("(myBall1 == myBall2) is " + (myBall1 == myBall2)); // Testing equals() method System.out.println("myBall1.equals(myBall2) is " + myBall1.equals(myBall2)); } } toString() is called implicitly to obtain the string representation. Introductory Java Workshop - Part I

  42. 12. A client program for Ball (2/2) Enter radius: 1.2 Enter radius: 1.2 2 balls are created. 1st ball: [1.2] 2nd ball: [1.2] (myBall1 == myBall2) is false myBall1.equals(myBall2) is true Enter radius: 1.2 Enter radius: 1.5 2 balls are created. 1st ball: [1.2] 2nd ball: [1.5] (myBall1 == myBall2) is false myBall1.equals(myBall2) is false Introductory Java Workshop - Part I Sample run of TestBall

  43. 13. Ex #4: Fraction (1/4) • Create a Fraction class with 2 attributes, both integers: • private intnumer; // numerator • private intdenom; // denominator • Provide the following constructors • Default constructor Fraction() creates a fraction 1/1 • Alternative constructor Fraction(int, int) where the parameters are the numerator and denominator. You may assume that the denominator is always positive. • Provide the following methods (and others if necessary) • The overriding methods equals() and toString() (see sample runs) Introductory Java Workshop - Part I

  44. 13. Ex #4: Fraction (2/4) • Attributes  Accessors, Mutators, and Constructors  toString()  equals() • A client program TestFraction.java is provided, and should not be modified. It does the following: • Read data to create 2 fraction objects • Display the two fractions (use toString() implicitly) • Check if the 2 fractions are the same (use equals() ) • You must define your Fraction class such that running TestFraction produces the same output as the sample runs shown. Introductory Java Workshop - Part I

  45. 13. Ex #4: TestFraction.java (3/4) TestFraction.java importjava.util.*; classTestFraction { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter 1st fraction: "); int a = sc.nextInt(); int b = sc.nextInt(); Fraction f1 = new Fraction(a, b); System.out.print("Enter 2nd fraction: "); a = sc.nextInt(); b = sc.nextInt(); Fraction f2 = new Fraction(a, b); System.out.println(); System.out.println("1st fraction is " + f1); System.out.println("2nd fraction is " + f2); if (f1.equals(f2)) System.out.println("The fractions are the same."); else System.out.println("The fractions are not the same."); } • Read data to create 2 fraction objects • Check if the 2 fractions are the same • Display the 2 fractions Introductory Java Workshop - Part I

  46. 13. Ex #4: Sample runs (4/4) Enter 1st fraction: 3 3 Enter 2nd fraction: 3 3 1st fraction is 3/3 2nd fraction is 3/3 The fractions are the same. Enter 1st fraction: 0 8 Enter 2nd fraction: 6 14 1st fraction is 0/8 2nd fraction is 6/14 The fractions are not the same. Enter 1st fraction: 1 10 Enter 2nd fraction: 1 10 1st fraction is 1/10 2nd fraction is 1/10 The fractions are the same. Enter 1st fraction: -2 5 Enter 2nd fraction: 14 6 1st fraction is -2/5 2nd fraction is 14/6 The fractions are not the same. Introductory Java Workshop - Part I

  47. 14. Homework #1 Enter 1st fraction: 2 10 Enter 2nd fraction: 1 5 1st fraction is 2/10 2nd fraction is 1/5 The fractions are the same. Enter 1st fraction: -2 5 Enter 2nd fraction: 8 20 1st fraction is -2/5 2nd fraction is 8/20 The fractions are not the same. Introductory Java Workshop - Part I • Add a method simplify() into the Fraction class which returns the simplest form of a fraction. • E.g., calling simplify() on 2/10 gives 1/5. • Modify the equals() method in Fraction such that it compares two fractions based on their simplest form. • Sample runs:

  48. 14. Homework #2 (1/2) Introductory Java Workshop - Part I • Add two attributes x and y into the Ball class which represent the coordinates of the centre of a ball. • Modify the toString() method in Ball such that the string representation of a ball contains the radius and the coordinates of the centre of the balls. • Modify the equals() method in Ball such that it compares two balls based on the radius and the coordinates of the centre of the balls.

  49. 14. Homework #2 (2/2) Enter radius: 1.2 Enter centre: 1 1 Enter radius: 1.2 Enter centre: 1 1 2 balls are created. 1st ball: [1.2, (1, 1)] 2nd ball: [1.2, (1, 1)] (myBall1 == myBall2) is false myBall1.equals(myBall2) is true 2 balls are created. 1st ball: [1.2, (0, 3)] 2nd ball: [1.5, (0, 3)] (myBall1 == myBall2) is false myBall1.equals(myBall2) is false Enter radius: 1.2 Enter centre: 0 3 Enter radius: 1.5 Enter radius: 0.3 2 balls are created. 1st ball: [1.2, (0, 3)] 2nd ball: [1.2, (0, 5)] (myBall1 == myBall2) is false myBall1.equals(myBall2) is false Enter radius: 1.2 Enter centre: 0 3 Enter radius: 1.2 Enter radius: 0.5 Introductory Java Workshop - Part I Sample runs

  50. End of file Introductory Java Workshop - Part I

More Related