Title: Getting Started with Java Programming
1Getting Started with Java Programming
CSC3170
2Outline
- Basic Object-Oriented Programming Concepts (OO
Concept) - Java Basics (for C programmers)
- Compile and Run
- Useful Reference
3Basic Object-Oriented Programming Concepts
4Definition
- Object-oriented programming uses objects and
their interactions to design computer program - Class
- To define an object, specifying the objects
- characteristics, attributes
- methods, operations
- E.g. The Student class specifies that a student
object - has attributes student ID, name, and address
- has an operation to change address
- Object
- A pattern of a class
- E.g. The Alice object is an object for the
Student class. It is a particular student. There
can be many objects for the Student class, such
as Alice, Bob, Charlie, , etc
5Terms in OO Concept
6What is an Object?
- Real-world Object
- States
- Behaviors (do things)
- Software Object
- Instance Variables
- Methods
7What is an Object?
- More about Methods
- A method in OO
- alice.changeAddress(Shatin)
- A function in C (imperative) language
- changeAddress(alice, Shatin)
- Accept parameters
- Return a value
- Related data functions ? Object
8What is a Message?
- Objects communicate by sending messages
- A method is an interface to accept messages
- alice.changeAddress(Shatin)
Shatin
true
9What is a Class?
- A class is a template / blueprint of an object
- There are 100 students
- 100 instances of the Student class
10What is a Class?
instance ofrelationship
Note that each instance encapsulates its own copy
of instance variables
11What is a Class?
- Where to store the number of students?
- Class variable
- All instances share a single copy
- Class can also have class methods
- Cannot access instance variables and instance
methods - ? Student.name
- ? Student.changeAddress()
- ? Student.NoOfStudents
12Why Object-Oriented Programming?
- Inheritance
- Each subclass inherits all variables and methods
of its superclass - Abstraction
- Simply complex reality
- Encapsulation
- The values of variables of an object are private
- Polymorphism
- Allows the objects of different types respond to
the method call of the same name
13Java Basics
14Hello World!
- //HelloWorld.java
- import java.io.
- class HelloWorld / print Hello World! /
- public static void main(String args)
- System.out.println("Hello World!")
-
//helloworld.c include int main(int
argc, char argv) / print Hello World!
/ printf("Hello World!\n") return 0
15Dissecting Hello World!
- //HelloWorld.java
- import java.io.
- class HelloWorld / print Hello World! /
- public static void main(String args)
- System.out.println("Hello World!")
-
- //-style one-line comment
- include ? import java.io.
- a huge number of (standard) packages ready for
use - Define a new class called HelloWorld
- C-style / / comment
- Define the main method in class HelloWorld
16Dissecting Hello World!
- //import java.io. //not required for console
output - class HelloWorld / print Hello World! /
- public static void main(String args)
- System.out.println("Hello World!")
-
visibility
return type
parameter list
modifiers
method name
- Visibility modifier
- public, protected, private
- static modifier
- static ? class variable/method
- Return type
- void, int, double, char, boolean, ,
, - Method name
- Parameter list
- Primitives pass-by-value
- Reference Types pass-by-reference
17Dissecting Hello World!
- //import java.io. //not required for console
output - class HelloWorld / print Hello World! /
- public static void main(String args)
- System.out.println("Hello
World!") -
To invoke the Java Program, we type java
HelloWorld Peter Paul Mary Then, args0
Peter args1 Paul args2
Mary args.length 3
include int main(int argc, char
argv) / print Hello World! /
puts("Hello World!") / OR printf("Hello
World!\n") / return 0
This is different from C, if we type hello_world
Peter Paul Mary Then, argv1 Peter argv2
Paul argv3 Mary argc 4
18Java is similar to C!
- Data Types
- short, int, long, float, double
- Operators
- - / --
- Control Flows
- Selection
if () else
switch () case
break case
break default
19Java is similar to C!
- Control Flows
- Iterations
- while ()
-
-
- do
-
- while ()
- for (
) -
20Java is NOT C!
- External Dependencies
- include ? import package.
- Data Types
- char ? byte (an 8-bit integer)
- char ? char (a character, e.g. c)
- int ? boolean (e.g. true / false)
- int ? int (a 32-bit integer)
- char string8 Java / an array /
- ? String string Java //an object
- int array8
- ? int array new int8//an object
21Java is NOT C!
- Operators
- new
- Object obj new Object()
- Student student new Student()
- instanceof
- (student instanceof Student) true
- (obj instanceof Student) false
- (anything instanceof Object) true
- Constants
- define LENGTH 8
- ? public static final int LENGTH8
22Your first Java program
- Model your application with objects
- Design the states and behaviors of each object
- Define a class for each type of object
- Implement the states (with instance variables)
and behaviors (with methods) - Write the main method to create objects and
kick-start the object interactions
23Your first Java program
- class Student
- public static int NoOfStudents 0
- public String studentID
- public String name
- public String address
- //constructor (create an object / instance)
- public Student(String studentID, String name,
String address) - NoOfStudents
- this.studentID studentID
- this.name name
- this.address address
-
- public void changeAddress(String address)
- this.address address
-
24Your first Java program
- class Student
- public static int NoOfStudents 0
- public String studentID
- public String name
- public String address
- //constructor
- public Student(String studentID, String name,
String address) - NoOfStudents
- this.studentID studentID
- this.name name
- this.address address
-
- public void changeAddress(String address)
- this.address address
-
This is perfectly legal, but by making everything
public, everyone can change your states Instead,
we can write, private String studentID public
String getStudentID() return
studentID Now, no one except yourself can
change your own states. This sounds silly, but it
will avoid many subtle bugs that may otherwise be
difficult to track.
25Your first Java program
Even if you allow others to change your states,
you may want to perform some other operations
before granting write access, for
instance, private String address public boolean
changeAddress(String address, String password)
boolean authorized false if
(password.equals("CSC3170")) authorized
true this.address address return
authorized
- class Student
- public static int NoOfStudents 0
- public String studentID
- public String name
- public String address
- //constructor
- public Student(String studentID, String name,
String address) - NoOfStudents
- this.studentID studentID
- this.name name
- this.address address
-
- public void changeAddress(String address)
- this.address address
-
26Putting it Altogether
- //Defining the class Student
- class Student
- //class variable
- private static int NoOfStudents 0
- //instance variables
- private String studentID
- private String name
- private String address
- //constructor
- public Student(String studentID, String name,
String address) - NoOfStudents
- this.studentID studentID
- this.name name
- this.address address
-
- //class method
- public static int getNoOfStudents()
- //instance methods
- public boolean changeAddress(String address,
String password) - boolean authorized false
- if (password.equals("CSC3170"))
- authorized true
- this.address address
-
- return authorized
-
- public String getStudentID()
- return studentID
-
- public String getName()
- return name
-
27The final step
- ? Model your application with objects
- ? Design the states and behaviors of each object
- ? Define a class for each type of object
- ? Implement the states (with instance variables)
and behaviors (with methods) - Write the main method to create objects
kick-start the object interactions
28The RollCall Class
- class RollCall
- public static void main(String args)
- Student alice, bob, charlie
- alice new Student("01234567", "Alice",
"Mongkok") - bob new Student("02345678", "Bob",
"Central") - charlie new Student("03456789", "Charlie",
"Tuen Mun") - System.out.println(alice.getStudentID()
"\t" alice.getName() "\t"
alice.getAddress()) - System.out.println(bob.getStudentID() "\t"
bob.getName() "\t"
bob.getAddress()) - System.out.println(charlie.getStudentID()
"\t" charlie.getName() "\t"
charlie.getAddress()) - charlie.changeAddress("Shatin", "CSC3170")
- System.out.println()
- System.out.println(charlie.getStudentID()
"\t" charlie.getName() "\t"
charlie.getAddress()) -
29Printing Arbitrary Objects
- class RollCall
- public static void main(String args)
- Student alice, bob, charlie
- alice new Student("01234567", "Raymond",
Mongkok") - bob new Student("02345678", "Fianny",
Central") - charlie new Student("03456789", "Leo Lau",
Tuen Mun") - System.out.println(alice.getStudentID()
"\t" alice.getName() "\t"
alice.getAddress()) - System.out.println(bob.getStudentID() "\t"
bob.getName() "\t" bob.getAddress()) - System.out.println(charlie.getStudentID()
"\t" charlie.getName() "\t"
charlie.getAddress()) - charlie.changeAddress(Shatin", "CSC3170")
- System.out.println()
- System.out.println(charlie.getStudentID()
"\t" charlie.getName() "\t"
charlie.getAddress()) -
- Its so troublesome to print an Object!
- Wouldnt it be nice if we can say
- System.out.println(alice)
- Yes, you can! Just add the following to Student!
- public String toString()
- return studentID \t name \t
address
30Java Standard I/O
- Standard Output
- stdout ? System.out
- puts(str) / printf(s\n, str)?
System.out.println(str) - printf(s, str) ? System.out.print(str)
- Standard Input
- stdin ? System.in
- gets(str) ?
- import java.io.
- BufferedReader in new BufferedReader(new
InputStreamReader(System.in)) - str in.readLine()
- char c getchar() ? char c in.read()
31More Java Standard I/O
- Standard Output
- System.out.println() can accept
- boolean, char, char, double, float, int, long,
Object, and String - Standard Input
- To read numbers
- Use readLine() to read String
- Convert to appropriate type using
- Integer.parseInt(), Double.parseDouble(),
- Please visit http//java.sun.com/javase/6/docs/api
/ to see how to use such methods
32The Echo Class
- import java.io.
- class Echo
- public static void main(String args)
- Echo echo
- echo new Echo()
- echo.start()
- System.out.println("Good Bye!")
-
- public Echo()
- System.out.println("Hello!")
-
- public void start()
- BufferedReader in new BufferedReader(new
InputStreamReader(System.in)) - String str
- try
- System.out.print("Enter string (or a blank
line to terminate) ") - str in.readLine()
- while (!str.trim().equals(""))
- System.out.println("You typed " str)
- System.out.print("Enter string (or a
blank line to terminate) ") - str in.readLine()
-
- catch (IOException e)
- System.err.println("Caught IOException "
e.getMessage()) -
-
33Exception Handling
- Exception provides a smart way to handle
exceptional event - An appropriate exception handler takes over
when exception is thrown - try
-
- catch ( )
-
- finally
- / this will be executed after normal execution
or execution of an exception handler / -
-
- You can also throw or re-throw an exception if
you dont know how to handle
- try
- System.out.print("Enter string (or a blank
line to terminate) ") - str in.readLine()
- while (!str.trim().equals(""))
- System.out.println("You typed " str)
- System.out.print("Enter string (or a
blank line to terminate) ") - str in.readLine()
-
- catch (IOException e)
- System.err.println(("Caught IOException "
e.getMessage()) -
-
Exceptional Event Stream is not readable
The exception handler for I/O Exception produces
an error message
34The Adder Class
- import java.io.
- class Adder
- public static void main(String args)
- Adder adder new Adder()
- adder.add()
-
- public Adder()
- System.out.println("Input an integer, or
press Enter to terminate!") -
- public void add()
- BufferedReader in new BufferedReader(new
InputStreamReader(System.in)) - String str
- int sum 0
- try
- str in.readLine()
- while (!str.trim().equals(""))
- sum Integer.parseInt(str)
- System.out.print(sum " ")
- str in.readLine()
-
- catch (IOException e)
- //useful for debugging
- e.printStackTrace()
- catch (NumberFormatException e)
- System.err.println("Caught
NumberFormatException " e.getMessage()) - finally
- System.out.println("This will be printed in
any case!") -
-
35Compile and Run
36Set Path
- Connect to your Unix account
- Add the following 2 lines to the file /.cshrc
- setenv JAVA_HOME /usr/local/jdk1.6.0
- setenv PATH JAVA_HOME/binPATH
- Relogin OR type source .cshrc for the above to
take effect - You only need to do the above steps once only
- If you have not set path, you have to type the
full path in the shell to compile and run your
java programs - /usr/local/jdk1.6.0/bin/javac
- /usr/local/jdk1.6.0/bin/java
37Compile and Run
- Java Compiler javac
- Compile your source file(s)
- Usage javac
- E.g. javac System.java, javac .java
- Java Interpreter java
- Run your Java program
- Usage java
- E.g. java System
- No .java / .class at the end
38Useful Reference
39java.sun.com
- The Java Tutorial
- http//java.sun.com/docs/books/tutorial/
- Getting started
- http//java.sun.com/docs/books/tutorial/getStarted
/ - An introduction to Java technology and lessons on
installing Java development software and using it
to create a simple program - Learning the Java Language
- http//java.sun.com/docs/books/tutorial/java/
- Describes the essential concepts and features of
the Java Programming Language
40java.sun.com
- Essential Java Classes
- http//java.sun.com/docs/books/tutorial/essential/
- Lessons on exceptions, basic input/output,
concurrency, regular expressions, and the
platform environment. - JDBC Database Access
- http//java.sun.com/docs/books/tutorial/jdbc/
- Introduces an API for connectivity between the
Java applications and a wide range of databases
and a data sources.
41java.sun.com
- JavaTM Platform, Standard Edition 6 API
Specification - http//java.sun.com/javase/6/docs/api/
- To see how to call the API functions
- Java SE Reference
- http//java.sun.com/javase/reference/index.jsp
42www.cse.cuhk.edu.hk
- Introduction to Computing Using Java (CSC1130)
- http//www.cse.cuhk.edu.hk/csc1130/
- CSE Summer Preparatory Course
- http//www.cse.cuhk.edu.hk/csesc/
43WWW
- Java Platform Performance
- http//java.sun.com/docs/books/performance/
- For experienced Java programmers
- Gotchas Java Glossary
- http//mindprod.com/jgloss/gotchas.html
- Avoid common Java pitfalls
- Free Electronic Book Thinking in Java, 3rd
Edition - http//www.mindview.net/Books/TIJ/
- How to write Doc Comments
- http//java.sun.com/j2se/javadoc/writingdoccomment
s/
44End