Advanced_Java_Programming
Advanced_Java_Programming
Introduction to Java
● What Is Java?
● Getting Started With Java Programming
– Create, Compile and Running a Java
Application
2
Characteristics of Java
● Java is simple
● Java is object-oriented
● Java is distributed
● Java is interpreted
● Java is robust
● Java is secure
● Java is architecture-neutral
● Java is portable
● Java’s performance
● Java is multithreaded
● Java is dynamic
3
Getting Started with Java
Programming
● A Simple Java Application
● Compiling Programs
● Executing Applications
4
A Simple Application
Example 1.1
//This application program prints Welcome
//to Java!
package chapter1;
5
Anatomy of a Java Program
● Comments
● Reserved words
● Modifiers
● Statements
● Blocks
● Classes
● Methods
● The main method
● The exit method
6
Comments
11
Classes
The class is the essential Java
construct. A class is a template
or blueprint for objects.
12
Methods
●What is System.out.println? It is a
method: a collection of statements that
performs a sequence of operations to
display a message on the console.
● It can be used even without fully
understanding the details of how it works.
●It is used by invoking a statement with a
string argument. The string argument is
enclosed within parentheses. In this case,
the argument is "Welcome to Java!"
●You can call the same println method
with a different argument to print a 13
main Method
The main method provides the
control of program flow. The
Java interpreter executes the
application by invoking the main
method.
18
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
19
Numerical Data Types (p.33)
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
float 32 bits
double 64 bits
20
Assignment Statements
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
21
Declaring and Initializing
in One Step
● int x = 1;
● double d = 1.4;
● float f = 1.4;
Is this statement correct?
22
Constants
final datatype CONSTANTNAME = VALUE;
23
Operators
+, -, *, /, and %
26
Example Program 2 : Division
27
Download Java
● From www.java.sun.com/j2se
● Click on j2se 5.0
● See on your right (popular downloads) ..click on
j2se 5.0
● Click on download jdk 5.0 update 3
● Accept the agreement and continue
● Download the version as per your platform
● For example, for Windows click on Windows
offline installation – this will download the
required file .. This will take a lot of time ..
depending upon the speed of your line .. Once
downloaded ..run this file to install Java 28
Compiling and Running a Java
Program
● Java source code files (files with a .java
extension) are compiled into a format called
bytecode (files with a .class extension), which can
then be executed by a Java interpreter. Compiled
Java code can run on most computers because
Java interpreters and runtime environments,
known as Java Virtual Machines (VMs), exist for
most operating systems, including UNIX, the
MACintosh OS, and Windows. Bytecode can also
be converted directly into machine language
instructions by a just-in-time compiler (JIT).
29
For Example
● Create a file named say .. addition.java using some
editor say wordpad.
● From the command line type the following
– javac addition.java (java code compiled to a bytecode)
● A file called addition.class(bytecode) is created,
● Now type
java addition (bytecode being executed by java
interpreter)
And you will get the results
30
Number Literals
A literal is a constant value that
appears directly in the program. For
example, 34, 1,000,000, and 5.0 are
literals in the following
statements:
int i = 34;
long l = 1000000;
double d = 5.0;
31
Integer Literals
An integer literal can be assigned to
an integer variable as long as it can
fit into the variable. A compilation
error would occur if the literal were
too large for the variable to hold.
For example, the statement byte b =
1000 would cause a compilation error,
because 1000 cannot be stored in a
variable of the byte type.
An integer literal is assumed to be of
the int type, whose value is between
-231 (-2147483648) to 231–1
(2147483647). To denote an integer32
Floating-Point Literals
Floating-point literals are written
with a decimal point. By default, a
floating-point literal is treated as
a double type value. For example, 5.0
is considered a double value, not a
float value. You can make a number a
float by appending the letter f or F,
and make a number a double by
appending the letter d or D. For
example, you can use 100.2f or 100.2F
for a float number, and 100.2d or
100.2D for a double number.
33
Scientific Notation
Floating-point literals can also be
specified in scientific notation,
for example, 1.23456e+2, same as
1.23456e2, is equivalent to 123.456,
and 1.23456e-2 is equivalent to
0.0123456. E (or e) represents an
exponent and it can be either in
lowercase or uppercase.
34
Arithmetic Expressions
is translated to
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x +
9*(4/x + (9+x)/y)
35
Shortcut Assignment Operators
Operator Example Equivalent
+= i+=8 i = i+8
-= f-=8.0 f = f-8.0
*= i*=8 i = i*8
/= i/=8 i = i/8
%= i%=8 i = i%8
36
Increment and
Decrement Operators
37
Increment and
Decrement Operators, cont.
38
Increment and
Decrement Operators, cont.
Using increment and decrement operators
makes expressions short,
int x = k; //(Wrong)
long k = x; //(fine,implicit casting)
44
Type Casting
● double
● float
● long
● int
● short
● byte
45
Type Casting, cont.
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
46
Answer
● Needs explicit type cast
47
Character Data Type
Special characters
char tab = ‘\t’;
48
Unicode Format
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000a
Carriage return \r \u000d
49
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
50
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
51
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
52
The boolean Type and Operators
54
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or
55
Truth Table for Operator !
Truth Table for Operator !
Operand !Operand
true false
false true
56
Truth Table for Operator &&
Operand1 Operand2 Operand1 &&
Operand2
false false false
false true false
true false false
true true true
57
Truth Table for Operator ||
Operand1 Operand2 Operand1 ||
Operand2
false false false
false true true
true false true
true true true
58
Operator Precedence
How to evaluate
3 + 4 * 4 > 5 * (4 + 3) - ++i
59
Operator Precedence
● var++, var--
● +, - (Unary plus and minus), ++var,--var
● (type) Casting
● ! (Not)
● *, /, % (Multiplication, division, and modulus)
● +, - (Binary addition and subtraction)
● <, <=, >, >= (Comparison)
● ==, !=; (Equality)
● & (Unconditional AND)
● ^ (Exclusive OR)
● | (Unconditional OR)
● && (Conditional AND) Short-circuit AND
● || (Conditional OR) Short-circuit OR
● =, +=, -=, *=, /=, %= (Assignment operator)
60
Operator Associativity
When two operators with the
same precedence are evaluated,
the associativity of the
operators determines the order of
evaluation. All binary operators
except assignment operators are
left-associative.
a – b + c – d is equivalent to
((a – b) + c) – d
Assignment operators are
right-associative. Therefore, the
expression 61
Operand Evaluation Order
The precedence and
associativity rules specify
the order of the operators,
but do not specify the order
in which the operands of a
binary operator are evaluated.
Operands are evaluated from
left to right in Java.
The left-hand operand of a
binary operator is evaluated
before any part of the right- 62
Operand Evaluation Order, cont.
If no operands have side effects
that change the value of a variable,
the order of operand evaluation is
irrelevant. Interesting cases arise
when operands do have a side effect.
For example, x becomes 1 in the
following code, because a is
evaluated to 0 before ++a is
evaluated to 1.
int a = 0;
int x = a + (++a);
But x becomes 2 in the following
code, because ++a is evaluated to 1,
then a is evaluated to 1. 63
Operator Precedence
How to evaluate
3 + 4 * 4 > 5 * (4 + 3) - ++i
Lets parenthisize
(3 + (4 * 4) ) > ( (5 * (4 + 3)) – (++i ) )
This is evaluates to
19 > (35 – (++i))
64
AWT
AWT (Abstract Window Toolkit): AWT represents a class library to develop applications using
GUI.
The java.awt package consists of classes and interfaces to develop GUIs.
65
Component: A component represents an object which is displayed pictorially on the screen
and interacts with the user. Ex. Button, TextField, TextArea
Panel: Panel class is a subclass of Container and is a super class of Applet. When screen
output is redirected to an applet, it is drawn on the surface of the Panel object. In, essence
panel is a window that does not contain a title bar, menu bar or border.
Window: A window represents a rectangular area on the screen without any borders or
title bar. The Window class create a top-level window.
Frame: It is a subclass of Window and it has title bar, menu bar, border and resizing
windows.
66
Delegation Event Model:
The modern approach (from version 1.1 onwards) to handle events is based on the
delegation event model. Its concept is quite simple: a source generates an event and sends it
to one or more listeners.
67
Event Sources: A source is an object that generates an event. Generally sources are
components. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event. Each type of event has its own registration method. Here is the
general form:
Here, Type is the name of the event, and el is a reference to the event listener. For
example, the method that registers a keyboard event listener is called addKeyListener( ).
A source must also provide a method that allows a listener to unregister an interest in a
specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el )
Event Listeners: A listener is an object that is notified when an event occurs. It has two
major requirements.
1.It must have been registered with one or more sources to receive notifications about
specific types of events.
2. It must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event package. 68
Sources of Events:
70
Useful Methods of Component class:
You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:
String getActionCommand( ) -Returns the command string associated with this 71
The AdjustmentEvent Class:
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.
Instances of this class describe text events. These are generated by text fields and text
areas when characters are entered by a user or program. TextEvent defines the integer
constant TEXT_VALUE_CHANGED.
73
The WindowEvent Class:
The WindowEvent class defines integer constants that can be used to identify different
types of events:
EventListener Interfaces:
An event listener registers with an event source to receive notifications about the
events of a particular type. Various event listener interfaces defined in the
java.awt.event package are given below
74
The WindowEvent Class:
The WindowEvent class defines integer constants that can be used to identify different
types of events:
EventListener Interfaces:
An event listener registers with an event source to receive notifications about the events
of a particular type. Various event listener interfaces defined in the java.awt.event
package are given below
75
76
77
78
Registration Methods:
For registering the component with the Listener, many classes provide the registration methods.
For example:
Button
o public void addActionListener(ActionListener a){}
MenuItem
o public void addActionListener(ActionListener a){}
TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
TextArea
o public void addTextListener(TextListener a){}
Checkbox
o public void addItemListener(ItemListener a){}
Choice
o public void addItemListener(ItemListener a){}
List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Mouse
o public void addMouseListener(MouseListener a){}
79
Threading concepts
a Thread is a:
•Feature through which we can perform multiple activities
within a single
process.
•Lightweight process.
•Series of executed statements.
•Nested sequence of method calls. 80
Thread Model
2) Running
A thread is in a Running state when it is
under execution.
3) Suspended
A thread is in the Suspended state when
it is temporarily inactive or under
execution.
4) Blocked
A thread is in the Blocked state when it is
waiting for resources.
5) Terminated
A thread comes in this state when at any
given time, it halts its execution
immediately.
81
Creating Thread
A thread is created either by "creating or implementing"
the Runnable Interface or by extending the Thread class. These
are the only two ways through which we can create a thread.
Thread Class
•Thread()
•Thread(Runnable, String name)
•Thread(Runnable target)
•Thread(ThreadGroup group, Runnable target, String name)
•Thread(ThreadGroup group, Runnable target)
•Thread(ThreadGroup group, String name)
•Thread(ThreadGroup group, Runnable target, String name, long
stackSize)
82
83