1 / 34

From C++ to Java

From C++ to Java. A whirlwind tour of Java for C++ programmers. Java statements. Identical to those of C++ Assignment Decision if else switch Repetition while for do while break, continue return catch, throw. Java scope rules.

birch
Télécharger la présentation

From 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. From C++ to Java A whirlwind tour of Java for C++ programmers

  2. Java statements • Identical to those of C++ • Assignment • Decision • if else • switch • Repetition • while • for • do while • break, continue • return • catch, throw

  3. Java scope rules • The scope of a local variable extends from the point where the variable is declared to the end of the block containing the declaration. • The scope of a formal parameter is the entire definition of the method. • Blocks may be nested • Variables may be declared anywhere within the block • A variable declared within a block may not have the same name as any identifier within an enclosing block.

  4. Java scope rules • Scope of a for loop index variable is the body of the loop • All variable definitions must occur within a class declaration—there are no global variables in Java!

  5. Differences between C++ and Java • Conditions in Java control statements must be boolean (C++ allows arithmetic and assignment expressions). • There are no standalone functions in Java, only methods that are defined within classes. • There are no global variables (variables defined outside of a class) in Java. • There are no pointers in Java; however, objects are accessed via reference variables

  6. Differences between C++ and Java • A .java file usually contains a single class definition, and the name of the class is the same as the name of the file. • For example, the class HelloWorld is defined in the file HelloWorld.java • In Java, all parameters are passed by value; there is no “&” operator for passing parameters by reference. • Operators cannot be overloaded in Java. • There are no templates in Java.

  7. Simple console output in Java • Use System.out.print and System.out.println: int x = 5; double y = 3.2e4; String name = "Bob"; System.out.println("x = " + x); System.out.println("y = " + y); System.out.println("name = " + name); • Output: x = 5 y = 32000.0 name = Bob

  8. Simple console input in Java • Not so simple, unfortunately… int n;double x;BufferedReader inData = new BufferedReader( new InputStreamReader(System.in));n = Integer.parseInt(inData.readLine());x = Double.parseDouble(inData.readLine()); • Fortunately, we will not be doing that much console io—the bulk of our applications will be GUI-based.

  9. Howdy.java import java.io.*; public class Howdy{ public static void main(String[] args) throws IOException { BufferedReader inData = new BufferedReader( new InputStreamReader(System.in)); System.out.print(“What is your name? ”); String name = inData.readLine(); System.out.println(“Howdy there, ” + name); } }

  10. Primitive Data Types • Java primitive types include: • byte • short • int • long • float • double • char • boolean

  11. Java classes • All Java classes are descendants of the Object class. • All classes inherit certain methods from Object. • Variables of primitive types are not objects. • There are hundreds of Java classes available to the programmer.

  12. Java Strings • Strings are sequences of characters, such as “hello” • Java does not have a built in string type, but the standard Java library has a class called String • String declarations:String s; // s is initially null String greeting = "Howdy!";

  13. String concatenation • + is the concatenation operator: String s1 = "Jim "; String s2 = "Bob"; String name = s1 + s2; String clone = name + 2;

  14. substring() and length() String s = "abcdefgh"; String sub = s.substring(3,7); // sub is "defg" String sub2 = s.substring(3); // sub2 is "defgh" int len = s.length(); // len is 8

  15. Strings are immutable • Objects of the String class are immutable, which means you cannot change the individual characters in a String. • To change a String, use assignment to make the object point to a different String: String s = "Mike"; s = s.substring(0,2) + "lk"; // s is now "Milk"

  16. Testing Strings for equality • The equals method tests for equality: String s1 = "Hello", s2 = "hello"; s1.equals(s2) returns falses1.equals("Hello") is true • The equalsIgnoreCase method returns true if 2 Strings are identical except for upper/lower case: s1.equalsIgnoreCase(s2) returns true • Do not use == to compare strings—you are comparing string locations when you do!

  17. Useful String methods • char charAt(int index) • returns the character at the specified index • int compareTo(String s) • returns • negative value if the String is alphabetically less than s, • positive value if the String is alphabetically greater than s • 0 if the strings are equal • boolean equals(String s) • returns true if the String equals s

  18. Useful String methods • boolean equalsIgnoreCase(String s) • returns true if the String equals s, except for upper/lower case differences • int indexOf(String s) int indexOf(String s, int fromIndex) • return the start of the first substring equal to s, starting at index 0 or at fromIndex • if s is not contained in String, return –1.

  19. Useful String methods • int length() • returns the length of the string • String substring(int beginNdx)String substring(int beginNdx, int endNdx) • return a new string consisting of all characters from beginNdx to the end of the string or until endNdx (exclusive)

  20. Useful String methods • String toLowerCase() • returns a new string with all characters converted to lower case • String toUpperCase() • returns a new string with all characters converted to upper case • String trim() • returns a new string by eliminating leading and trailing blanks from original string

  21. Java arrays • There are 2 equivalent notations for defining an array: • int a[]; • int[] a; • Note that space for the array is not yet allocated • In Java, steps for creating an array are: • Define the array • Allocate storage • Initialize elements

  22. Allocating storage for an array • Allocate a 100-element array: • a = new int[100]; • You can specify initial values like this: • a = new int[]{1,2,3,4,5}; • You can declare and initialize all in a single step: • int a[] = {1,2,3,4,5};

  23. Be careful! • String[] names = new String[4]; • At this point, names contains 4 elements, all of which have the value null. • The elements of names must be initialized before they can be used. For example: names[0] = “bob”; • This situation arises whenever you have an array of objects. Remember to • Allocate storage for the array, and • Initialize the elements

  24. Array operations • The member variable length contains the length of the array: for(int i=0; i < a.length; i++){ System.out.println(a[i]); }

  25. Array operations • Array assignment is permitted: int a[] = {1,2,3,4}; int b[]; b = a; for(int i = 0; i < b.length; i++) { System.out.println(b[i]); }

  26. Arrays of objects • When creating arrays of objects, keep in mind that you must create the individual objects before accessing each one. • The following example illustrates the process of using arrays of objects. • In the example we use a class named MyClass (defined on the next slide)

  27. MyClass public class MyClass { static int count=0; private int data; public MyClass() { count++; data = count; } public String toString() { return “” + data; }}

  28. An array of MyClass objects // declare an array: MyClass arr[] = new MyClass[5]; // Now the array holds references to // MyClass objects, not objects itself. // The following code produces a // runtime error: System.out.println(arr[0]); // arr[0] is null!

  29. An array of MyClass objects • // To fix this error, we create objects: • MyClass arr[] = new MyClass[] { new MyClass(), new MyClass(), new MyClass(), new MyClass() • }; • // alternately, we could initialize the • // array with a for loop.

  30. Multidimensional arrays int[][] arr = { {1, 2, 3}, {4, 5, 6} }; for(int i = 0; i < arr.length; i++) { for(int j = 0; j < arr[i].length; j++) { System.out.println(arr[i][j]); } }

  31. Multidimensional arrays MyClass arr[][]= new MyClass[2][5]; for (int i = 0; i < 2; i++){ for (int j = 0; j < 5; j++) { arr[i][j] = new MyClass(); } } // create the objects before you use the // array!

  32. Ragged arrays int[][] arr = { {1,2}, null, {3,4,5}, {6} }; for (int i = 0; i < arr.length; i++){ if (arr[i] != null) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } } System.out.println();}

  33. Methods can return arrays public static String[] getNames(int n) throws IOException{ BufferedReader inData = new BufferedReader( new InputStreamReader(System.in)); String[] names = new String[n]; for (int i = 0; i < n; i++) names[i] = inData.readLine(); return names;}

  34. End of the Tour

More Related