Title: Advanced Java Programming CSE 7345/5345/ NTU 531
1Advanced Java ProgrammingCSE 7345/5345/ NTU 531
Welcome Back!!!
2Chantale Laurent-Rice
Office Hours by appt 330pm-430pm SIC 353
Welcome Back!!!
trice75447_at_aol.com
claurent_at_engr.smu.edu
3Introduction
- Chapter 1
- Course Objectives
- Organization of the Book
4 Objectives
- Upon completing this chapter, you will understand
- Create, compile, and run Java programs
- Primitive data types
5Book Chapters
- Part I Fundamentals of Programming
- Chapter 1 Introduction to Java
- Chapter 2 Primitive Data Types and Operations
- Chapter 3 Control Statements
- Chapter 4 Methods
- Chapter 5 Arrays
6Book Chapters, cont.
- Part II Object-Oriented Programming
- Chapter 6 Objects and Classes
- Chapter 7 Strings
- Chapter 8 Class Inheritance and Interfaces
- Chapter 9 Object-Oriented Software Development
7Book Chapters, cont.
- Part III GUI Programming
- Chapter 10 Getting Started with GUI Programming
- Chapter 11 Creating User Interfaces
- Chapter 12 Applets and Advanced GUI
8Book Chapters, cont.
- Part IV Developing Comprehensive Projects
- Chapter 13 Exception Handling
- Chapter 14 Internationalization
- Chapter 15 Multithreading
- Chapter 16 Multimedia
- Chapter 17 Input and Output
- Chapter 18 Networking
- Chapter 19 Java Data Structures
9Chapter 1
- Objectives
- Get an overall perspective of what capabilities
and features are encompassed by Java and its
development kit. - Take a first look at Java syntax.
- Getting Input from Input Dialog Boxes
- Style and Documentation Guidelines
10What Is Java?
- History
- Characteristics of Java
11What is Java?
- An Object-Oriented Programming Language developed
at Sun Microsystems - A Virtual Machine (run-time environment) that can
be embedded in web browsers (e.g. Netscape
Navigator, Microsoft Internet Explorer and IBM
WebExplorer) and operating systems. - A set of standardized Class libraries (packages),
that support - Creating graphical user interfaces
- Communicating over networks
- Controlling multimedia data
12History
- James Gosling and Sun Microsystems
- Oak
- Java, May 20, 1995, Sun World
- HotJava
- The first Java-enabled Web browser
- JDK Evolutions
- J2SE, J2ME, and J2EE (not mentioned in the book)
13Characteristics of Java
- Java is simple
- Object-Oriented
- Distributed
- Interpreted
- Robust
- Secure
- Architecture-neutral
- Portable
- High-performance
- Multithreaded
- dynamic
14Java is Simple
- Java is not just a language for use with the
Internet. - It is a full featured Object-Oriented Programming
Language (OOPL). - Java is a bit easier than the popular OOP
language C. - Java uses automatic memory allocation and garbage
collection.
15What is Object-Oriented Programming?
- Think of OOP as a set of implementation
techniques that - Can be done in any programming language
- Are very difficult to do in most programming
languages - OOP provides great flexibility, modularity, and
reusability.
16Java is Distributed
- Distributed computing involves several computers
working together on a network. - Javas concurrency features make is unique for
developing many interactive and networked
applications.
17Java is Interpreted
- Java Virtual Machine
- Java is compiled to byte-codes whose target
architecture is the Java Virtual machine (JVM). - The virtual machine is embeddable within other
environments, e.g. web browser and operating
systems. - Utilize a byte-code verifier when reading in
byte-codes. The class loader is employed for
classes loaded over the network (enhances
security)
18Java Virtual Machine
Environment
Java Source code .java
Java byte-code .class
java
Java VM
javac
19Java is Robust
- Robust means reliable.
- No programming language can ensure complete
reliability. - Java puts a lot of emphasis on early checking for
possible errors, because Java compilers can
detect many problems that would first show up at
execution time in other languages. - Java has a runtime exception-handling feature to
provide programming support for robustness.
20Java Is Architecture-Neutral
- Java is interpreted.
- JIT compiler
- Just-in-time compilers
- This provides
- Improved performance
- Better match to specific hardware
21JIT Compiler
- JIT- takes byte-codes and change it to machine
code.
J.I.T. Compiler
JVM Running Applet or Application
.class file
machine code
22JIT Compiler
- Because of the need for architecture
independence, performance tuning must be
performed on the client-side. - This client-side compilation is known as
Just-In-Time (JIT) compilation.
23Portable, Dynamic, Multithreaded, and Extensible
.class files
- Java runtime based on architecturally-neutral
byte-codes - (per class).
- Multithreading is a programs capability to
perform several - tasks simultaneously.
interpreted
Java Runtime
loaded classes (byte-codes)
call
Native .dll
Native .dll
24Advantages
- Byte-code is a compact machine language form. In
Java the target machine is the Java Virtual
Machine (VM). - These byte-codes are thus portable across
architecture boundaries. - Applets and Applications have class files
loaded on their behalf in order to execute.
25JDK Versions
- JDK 1.02 (1995)
- JDK 1.1 (1996)
- Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
- Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
- Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)
26JDK Editions
- Java Standard Edition (J2SE)
- J2SE can be used to develop client-side
standalone applications or applets. - Java Enterprise Edition (J2EE)
- J2EE can be used to develop server-side
applications such as Java servlets and Java
ServerPages. - Java Micro Edition (J2ME).
- J2ME can be used to develop applications for
mobile devices such as cell phones. - This book uses J2SE to introduce Java
programming.
27Java IDE Tools
- Forte by Sun MicroSystems
- Borland JBuilder
- Microsoft Visual J
- WebGain Café
- IBM Visual Age for Java
- IBM Eclipse
28Getting Started with Java Programming
- A Simple Java Application
- Compiling Programs
- Executing Applications
29Command Line
- Example 1.1
- //This application program prints Welcome
- //to Java!
- package chapter1
- public class Welcome
- public static void main(String args)
- System.out.println("Welcome to Java!")
-
Run
Source
30Creating and Compiling Programs
- On command line
- javac file.java
31Executing Applications
- On command line
- java classname
32Command line Example
- javac Welcome.java
- java Welcome
- output...
33Compiling and Running a Program
Where are the files stored in the directory?
34There are three forms of comments in Java.
- 1- int i 10 // i is used as a counter
- 2- The multiline comment
- / This is a comment /
- This form of comment may also extend over
several lines as shown here - /
- This is a longer comment
- that extends over
- five lines.
- /
35There are three forms of comments in Java.
- 3- This is the documentation comment.
- /
- This is a Java
- documentation
- comment
- /
- The advantage of documentation comments is that
tools can extract them from source files and
automatically generate documentation for your
programs. The JDK has a tool named javadoc that
performs this function.
36Package
- The second line in the program (package
chapter1) specifies a package name, chapter1,
for the class Welcome. - Forte compiles the source code in Welcome.java,
generates Welcome.class, and stores Welcome.class
in the chapter1 folder.
37Blocks
A pair of braces in a program forms a block that
groups components of a program.
38Block Styles
- Use end-of-line style for braces.
39main Method
- The main method provides the control of program
flow. The Java interpreter executes the
application by invoking the main method. -
- The main method looks like this
-
- public static void main(String args)
- // Statements
40Displaying Text in a Message Dialog Box
- you can use the showMessageDialog method in the
JOptionPane class. - JOptionPane is one of the many predefined
classes in the Java system, which can be reused.
Run
Source
41The showMessageDialog Method
- JOptionPane.showMessageDialog(null, "Welcome to
Java!", - "Example 1.2", JOptionPane.INFORMATION_MESSAGE))
42A simple Java Applet
- import java.awt.
- import java.awt.event.
- import java.applet.Applet
- import java.awt.Graphics
- /
- ltapplet code"FirstApplet" width200 height200gt
- lt/appletgt
- /
- public class FirstApplet extends Applet
-
- public void paint(Graphics g)
-
- g.drawString("This is my first applet!", 20,
100) -
-
- See word doc for output.
43Integral Literals
- Integral literals may be expressed in decimal,
octal, or hexadecimal. - The default is decimal.
- To indicate octal, prefix the literal with 0
(zero) - To indicate hexadecimal, prefix the literal with
0x or 0X - the hex digits may be upper-or lowercase.
44Integral Literals
- For example
- The value twenty-eight may be expressed the
following ways - 28
- 034
- 0x1c
- 0x1C
- 0X1c
- 0X1C
45Integral Literals
- By default, an integral literal is a 32-bit
value. - To indicate a long (64-bit) literal, append the
suffix L to the literal expression. - The suffix can be lowercase, but then it looks so
much like a one that makes it confusing.
46Literals
- Literals are explicit data values that appear in
your program. - A literal is a value specified in the program
source, as opposed to one determined at runtime.
Literals can represent primitive or string
variables, and may appear on the right side of
assignments or in method calls. You cannot assign
a value into a literal, so they cannot appear on
the left of an assignment. - For example
- int x 25
47Boolean Literals
- The only literals of boolean type are true and
false. - For example
-
- 1. boolean isBig true
-
- 2. boolean isLittle false
48char Literals
- A char literal can be expressed by enclosing the
desired character in single quotes, -
- For example
-
- char c ' w '
49Chapter 1 Topic Summary
- Java is many things
- A concurrent object-oriented programming language
- A virtual machine and Web-aware run-time
- A powerful and stable set of class libraries.
50Chapter 2Liang, Nutshell Objectives
- Introduce Programming with an Example
- Identifiers, Variables, and Constants
- Primitive Data Types
- byte, short, int, long, float, double, char,
boolean - Expressions
- Operators, Precedence, Associativity, Operand
Evaluation Order , --, , /, , , -, ,
/, , , , , , -, - Syntax Errors, Runtime Errors, and Logic Errors
51Java Reserved Words or Keywords
- abstract default if private this
- boolean do implements protected throw
- break double import public throws
- byte else instanceof return transient
- case extends int short try
- catch final interface static void
- char finally long strictfp volatile
- class float native super while
- const for new switch
- continue goto package synchronized
52Keyword and identifiers
- An identifier is a word used by a programmer to
name a variable, method, class, or label. - Keywords and reserved words may not be used as
identifiers. - An identifier must begin with a letter, a dollar
sign (4), or an underscore (_) subsequent
characters may be letter, dollar signs,
underscores, or digits.
53Examples
- foobar // legal
- BIGinterface // legal
- incomeAfterExpenses // legal
- 3_nodes5 // illegal
- !theCase // illegal
54Using Keyword
- Using a keyword as an identifier is a syntax
error - Keywords that are reserved, but not used, by Java
- const
- goto
55Reserved Words
- Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be
used for other purposes in the program. - For example, when the compiler sees the word
class, it understands that the word after class
is the name for the class.
56Java support eight different basic data type
- Type Description Keyword
- character 16-bit Unicode character data char
- boolean true/false values boolean
- byte 8-bit signed integer numbers byte
- short 16-bit signed integer numbers short
- integer 32-bit signed integer numbers int
- long 64-bit signed integer numbers long
- float 32-bit signed floating-point numbers float
- double 64-bit signed floating-point
numbers double
57Primitive Data Type
- Java's Primitive C Simple data type
- data type integral floating
- boolean char float
- char short long
- byte int long double
- short
long - int
enum - long
unsigned char - float
unsigned short - double
unsigned int - unsigned long
58Primitive Data Types and Operations
- Type Precision Default Value
- byte 8 bits 0
- short 16 bits 0
- int 32 bits 0
- long 64 bits 0
- char 16 bits \u0000
- float 32 bits 0.0f
- double 64 bits 0.0d
- boolean - false
- obj-ref - null
59The four signed data types are
-
- v byte
- v short
- v int
- v long
60Valid Control Character
- Valid control character are
- \b backspace
- \t horizontal tab
- \n linefeed
- \f formfeed
- \r carriage return
- \ double quote
- \ single quote
- \\ backslash
- dddd for Unicode - is 0000 to hex ffff
61Operator Precedence
- var, var--
- , - (Unary plus and minus), var,--var
- (type) Casting
- ! (Not)
- , /, (Multiplication, division, and modulus)
- , - (Binary addition and subtraction)
- lt, lt, gt, gt (Comparison or Relational)
- , ! (Equality)
- (Unconditional AND)
- (Exclusive OR)
- (Unconditional OR)
- (Conditional AND) Short-circuit AND
- (Conditional OR) Short-circuit OR
- , , -, , /, (Assignment operator)
62Bitwise Operators
- Java defines several bitwise operators which can
be applied to the integer types, - long, int, short, char, byte
- These operators act upon the individual bits of
their operands.
63Bitwise Operators
- Operator Name
- Bitwise unary NOT
- Bitwise AND
- Bitwise OR
- Bitwise exclusive OR
- gtgt Shift right
- gtgtgt Shift right zero fill
- ltlt Shift left
-
64Bitwise Operators
- Operator Name
-
- Bitwise AND assignment
- Bitwise OR assignment
- Bitwise exclusive OR assignment
- gtgt Shift right assignment
- gtgtgt Shift right zero fill assignment
- ltlt Shift left assignment
65Bitwise NOT ( )
- Also called the bitwise complement, the unary NOT
operator, , - Inverts all the bits of its operand.
- Example
- Number 74
- before bitwise NOT -gt 01001010
- after the NOT operator applied -gt 10110101
66Bitwise AND ( )
- Produces a 1 bit if both operands are also 1,
otherwise a zero is produced. - Example
- Number 74 29 -gt 8
- -gt 0 1 0 0 1 0 1 0
- -gt 0 0 0 1 1 1 0 1
- After -gt 0 0 0 0 1 000
67Bitwise OR ( )
- Combines bits such that if either of the bits in
the operands is a 1, then the resultant bit is a
1. A zero if both bits are zeros. - Example
- Number 74 29 -gt 95
- -gt 0 1 0 0 1 0 1 0
- -gt 0 0 0 1 1 1 0 1
- After -gt 0 1 0 1 1 1 1 1
68Bitwise XOR ( )
- Combines bits such that if exactly one operand is
1, then the result is 1. Otherwise, the result is
zero. - Example
- Number 74 29 -gt 87
- -gt 0 1 0 0 1 0 1 0
- -gt 0 0 0 1 1 1 0 1
- After -gt 0 1 0 1 0 1 1 1
69Left shift ( ltlt )Right shift ( gtgt )unsigned
right shift ( gtgtgt)
- Left shift (gtgt) shifts all of the bits in a value
to the left a specified number of times. - Right shift (gtgt) shifts all of the bits in a
value to the right a specified number of times. - Unsigned right shift (gtgtgt) automatically fills
the high-order bits with its previous contents
each time a shift occurs. This preserves the sign
of the value.
70Relational or Comparisons Operators
- Operator Name
- Equal to
- ! Not equal to
- gt Greater than
- lt Less than
- gt Greater than or equal to
- lt Less than or equal to
71Relational Operators
- The relational operators determine the
relationship that one operand has to the other - They determine equality and ordering.
- The result of these operations is a boolean
value.
72Boolean Logical Operators
- Operator Name
- Logical AND
- Logical OR
- Logical XOR (exclusive OR)
- Short-circuit OR
- Short-circuit AND
- ! Logical unary NOT (inverts)
73Boolean Logical Operators
- Operator Name
-
- AND assignment
- OR assignment
- XOR assignment
- Equal to
- ! Not equal to
- ? Ternary if-then-else
-
74Boolean Logical Operators
- The Boolean Logical operators operate only on
boolean operands. - All of the binary logical operators combine two
boolean values to form a resultant boolean value.
75The boolean Type and Operators
- boolean lightsOn true
- boolean lightsOn false
- boolean b (1 gt 2)
- (and) (1 lt x) (x lt 100)
- (or) (lightsOn) (isDayTime)
- ! (not) !(isStopped)
76Truth Table for Operator !
Truth Table for Operator ! Operand !Operand true
false false true
77Truth Table for Operator
Operand1Operand2Operand1 Operand2 false false f
alse false true false true false false true true t
rue
78Truth Table for Operator
Operand1 Operand2 Operand1 Operand2 false false
false false true true true false true true true t
rue
79Truth Table for Operator
Operand1 Operand2 Operand1 Operand2 false false
false false true true true false true true true fa
lse
80The and Operators
- conditional AND operator
- unconditional AND operator
- conditional OR operator
- unconditional OR operator
- exp1 exp2
- (1 lt x) (x lt 100)
- (1 lt x) (x lt 100)
81The and Operators
- If x is 1, what is x after this expression?
- (x gt 1) (x lt 10)
- If x is 1, what is x after this expression?
- (1 gt x) ( 1 gt x)
- How about (1 x) (10 gt x)?
- (1 x) (10 gt x)?
82Getting Input from Input Dialog Boxes
- String string JOptionPane.showInputDialog(
- null, Prompt Message, Dialog Title,
- JOptionPane.QUESTION_MESSAGE))
- where x is a string for the prompting message and
y is a string for the title of the input dialog
box.
83Convertting Strings to Doubles
- To convert a string into a double value, you can
use the static parseDouble method in the Double
class as follows -
- double doubleValue Double.parseDouble(doubleStrin
g) -
- where doubleString is a numeric string such as
123.45.
84Read / Work With (Course Links)
- Liang, Nutshell Chapter 3-4
- Life Cycle of Applets
- List Of Basic Tags
- Try It Editor
85Chapter 3 Control Statements
- Selection Statements
- Using if and if...else
- Nested if Statements
- Using switch Statements
- Conditional Operator
- Repetition Statements
- Looping while, do-while, and for
- Nested loops
- Using break and continue
86Selection Statements
- if Statements
- switch Statements
- Conditional Operators
87Caution
- Adding a semicolon at the end of an if clause is
a common mistake. - if (radius gt 0)
-
- area radiusradiusPI
- System.out.println(
- "The area for the circle of radius "
- radius " is " area)
-
- This mistake is hard to find, because it is not a
compilation error or a runtime error, it is a
logic error.
Wrong
88switch Statements
- switch (year)
- case 7 annualInterestRate 7.25
- break
- case 15 annualInterestRate 8.50
- break
- case 30 annualInterestRate 9.0
- break
- default System.out.println(
- "Wrong number of years, enter 7, 15, or 30")
89Repetitions
- while Loops
- do-while Loops
- for Loops
- break and continue
90Chapter 4 Methods
- Introducing Methods
- Benefits of methods, Declaring Methods, and
Calling Methods - Passing Parameters
- Pass by Value
- Overloading Methods
- Ambiguous Invocation
- Scope of Local Variables
- Method Abstraction
- The Math Class
91Introducing Methods
Method Structure
A method is a collection of statements that are
grouped together to perform an operation.
92Methods
- A method is essentially a set of program
statements. It forms the fundamental unit of
execution in Java. Each method exists as part of
a class. - During the execution of a program, methods may
invoke other methods in the same or a different
class. - No program code can exist outside a method, and
no method can exist outside a class.
93Using Methods
- For example
- public class TheMethod
-
- public static void main(String args)
-
- System.out.println(First method)
-
94All methods are passed by value.
- All methods are passed by value. This means that
copies of the arguments are provided to a method.
-
- Any changes to those copies are not visible
outside the method. - This situation changes when an array or object is
passed as an argument.
95call-by-value argument passing
- In this case the entire array or object is not
actually copied. - Instead, only a copy of the reference is
provided. - Therefore, any changes to the array or object are
visible outside the method. - However, the reference itself is passed by value.
96call-by-value argument passing
- Method a( ) accepts three arguments
- an int
- an int array
- an object reference
- The value of these arguments are displayed
before and after the method call.
97call-by-value argument passing
- The key points to note are
- The change to the first argument is not visible
to the main( ) method. - The changes to the array and object are visible
to the main( ) method.
98Example
- public class CallByValue
-
- public static void main(String args)
-
- // Initializes variables
- int i 5
- int j 1, 2, 3, 4,
- StringBuffer sb new StringBuffer("abcd")
-
- // Display variables
- display(i, j, sb)
-
- // call method
- a(i, j, sb)
-
- //Display variables again
- display(i, j, sb)
-
99Example (cont)
- public static void a(int i, int j,
StringBuffer sb) -
- i 7
- j0 11
- sb.append("fghi")
-
- public static void display(int i, int j,
StringBuffer sb) -
- System.out.println(i)
- for (int index 0 index lt j.length index)
- System.out.print(jindex " ")
- System.out.println(" ")
- System.out.println(sb)
-
-
-
100Methods that return Values.
- The return type for a method can be used in the
Java -
- The return type for a method can be any type used
in the Java programming language, which includes
the primitive (or scalar) types int, double,
char, and so on, as well as class type (including
class types you create).
101Methods that return values
- public class GettingARaise
-
- public static void main(String args)
-
- double mySalary 200.00
-
- System.out.println("Demonstrating some
raises") -
- predictRaise(mySalary)
- System.out.println("Demonstrating my salary "
mySalary) - predictRaise(400.00)
- predictRaiseGivenIncrease(600, 800)
-
-
102Methods that return values
- public static void predictRaise(double
moneyAmount) -
- double newAmount
- newAmount moneyAmount 1.10
- System.out.println("With raise salary is "
newAmount) -
- public static void predictRaiseGivenIncrease(doub
le moneyAmount, double percentRate) -
- double newAmount
- newAmount moneyAmount (1 percentRate)
- System.out.println("With raise predicted given
salary is " newAmount) -
-
103Read / Work With (Course Links)
- Liang, Nutshell Chapter 4-6
- Life Cycle of Applets
- List Of Basic Tags
- Try It Editor