0% found this document useful (0 votes)
6 views83 pages

Advanced_Java_Programming

The document provides an introduction to Java programming, covering its characteristics, basic syntax, and structure of a Java program. It includes examples of simple applications, data types, variables, operators, and methods, as well as instructions for compiling and running Java programs. Additionally, it discusses concepts such as type casting, boolean operators, and operator precedence.

Uploaded by

varanyogesh789
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views83 pages

Advanced_Java_Programming

The document provides an introduction to Java programming, covering its characteristics, basic syntax, and structure of a Java program. It includes examples of simple applications, data types, variables, operators, and methods, as well as instructions for compiling and running Java programs. Additionally, it discusses concepts such as type casting, boolean operators, and operator precedence.

Uploaded by

varanyogesh789
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 83

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;

public class Welcome {


public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

5
Anatomy of a Java Program
● Comments
● Reserved words
● Modifiers
● Statements
● Blocks
● Classes
● Methods
● The main method
● The exit method

6
Comments

In Java, comments are


preceded by two slashes (//)
in a line, or enclosed
between /* and */ in one or
multiple lines. When the
compiler sees //, it ignores
all text after // in the
same line. When it sees /*,
7
Reserved 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. Other
reserved words in Example 1.1
8
Modifiers
Java uses certain reserved words
called modifiers that specify the
properties of the data, methods, and
classes and how they can be used.
Examples of modifiers are public and
static. Other modifiers are private,
final, abstract, and protected. A
public datum, method, or class can
be accessed by other programs. A
private datum or method cannot be
accessed by other programs. 9
Statements
A statement represents an
action or a sequence of
actions. The statement
System.out.println("Welcome
to Java!"); in the program
in Example 1.1 is a
statement to display the
greeting "Welcome to Java!"
Every statement in Java ends
10
Blocks
A pair of braces in a program
forms a block that groups
components of a program.

11
Classes
The class is the essential Java
construct. A class is a template
or blueprint for objects.

A java program is defined by


using one or more classes.

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.

The main method looks like this:

public static void main(String[]


args) {
14
The exit Method
Use Exit to terminate the program and
stop all threads.

When your program starts, a thread is


spawned to run the program. To
terminate the thread, you have to invoke
the exit method.
15
Primitive Data Types and Operations
● 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: ++, --, *, /, %, +=, -=, *=, /=, %=, ^,
&, |, +, -,
● Getting Input from Input Dialog Boxes
● Case Studies (Computing Mortgage, and Computing Changes)
● Style and Documentation Guidelines
● Syntax Errors, Runtime Errors, and Logic Errors
16
Identifiers
● An identifier is a sequence of
characters that consist of letters,
digits, underscores (_), and dollar
signs ($).
● An identifier must start with a
letter, an underscore (_), or a dollar
sign ($). It cannot start with a
digit.
● An identifier cannot be a reserved word. (See Appendix
A, “Java Keywords,” for a list of reserved words).
● An identifier cannot be true, false, or
null.
17
Variables
// Compute the first area
radius = 1.0;
area = radius*radius*3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

// Compute the second area


radius = 2.0;
area = radius*radius*3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

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;

final double PI = 3.14159;


final int SIZE = 3;

23
Operators
+, -, *, /, and %

5/2 yields an integer 2.


5.0/2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the


division)
5.0 % 2 is not defined : modulo is
defined only for integers.
24
NOTE
Calculations involving floating-
point numbers are approximated
because these numbers are not
stored with complete accuracy. For
example,
System.out.println(1 - 0.1 - 0.1 -
0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not
0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not
0.1. Integers are stored
25
Example Program 1: Addition

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,

but it also makes them complex and


difficult to read.

Avoid using these operators in


expressions that modify multiple
variables, or the same variable for
multiple times such as this: int k = ++i
+ i. Its not a good programming
39
40
41
42
Assignment Expressions and
Assignment Statements
Prior to Java 2, all the expressions
can be used as statements. Since Java
2, only the following types of
expressions can be statements:
variable op= expression; // Where op is
+, -, *, /, or %
++variable;
variable++;
--variable;
variable--;
43
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i*3+4;
double d = i*3.1+k/2;

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)

What is wrong? int x = 5/2.0;

46
Answer
● Needs explicit type cast

● int x = (int) 5/2.0;

47
Character Data Type

char letter = 'A'; (ASCII)


char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)

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';

char c = 97; // Same as char c = (char)97;

52
The boolean Type and Operators

boolean lightsOn = true;


boolean lightsOn = false;

boolean b = (1 > 2);

● && (and) (1 < x) && (x < 100)


● || (or) (lightsOn) || (isDayTime)
●! (not) !(isStopped)
53
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

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

This evaluates to true if the value of i just before this


expression is > 15

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

Container: A Container is a subclass of Component; it has methods that allow other


components to be nested in it. A container is responsible for laying out (that is positioning)
any component that it contains. It does this with various layout managers.

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.

Events: An event is an object that describes a state change in a source. It can be


generated as a consequence of a person interacting with the elements in a GUI. Some of
the activities that cause events to be generated are pressing a button, entering a character
via the keyboard, selecting an item in a list, and clicking the mouse.

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:

public void addTypeListener (TypeListener el )

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:

Event Classes and Listener Interfaces:


The java.awt.event package provides many event classes and Listener interfaces for event
handling. At the root of the Java event class hierarchy is EventObject, which is in
java.util. It is the super class for all events. It‘s one constructor is shown here:
EventObject(Object src) - Here, src is the object that generates this event.
EventObject contains two methods:
Object getSource( ) - Object on which event initially occurred.
String toString( ) - toString( ) returns the string equivalent of the event.
The package java.awt.event defines many types of events that are generated by various
user interface elements

70
Useful Methods of Component class:

The ActionEvent Class:


An ActionEvent is generated when a button is pressed, a list item is double-clicked,
or a menu item is selected.
The ActionEvent class defines four integer constants that can be used to identify any
modifiers associated with an action event: ALT_MASK, CTRL_MASK,
META_MASK (Ex. Escape), and SHIFT_MASK.

ActionEvent has these three constructors:


o ActionEvent(Object src, int type, String cmd)
o ActionEvent(Object src, int type, String cmd, int modifiers)
o ActionEvent(Object src, int type, String cmd, long when, int modifiers)

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.

The ComponentEvent Class:


A ComponentEvent is generated when the size, position, or visibility of a component is
changed. There are four types of component events. The ComponentEvent class defines
integer constants that can be used to identify them:
ComponentEvent is the
superclass either directly
or indirectly of
ContainerEvent,
FocusEvent, KeyEvent,
MouseEvent, and
WindowEvent, among
others.
72
The KeyEvent Class
A KeyEvent is generated when keyboard input occurs. There are three types of key
events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED.

The MouseEvent Class:


There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
Two commonly used methods in
this class are getX( ) and
getY( ). These return the X and
Y coordinates of the mouse
within the component when the
event occurred.
Their forms are shown here:
int getX( )
int getY( )

The TextEvent Class:

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 very light-weighted process, or we can say the


smallest part of the process that allows a program to operate more
efficiently
In order toby running
perform multiple tasks
complicated simultaneously.
tasks in the background,
we used the Thread concept in Java. All the tasks are
executed without affecting the main program. In a
program or process,

Another benefit of using thread is that if a thread gets an


exception or an error at the time of its execution, it
doesn't affect the execution of the other threads. All the
threads share a common memory and have their own
stack, local variables and program counter. When multiple
threads are executed in parallel at the same time, this
process is known as Multithreading.

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

1) New (Ready to run)


A thread is in New when it gets CPU time.

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

A Thread class has several methods and constructors which allow


us to perform various operations on a thread. The Thread class
extends the Object class. The Object class implements
the Runnable interface. The thread class has the following
constructors that are used to perform various operations.

•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

You might also like