1 / 69

C++ to Java

C++ to Java. Gang Qian Department of Computer Science University of Central Oklahoma. Objectives. Install and configure JDK Edit and compile Java programs Use JDK documentation Major differences between Java and C++. Download JDK. Download Java 6 from

acampbell
Download Presentation

C++ to Java

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. C++ to Java Gang Qian Department of Computer Science University of Central Oklahoma

  2. Objectives • Install and configure JDK • Edit and compile Java programs • Use JDK documentation • Major differences between Java and C++

  3. Download JDK • Download Java 6 from • http://java.sun.com/javase/downloads/index.jsp • Run the download setup program to install JDK

  4. Configure JDK on Windows XP • Set up Java paths so that Windows XP can find Java commands • Right click on the My Computer icon on the desktop • In the shortcut menu, select Properties • In the System Properties window, click on the Advanced tab • Click on the Environment Variables button • In the Environment Variables window, You can set or modify user variables or system variables • User variables affect the individual users • System variables affect all the users in the system

  5. Under the User variables section, choose PATH and click Edit if PATH is already a user variable. Otherwise, click New to display the New User Variable window • Enter PATH in the Variable textbox, add C:\Program Files\Java\jdk1.6.0\bin;%path%; in the Variable Value textbox and then click on OK. • Note: “C:\Program Files\Java\jdk1.6.0\bin” should be replaced with the folder in which you install the JDK • No need to reboot the computer. Open a new command window to use JDK commands

  6. You may also need to add or modify the environment variable CLASSPATH • Create or edit CLASSPATH so that it has “.” • Example: .;...

  7. Hello, World! • Classes are building blocks of a Java program • Unlike C++, there is no independent procedure or function in Java • A typical Java class has three parts: • Constructor • Method • Instance variable

  8. public class Greeter { private String name; public Greeter(String aName){ name = aName; } public String sayHello(){ return "Hello, " + name + "!"; } } • There is no ending semicolon in a class definition • Each part of the definition is tagged as public or private • The syntax is different from C++, but the meanings are similar • More discussion later

  9. In Java, a method declaration always includes its body • The declaration and the definition of a method in C++ are often separate • Java requires that, if a method is declared to return something, then you need to guarantee that the method will always return something under all circumstances • For example, the follow method needs at least an else clause public boolean isOdd(){ if (value%2 != 0) { return true; } else return false; }

  10. Construct new objects with new operator new Greeter("World") • The new operator returns a reference (pointer) to the constructed object • Called an instance of the Greeter class • We can call methods of an object (new Greeter("World")).sayHello() • An object of the Greeter class is created on the fly and its method sayHello() is called

  11. Object references are usually stored in a variable if they are used repeatedly Greeter worldGreeter = new Greeter("World"); • worldGreeter is a variable that holds the reference • Method of an object can be invoked on the variable String greeting = worldGreeter.sayHello(); • Now we need to run the Greeter class and display the greetings

  12. Java has two types of variables: primitive and reference • Primitive type variables are those defined with primitive data types such as int, double, etc. • If a variable is declared using a class name, it is a reference variable • Note the difference between Java and C++ here • Java references are similar to C++ pointers • C++: Greeter* worldGreeter • There are no object variables in Java

  13. Execution of a Java Program starts with the main method of a class public class GreeterTester { public static void main(String[] args){ Greeter worldGreeter = new Greeter("World"); String greeting = worldGreeter.sayHello(); System.out.println(greeting); } } • The main method is static, which means that you do not need to have an instance of the class to call the method • The args parameter holds command-line arguments • Similar to int main(int argc, char **argv) in C++ • The println method of object System.out is used to print the result on screen

  14. Run a Java Program • In Java, usually each class is put in a separate file named classname.java • E.g., we put class Greeter in file Greeter.java and put class GreeterTester in file GreeterTester.java • Note that Java is case-sensitive. Make sure that the file name is exactly the same as the class name in it

  15. Using the JDK • Create a new directory to hold your files • Use a text editor to prepare files (Greeter.java, GreeterTester.java) • Open a shell window, e.g., Command Prompt in Windows • Go to the directory that holds your files • Compile and run Compile: javac GreeterTester.java Run: java GreeterTester • Note that Greeter.java is automatically compiled • Output is shown in the console • javac is the command to invoke the Java compiler • It generates binary code in .class files for each class • java is the command to invoke the Java interpreter that runs the compiled program (the class that contains the main method)

  16. The structure of this program is a typical Java application: • The program contains a collection of classes • One class has a main method • The program is started by launching the Java interpreter with the name of the class that contains the main method

  17. Java Documentation • Download Java 6 documentation at: • http://java.sun.com/javase/downloads/index.jsp • Follow the instructions on the same page to unzip the documentation • Or view the documentation online at: • http://java.sun.com/javase/6/docs/api/

  18. Exercise • Download, install and configure Java 6 • Create, compile and run the HelloWorld program • Add a sayGoodbye method to the Greeter class and add a call to test the method in the GreeterTester class • What happens if you run the Java interpreter on the Greeter class instead of the GreeterTester class? Try and explain • Browse JDK documentation and understand its general structure

  19. Primitive Types • Values of primitive types are not object references • They are very similar to those of C++ • Notes • A number without the fractional part is int by default • A number with the fractional part is double by default

  20. To indicate long constants, use a suffix L, such as 100000000000L • float constants need a suffix F, such as 3.14159F • Characters (char) are encoded in Unicode • Unicode: A uniform encoding scheme for characters in many languages around the world • See http://www.unicode.org/ • For characters: http://www.unicode.org/charts/ • char constants are enclosed in single quotes, such as ‘a’ • Unicode representation: ‘\u0000’ - ‘\uFFFF’, such as ‘\u0061’ (letter ‘a’) • Some special characters can also be represented as escape sequences, such as the newline character ‘\n’

  21. A list of common escape sequences in Java • \b - backspace • \t - tab • \n - linefeed • \f - formfeed • \r - carriage return • \" - double quote • \' - single quote • \\ - backslash

  22. Java versus C++ • While data types in C and C++ are often machine and compiler dependent (for instance the size of int), Java specifies everything • All numeric variables in Java are signed • Implicit conversions are only allowed when there is no information loss • E.g., short to int or float to double • All other conversions require a cast: double x = 1.0; int n = (int) x; • Java prevents casting between arbitrary variables • Only casts between numeric variables and between sub and super classes of the same object are allowed • It is not possible to convert between the boolean type and a numeric type • Java requires that a local variable must be initialized before being referenced

  23. Mathematical functions • The Math class implements many useful mathematical methods • Remember that there is no stand-alone functions in Java • Note the difference between Java and C++ (<cmath> and <math.h>) • Examples • Math.sqrt(x): Square root of x • Math.pow(x, y): xy • Math.round(x): Closest integer to x • Math.abs(x): Absolute value |x|

  24. Control Flow Statements • Java control flow statements are almost the same as those in C++ • Exception handling has some differences that we will discuss later

  25. Loop Statements • while (expression) { statement } • do { statements } while (expression); • for (initialization; termination; increment) { statements } • Decision making • if (expression) { statements } else { statements } • switch (expression) { case value1: statements; break; case value2: statements; break; ... default: statements; }

  26. Java Comments • Comments with several lines (C style) • /* … */ • Comments with a single line (C++ style) • // • Java Documentation • /** … */ • Used to explain user defined classes and their methods • The command javadoc will extract the information and generate Java API style documentation

  27. Object References • As we have seen in the Hello World example, an object value is always a reference (pointer) to an object in Java Greeter worldGreeter = new Greeter("World"); • The new operator returns a reference to the newly constructed Greeter object • This is quite different from C++

  28. Multiple variables may have references to the same object Greeter anotherGreeter = worldGreeter; • Like references/pointers in C++, the change of the instance variable name will be reflected in both variables • To make a copy of the object itself, the clone method should be called • Discussed later

  29. Special reference null • null refers to no object • A reference variable can be set to null: worldGreeter = null • You can also test whether a reference variable is currently null if ( worldGreeter == null ) ... • Invoking a method on a null reference results in a runtime error: NullPointerException • Exceptions are discussed later • If there is an object that is not referenced by any variables, it will be recycled by garbage collector • No explicit delete • Java is safer than C++: no garbage and dangling pointers

  30. Strings • Java strings are a sequence of Unicode characters (2 bytes each) • chatAt method returns a character at a certain location in a String object String s = “World!”; char c = s.charAt(1); // c is ‘o’ now • The String class is immutable • Once created, its state (content) can not be changed • E.g., there is no setCharAt method s = “Hello!”;

  31. length method returns the length (number of characters) of a string • The length of an empty string "" is 0 • Note: an empty string is different from null • substring method yields substrings "Hello".substring(1, 3) is "ell" • Use equals to compare strings if(s.equals("Hello")) • == only tests whether the object references are identical: if ("Hello".substring(1, 3) == "ell") ... // NO!

  32. + operator concatenates strings: "Hello, " + name • If one argument of + is a string, the other is converted into a string: int n = 7; String greeting = "Hello, " + n; // yields "Hello, 7" • It works because every object in Java has a toString method, which is implicitly called when a conversion is needed Date now = new Date(); String greeting = "Hello, " + now; // concatenates now.toString() // yields "Hello, Wed Jan 17 16:57:18 PST 2001"

  33. Convert strings to numbers • Use the static methods: Integer.parseInt and Double.parseDouble String input = "7"; int n = Integer.parseInt(input); // yields integer 7 • If a string doesn't contain a number, it throws a NumberFormatException (unchecked) • Classes Double and Integer are wrapper classes for the corresponding primitive types • They will be further discussed later • Convert values of primitive types to strings • Overloaded static methods valueOfof Class String: • String s = String.valueOf(1.1);

  34. Parameter Passing • Implicit parameter: the object reference on which a method is called • Explicit parameter: parameters supplied between parentheses • Example: myGreeter.setName(“Mars”) • The reference stored in myGreeter is the implicit parameter • The string “Mars” is an explicit parameter • The implicit parameter of a method can be referred to by the keyword this • This can be used to resolve confliction public void setName(String name){ this.name = name; }

  35. Java uses "call by value": • Method receives a copy of a parameter value • The actual parameter value out of the method can not be changed inside the method • Note that a parameter of an object reference allows a method modify the object • Example: public void copyNameTo(Greeter other){ other.name = this.name; } Greeter worldGreeter = new Greeter("World"); Greeter daveGreeter = new Greeter("Dave"); worldGreeter.copyNameTo(daveGreeter);

  36. Java is different from C++ in that there is no “pass by reference” mechanism • In C++, the symbol “&” is used to indicate “pass by reference” • Example: public void copyLengthTo(int n){ n = name.length(); } public void copyGreeterTo(Greeter other){ other = new Greeter(name); } • There will be no effect after the methods return if we use the following statements: int length = 0; // length still 0 worldGreeter.copyLengthTo(length); // daveGreeter unchanged worldGreeter.copyGreeterTo(daveGreeter)

  37. Packages • Related classes can be grouped into packages • More organized, like the C++ libraries • Package names are dot-separated sequences of identifiers, such as • java.util • javax.swing • com.sun.misc, and • edu.ucok.comsc.cmsc3103.qian • Also helps to resolve class names • Class names only need to be unique within the same package • It is recommended that you start a package name with your domain name in reverse and then use some mechanism within your organization to ensure the remainder of the package name is unique • E.g., java.util and edu.ucok.comsc.cmsc3103.qian

  38. To place a class inside a package, add a package statement at the beginning of the source file package edu.ucok.comsc.cmsc3103.qian; public class Greeter{ ... } • Any class without a package statement is in the “default package” with no package name • The full name of a class consists of the package name followed by the class name • E.g., edu.ucok.comsc.cmsc3103.qian.Greeter • Java API: java.util.ArrayList

  39. Instead of using the long full name, it is very common to use the import keyword • E.g., import edu.ucok.comsc.cmsc3103.qian.Greeter • Then just use class name Greeter in the program • If you use two classes with the same name from different packages, then you must use at least one of them with the full name • You can also import all classes from a package • E.g., import java.util.*; • Classes in the java.lang package do not need import, such as the class String

  40. The class files must be located in subdirectories that match the package names • E.g., the class file Greeter.class in package edu.ucok.comsc.cmsc3103.qian must be placed in: Linux/UNIX: edu/ucok/comsc/cmsc3103/qian, or WINDOWS: edu\ucok\comsc\cmsc3103\qian of the base directory of the project • Then you need to always compile from the base directory and run from the base directory • Compile: javac edu/ucok/comsc/cmsc3103/qian/Greeter.class, or javac edu\ucok\comsc\cmsc3103\qian\Greeter.class • Run: java edu.ucok.comsc.cmsc3103.qian.greeter

  41. Basic Exception Handling • An exception occurs when the program deals with an abnormal situation String name = null; int n = name.length(); // A NullPointerException occurs • When an exception occurs and there is no handler for it, the program terminates • Different situations will generate different exception types • If the program try to open a file that does not exist, then a FileNotFoundException will occur • Like in C++, you can also define your own exceptions and use them in Java • More discussion in the “Exception” lecture

  42. In Java, there are two categories of exceptions: checked and unchecked • Java requires you to handle a checked exception by either declare it or catch it • Otherwise a compiling error will occur when you compile the program • The FileNotFoundException is a checked exception • You are not required to explicitly handle an unchecked exception • When one occurs, the program simply stops • The NullPointerException is an unchecked exception

  43. Usually a checked exception is caused by some external condition that beyond the programmer’s control • Therefore the compiler insists that the programmer handle those situations • Unchecked exceptions are often programming problems • Programmers are expected to eliminate this kind of exceptions by themselves

  44. When you write code that might cause a checked exception, you have two options: • Declare the exception in the method header using throws, or • catch the exception public void read(String filename){ FileReader reader = new FileReader(filename); ... } • The above example will have a compiling error • We can declared the checked exception in the method header public void read(String filename) throws FileNotFoundException{ FileReader reader = new FileReader(filename); ... }

  45. If the body of a method can throw multiple unhandled checked exceptions, all of them should be listed and separated by commas in the method header public void read(String filename) throws IOException, ClassNotFoundException • When a user method throws checked exception(s), the callers of the method also needs to handle them • The whole process may propagate all the way to the main method, at which point the program stops public static void main(String[] args) throws IOException, ClassNotFoundException

  46. You can also handle an exception by catching them try{ code that might throw an IOException }catch (IOException exception){ take corrective action } • Corrective action can be: • Notify user of error and offer to read another file • Log error in error report file • Or for debugging purpose: print stack trace and exit exception.printStackTrace(); System.exit(1);

  47. The finally clause of the try statement is optional • Mainly for cleanup during normal and exceptional processing, since it will run in either situation • Example: Close a file FileReader reader = null; try{ reader = new FileReader(name); ... }catch(Exception e){ ... }finally{ if (reader != null) reader.close(); }

  48. Use exceptions • You can throw exceptions in your own program • Two types of built-in exceptions can be thrown: • Exception: it is a checked exception • RuntimeException: it is an unchecked exception • RuntimeException is actually a subclass of Exception • Example: int a = 1, b = 0; if (b != 0) a /= b; else throw new ArithmeticException("Divided by zero!");

  49. Reading Input • The Scanner class (after Java5) canbe used to read user input from console Scanner in = new Scanner(System.in); System.out.print("How old are you?"); int age = in.nextInt(); • In the example, if the user does not enter a number, an InputMismatchException (unchecked) is thrown • The exception can be prevented by using the hasNextInt method before the nextInt method • There are also Scanner methods which allow you to read other data types (See Java API Documentation)

  50. Scanner is a quite convenient class that can be used for inputs from not only the console but also files and strings • See Scanner constructors • File I/Os will be discussed in the “File I/O” lecture • Exercise • Let user enter a String and display the reverse of the string

More Related