Title: From C to Java
1From C to Java
- A whirlwind tour of Java
- for
- C programmers
2Java statements
- Identical to those of C
- Assignment
- Decision
- if else
- switch
- Repetition
- while
- for
- do while
- break, continue
- return
- catch, throw
3Java 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.
4Java scope rules
- Scope of a for loop index variable is the body of
the loop - All variable definitions must occur within a
class declarationthere are no global variables
in Java!
5Differences 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
6Differences 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.
7Simple 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
8Simple console input in Java
- Not so simple, unfortunately
- int ndouble xBufferedReader 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 iothe bulk of our applications will be
GUI-based.
9Howdy.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)
10Primitive Data Types
- Java primitive types include
- byte
- short
- int
- long
- float
- double
- char
- boolean
11Java 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.
12Java 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 declarationsString s // s is initially
null - String greeting "Howdy!"
13String concatenation
- is the concatenation operator
- String s1 "Jim "
- String s2 "Bob"
- String name s1 s2
- String clone name 2
14substring() 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
15Strings 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"
16Testing 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 stringsyou are
comparing string locations when you do!
17Useful 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
18Useful 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.
19Useful 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)
20Useful 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
21Java 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
22Allocating storage for an array
- Allocate a 100-element array
- a new int100
- You can specify initial values like this
- a new int1,2,3,4,5
- You can declare and initialize all in a single
step - int a 1,2,3,4,5
23Be careful!
- String names new String4
- 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 - names0 bob
- This situation arises whenever you have an array
of objects. Remember to - Allocate storage for the array, and
- Initialize the elements
24Array operations
- The member variable length contains the length of
the array - for(int i0 i lt a.length i)
System.out.println(ai)
25Array operations
- Array assignment is permitted
- int a 1,2,3,4
- int b
- b a
- for(int i 0 i lt b.length i)
System.out.println(bi)
26Arrays 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)
27MyClass
public class MyClass static int count0
private int data public MyClass()
count data count public
String toString() return data
28An array of MyClass objects
// declare an array MyClass arr new
MyClass5 // Now the array holds references
to // MyClass objects, not objects itself. //
The following code produces a // runtime error
System.out.println(arr0) // arr0 is null!
29An 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.
30Multidimensional arrays
int arr 1, 2, 3, 4, 5, 6 for(int
i 0 i lt arr.length i) for(int j 0
j lt arri.length j)
System.out.println(arrij)
31Multidimensional arrays
MyClass arr new MyClass25 for (int i
0 i lt 2 i) for (int j 0 j lt 5
j) arrij new MyClass()
// create the objects before you use
the // array!
32Ragged arrays
int arr 1,2, null, 3,4,5, 6 for
(int i 0 i lt arr.length i) if (arri
! null) for (int j 0 j lt
arri.length j)
System.out.print(arrij " ")
System.out.println()
33Methods can return arrays
public static String getNames(int n) throws
IOException BufferedReader inData
new BufferedReader( new InputStreamReader(Sy
stem.in)) String names new Stringn
for (int i 0 i lt n i) namesi
inData.readLine() return names
34End of the Tour