Getting Started with Java Programming - PowerPoint PPT Presentation

1 / 44
About This Presentation
Title:

Getting Started with Java Programming

Description:

args[0] = 'Peter' args[1] = 'Paul' args[2] = 'Mary' args.length = 3 ... Write the main method to create objects and kick-start the object interactions ... – PowerPoint PPT presentation

Number of Views:111
Avg rating:3.0/5.0
Slides: 45
Provided by: cseCu
Category:

less

Transcript and Presenter's Notes

Title: Getting Started with Java Programming


1
Getting Started with Java Programming
CSC3170
2
Outline
  • Basic Object-Oriented Programming Concepts (OO
    Concept)
  • Java Basics (for C programmers)
  • Compile and Run
  • Useful Reference

3
Basic Object-Oriented Programming Concepts
  • (OO Concept)

4
Definition
  • 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

5
Terms in OO Concept
  • Object
  • Message
  • Class

6
What is an Object?
  • Real-world Object
  • States
  • Behaviors (do things)
  • Software Object
  • Instance Variables
  • Methods

7
What 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

8
What is a Message?
  • Objects communicate by sending messages
  • A method is an interface to accept messages
  • alice.changeAddress(Shatin)

Shatin
true
9
What is a Class?
  • A class is a template / blueprint of an object
  • There are 100 students
  • 100 instances of the Student class

10
What is a Class?
instance ofrelationship
Note that each instance encapsulates its own copy
of instance variables
11
What 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

12
Why 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

13
Java Basics
  • (for C programmers)

14
Hello 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
15
Dissecting 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

16
Dissecting 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

17
Dissecting 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
18
Java is similar to C!
  • Data Types
  • short, int, long, float, double
  • Operators
  • - / --
  • Control Flows
  • Selection

if () else

switch () case
break case
break default

19
Java is similar to C!
  • Control Flows
  • Iterations
  • while ()
  • do
  • while ()
  • for (
    )

20
Java 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

21
Java 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

22
Your 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

23
Your 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

24
Your 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.
25
Your 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

26
Putting 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

27
The 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

28
The 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())

29
Printing 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

30
Java 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()

31
More 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

32
The 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())

33
Exception 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
34
The 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!")

35
Compile and Run
36
Set 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

37
Compile 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

38
Useful Reference
39
java.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

40
java.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.

41
java.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

42
www.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/

43
WWW
  • 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/

44
End
Write a Comment
User Comments (0)
About PowerShow.com