Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ to Java Gang Qian Department of Computer Science

Similar presentations


Presentation on theme: "C++ to Java Gang Qian Department of Computer Science"— 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
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 Enter PATH in the Variable textbox, add
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 There is no ending semicolon in a class definition
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 Method of an object can be invoked on the variable
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 javac is the command to invoke the Java compiler
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:
Follow the instructions on the same page to unzip the documentation Or view the documentation online at:

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 float constants need a suffix F, such as 3.14159F
To indicate long constants, use a suffix L, such as L float constants need a suffix F, such as F Characters (char) are encoded in Unicode Unicode: A uniform encoding scheme for characters in many languages around the world See For characters: 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 Decision making 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 valueOf of 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 You can also import all classes from a package
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 Unchecked exceptions are often programming problems
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 We can declared the checked exception in the method header
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{

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 Java 5) can be 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

51 Array In Java, you can create an array of any data type
primitive data types and built-in or user-defined classes An array is also an object Since it is an object, an array needs to be dynamically allocated like other types of objects int[] numbers = new int[10]; In the example, an array object of 10 integers is created and a reference to it is assigned to the variable numbers Java arrays are similar to those in C++ in that their sizes are fixed But there is a major difference that is often confusing You can not declare an array in Java using: int numbers[10];

52 When an array is declared, all of its elements are initialized to 0, false or null, depending on the element type int[] numbers = new int[10]; In the example, we get an array object of 10 zeros The following examples shows two ways to initialize an array with different values int[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; However, the following statements will not work. They must be put together in one statement: int[] numbers; // will not work numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] numbers = new int[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

53 Array access with [] operator:
int n = numbers[i]; All array objects have a length member (not a method!) that yields the number of elements for (int i = 0; i < numbers.length; i++) Note: An array of length 0 is different from null From Java 5, there is a new syntax that can be used for array traversal for (int n : numbers) System.out.println(n);

54 Object arrays Greeter[] greeterArray = new Greeter[4];
// The following statement will not work! // System.out.println(greeterArray[0].sayHello()); // // Need to construct a Greeter object for each // element in the array greeterArray[0] = new Greeter(“A"); greeterArray[1] = new Greeter(“B"); greeterArray[2] = new Greeter(“C"); greeterArray[3] = new Greeter(“D"); for(Greeter g : greeterArray) System.out.println(g.sayHello()); There is actually no array of objects. It is an array of object references. For each reference, a corresponding object needs to be constructed An array of object references are initialized to null

55 Multi-dimensional array
Declaration: int[][] table = new int[3][4]; Access: int t = table[2][1]; It is actually an array of arrays, so we have table.length, table[0].length, ... int[][] table = new int[3][]; table[0] = new int[1]; table[1] = new int[2]; table[2] = new int[3];

56 Command-Line Arguments
The argument args of the main method accepts command-line arguments public static void main(String[] args) Example: public class CommandLineTester{ public static void main(String[] args){ if(args.length > 0) for(String str : args) System.out.println(str); } java CommandLineTester 1 2

57 A Generic Class: ArrayList<E>
The size of an array can not be changed once it is constructed An ArrayList<E> can hold a sequence of objects of type E and the length of the sequence can be changed The ArrayList<E> class is a generic class (new feature from Java 5) E can be any class but it cannot be a primitive type

58 Its remove method has a similar efficiency problem
The add method appends an object of E to the end of the list by default ArrayList<String> countries = new ArrayList<String>(); countries.add("Belgium"); countries.add("Italy"); countries.add("Thailand"); It is also possible to specify a particular location in the list to insert the new object countries.add(1, "Germany"); But it is not efficient due to the contiguous implementation of ArrayList<E> Its remove method has a similar efficiency problem countries.remove(0);

59

60 The get method gets an element at a given position
There is no need to cast to correct type: String country = countries.get(i); The set method sets an element at a given position countries.set(1, "France"); The size method yields the number of elements for (int i = 0; i < countries.size(); i++) . . . Or you may use the "for each" loop for (String country : countries) . . .

61 When using a generic class, the actual type parameter needs to be provided in the angle bracket in the declaration ArrayList<String> countries = new ArrayList<String>(); Details discussed in the “Polymorphism” lecture

62 Static Variables Shared among all instances of a class Example 1:
A single memory location Example 1: Shared random number generator public class Greeter{ . . . private static Random generator; }

63 Example 2: Shared constants public class Math{ . . .
public static final double PI = ; } To access: use Math.PI directly You can also access it through an object, but it is not recommended due to readability reasons

64 Static Methods Declare a method with the static keyword
Example: Math.sqrt Example: public static Greeter getRandomInstance(){ // note: generator is static field if (generator.nextBoolean()) return new Greeter("Mars"); else return new Greeter("Venus"); }

65 To use, call Greeter.getRandomInstance()
You can also access it through an object, but it is not recommended Note: The instance variables/methods of a class cannot be accessed directly within a static method of the class

66 Java Programming Style
Case Convention Variables, fields and methods: Start with lowercase, use caps for new words: name, sayHello Classes: Start with uppercase, use caps for new words: Greeter, ArrayList Constants (final): Use all caps, underscores to separate words: PI, MAX_VALUE

67 Property Access Braces Common to use get/set prefixes:
String getName() void setName(String newValue) Boolean property has is prefixes: public boolean isEmpty() Braces "Allman" brace style: braces line up public String sayHello() { return "Hello, " + name + "!"; } "Kernighan and Ritchie" brace style: saves a line public String sayHello() {

68 Variables Some programmers put variables before methods:
public class Greeter{ private String name; public Greeter(String aName) { . . . } From OO perspective, it is better to list the public interface first All variables should be private

69 Miscellaneous Spaces around operators, after keywords, but not after method names Good: if (x > Math.sqrt(y)) Bad: if(x>Math.sqrt (y)) Don't use C-style arrays: Good: int[] numbers Bad: int numbers[] No magic numbers Good: h = HASH_MULTIPLIER * h + val[off]; Bad: h = 31 * h + val[off];


Download ppt "C++ to Java Gang Qian Department of Computer Science"

Similar presentations


Ads by Google