Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
From C++ to Java
A whirlwind tour of Java
for
C++ programmers
Java statements
Identical to those of C++
Assignment
Decision
Repetition
if else
switch
while
for
do while
break, continue
return
catch, throw
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.
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!
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
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.
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
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.
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);
}
}
Primitive Data Types
Java primitive types include:
byte
short
int
long
float
double
char
boolean
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.
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!";
String concatenation
+ is the concatenation operator:
String
String
String
String
s1 = "Jim ";
s2 = "Bob";
name = s1 + s2;
clone = name + 2;
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
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"
Testing Strings for equality
The equals method tests for equality:
String s1 = "Hello",
s2 = "hello";
s1.equals(s2) returns false
s1.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!
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
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.
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)
Useful String methods
String toLowerCase()
String toUpperCase()
returns a new string with all characters converted
to lower case
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
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
Allocating storage for an array
Allocate a 100-element array:
You can specify initial values like this:
a = new int[100];
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};
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
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]);
}
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]);
}
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)
MyClass
public class MyClass
{
static int count=0;
private int data;
public MyClass()
{
count++;
data = count;
}
public String toString()
{
return “” + data;
}
}
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!
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.
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]);
}
}
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!
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();
}
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;
}
End of the Tour