CS3101-3 Programming Language - JAVA: Fall 2004 Sept. 15th
CS3101-3 Programming Language - JAVA: Fall 2004 Sept. 15th
About class
Website:
http://www1.cs.columbia.edu/~kewang/cs3
101/index.htm
Meeting time and place:
Wed. 11am-1pm, 825 Mudd
Six weeks only, ends at Oct. 20th
Homework
5 or 6 homework
One homework per week
All programming
Goes out every Wed night
Due next Tuesday 11:59:59pm
Submission and HW return eletronically
Grade percentage to be determined
Final?
Late policy
You have one 24-hour extension
Can be used only once
Otherwise, no late homework will be
accepted
Academia Integrity
The work you submit should be
implemented BY YOURSELF
Can get help from me, or friends
Must acknowledge all help given.
Topics to cover
Basic Java, Objects, Classes, Inheritance,
Interfaces, Exceptions, I/O
Applets, GUI Programming, Event
handling
Multithreading, Basic Networking
Packages, Libraries
Some advanced topics, like collections,
database, XML, etc. (If possible)
Textbook
No required textbook
Most of the information you need can be found online,
especially at http://java.sun.com
Tutorials and code camp:
http://java.sun.com/learning/tutorial/index.html
Java API specification:
http://java.sun.com/j2se/1.4.2/docs/api/index.html
Important one! Should visit often when coding
Reference books
Core Java 2, Volume I: Fundamentals
Core Java 2, Volume II: Advanced
Features
Thinking in Java, 3rd Edition
Electronic version available:
http://64.78.49.204/
PRACTICE
Intro to Java
Java programming language
The one we use to write our program
Compiled to byte code of JVM
Java is portable,
As long as there is a JVM compiled for
that particular processor and OS
Typical program, like C or C++, is
compiled for a particular processor
architecture and OS.
Write once, run everywhere!
Suns motto for Java
Very safe
No pointer
Automatic garbage collection
Check array access bound
Java
Java is an object-oriented language, with a
syntax similar to C
Structured around objects and methods
A method is an action or something you do with
the object
Hello World!
File name: Hello.java
/* Our first Java program Hello.java */
Command line
arguments
public class Hello {
//main()
public static void main ( String[] args ) {
System.out.println( "hello world!" );
}
}
Standard output, print with new line
About class
Fundamental unit of Java program
All java programs are classes
Each class define a unique kind of object
( a new data type)
Each class defines a set of fields, methods
or other classes
public: modifier. This class is publicly
available and anyone can use it.
Things to notice
Java is case sensitive
whitespace doesnt matter for compilation
File name must be the same as one of the
class names, including capitalization!
At most one public class per file
If there is one public class in the file, the
filename must be the same as it
Generally one class per file
What is an object?
Object is a thing
An object has state, behavior and identity
Internal variable: store state
Method: produce behavior
Unique address in memory: identity
What is class?
Class introduces a new data type
A class describes a set of objects that
have identical characteristics (data
elements) and behaviors (methods).
Existing classes provided by JRE
User defined classes
//declaration
sal.name=Salvatore J. Stolfo;
ke.printInfo();
Sal.printInfo(); // error here??
Class Person
Name: Ke Wang
ke
height: 0
weight: 0
sal
height: 0
weight: 0
x.printInfo();
This gives the same output as previous code !
height: 0
weight: 0
x
Name: Salvatore J. Stolfo
sal
height: 0
weight: 0
references
objects
Reference
We call x, as well as ke and sal, reference to
the object
Handles to access an object
Reference itself is not accessible/manipulable
Different from C/C++, cannot increment/decrement it
Implemented as pointer+
Java runtime is watching all assignment to references
Why? garbage collection (later)
Reference
Person ke;
ke = new Person();
ke.name=Ke Wang;
More on reference
Have distinguished value null, meaning
pointing to nothing
if( x==null) { }
ke.setWeight(-10);
ke.weight = -20;
Class Person
class Hello{
public static void main ( String[] args ) {
Person ke = new Person();
ke.weight = -20;
}
}
>javac Hello.java
Hello.java:5: weight has private access in Person
ke.weight = -20;
^
1 error
Access functions
Generally make fields private and provide
public getField() and setField() access
functions
O-O term for this is Encapsulation
C# does this by default
Primitive types
Primitive type
Size
Minimum
Maximum
Wrapper type
boolean
1-bit
Boolean
char
16-bit
Unicode 0
Unicode 216- 1
Character
byte
8-bit
-128
+127
Byte
short
16-bit
-215
+215-1
Short
int
32-bit
-231
+231-1
Integer
long
64-bit
-263
+263-1
Long
float
32-bit
IEEE754
IEEE754
Float
double
64-bit
IEEE754
IEEE754
Double
Primitive types
All numerical types are signed!
No unsigned keyword in Java
Primitive type
Default
boolean
false
char
\u0000 (null)
byte
(byte)0
short
(short)0
int
long
0L
float
0.0f
double
0.0d
Example
class Hello{
public static void main ( String[] args ) {
int x;
System.out.println(x);
}
}
>javac Hello.java
Hello.java:5: variable x might not have been initialized
System.out.println(x);
^
1 error
Arrays in Java
An ordered collection of something, addressed
by integer index
Something can be primitive values, objects, or even
other arrays. But all the values in an array must be of
the same type.
Only int or char as index
long values not allowed as array index
0 based
Value indexes for array a with length 10
a[0] a[9];
a.length==10
Note: length is an attribute, not method
Creation
int[] arr = new int[1024];
int [][] arr = { {1,2,3}, {4,5,6} };
Person[] persons = new Person[50];
Guaranteed to be initialized
Array of primitive type will be initialized to their
default value
Zeroes the memory for the array
Arrays in Java:
second kind of reference types in Java
int[] arr = new int [5];
arr
arr
More on reference
Java doesnt support & address of , or *, ->
dereference operators.
reference cannot be converted to or from integer,
cannot be incremented or decremented.
When you assign an object or array to a variable,
you are actually setting the variable to hold a
reference to that object or array.
Similarly, you are just passing a reference when
you pass object or array to a method
copy
Primitive types get copied directly by =
int x= 10; int y=x;
ke
Name: Ke Wang
height: 0
weight: 0
Compare equality
Primitive use ==, compare their value directly
int x = 10; int y=10;
if(x==y) { // true !
Scoping
Scope determines both the visibility and lifetime
of the names defined within the scope
Scope is determined by the placement of {},
which is called block.
{
int x = 10;
//only x available
{
int y = 20;
//both x and y available
}
//only x available, y out of scope!
}
Scoping
Notice, you cannot do the following,
although its legal in C/C++.
{
int x = 10;
{
int x = 20;
}
}
Compile error
Hello.java:6: x is already defined in
main(java.lang.String[])
int x =20;
^
1 error
Scope of objects
When you create an object using new, the
object hangs around past the end of the
scope, although the reference vanishes.
{
String s = new String("abc");
}
Garbage collector
In C++, you have to make sure that you
destroy the objects when you are done
with them.
Otherwise, memory leak.
Importing library
If you need any routines that defined by
java package
import java.util.*;
import java.io.*;
Static keyword
Want to have only one piece of storage for a
data, regardless how many objects are created,
or even no objects created
Need a method that isnt associated with any
particular object of this class
static keyword apply to both fields and methods
Can be called directly by class name
Example: java.lang.Math
main()
class Hello{
int num;
public static void main(String[] args) {
num = 10;
}
}
>javac Hello.java
Hello.java:4: non-static variable num cannot be referenced
from a static context
num = 10;
^
1 error
Method overloading
As long as the methods have different parameter lists
Output
System.out.println();
System.err.println();
Err corresponds to Unix stderr
System.[out|err].print();
Same as println(), but no terminating newline
BufferedReader(InputStreamReader isr)
Allows us to read in a complete line and return it as a
String
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader(filename));
String line = in.readLine();
Basic exception
readLine() throws IOException
Required to enclose within try/catch block
More on exception later
Integer.parseInt()
Static method
Can take the String returned by readLine()
and spit out an int
Throws NumberFormatException if String
cannot be interpreted as an integer
Question?