34
From C++ to Java A whirlwind tour of Java for C++ programmers

From C++ to Java A whirlwind tour of Java for C++ programmers

Embed Size (px)

Citation preview

Page 1: From C++ to Java A whirlwind tour of Java for C++ programmers

From C++ to Java

A whirlwind tour of Java for

C++ programmers

Page 2: 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

Page 3: From C++ to Java A whirlwind tour of Java for C++ programmers

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.

Page 4: From C++ to Java A whirlwind tour of Java for C++ programmers

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!

Page 5: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 6: From C++ to Java A whirlwind tour of Java for C++ programmers

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.

Page 7: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 8: From C++ to Java A whirlwind tour of Java for C++ programmers

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.

Page 9: From C++ to Java A whirlwind tour of Java for C++ programmers

Howdy.javaimport 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); }

}

Page 10: From C++ to Java A whirlwind tour of Java for C++ programmers

Primitive Data Types Java primitive types include:

byte short int long float double char boolean

Page 11: From C++ to Java A whirlwind tour of Java for C++ programmers

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.

Page 12: From C++ to Java A whirlwind tour of Java for C++ programmers

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!";

Page 13: From C++ to Java A whirlwind tour of Java for C++ programmers

String concatenation + is the concatenation operator:

String s1 = "Jim ";

String s2 = "Bob";

String name = s1 + s2;

String clone = name + 2;

Page 14: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 15: From C++ to Java A whirlwind tour of Java for C++ programmers

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"

Page 16: From C++ to Java A whirlwind tour of Java for C++ programmers

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!

Page 17: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 18: From C++ to Java A whirlwind tour of Java for C++ programmers

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.

Page 19: From C++ to Java A whirlwind tour of Java for C++ programmers

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)

Page 20: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 21: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 22: From C++ to Java A whirlwind tour of Java for C++ programmers

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};

Page 23: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 24: From C++ to Java A whirlwind tour of Java for C++ programmers

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]); }

Page 25: From C++ to Java A whirlwind tour of Java for C++ programmers

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]); }

Page 26: From C++ to Java A whirlwind tour of Java for C++ programmers

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)

Page 27: From C++ to Java A whirlwind tour of Java for C++ programmers

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

Page 28: From C++ to Java A whirlwind tour of Java for C++ programmers

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!

Page 29: From C++ to Java A whirlwind tour of Java for C++ programmers

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.

Page 30: From C++ to Java A whirlwind tour of Java for C++ programmers

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]); } }

Page 31: From C++ to Java A whirlwind tour of Java for C++ programmers

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!

Page 32: From C++ to Java A whirlwind tour of Java for C++ programmers

Ragged arraysint[][] 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();}

Page 33: From C++ to Java A whirlwind tour of Java for C++ programmers

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;}

Page 34: From C++ to Java A whirlwind tour of Java for C++ programmers

End of the Tour