Java chapter_1 and 2
Java chapter_1 and 2
Overview of Java
Programming
1
Java Programming Language
Java is a high level, class-based, OO PL that is designed to have as few
implementation dependencies as possible.
It is a general purpose programming language intended to
let programmers write once, run anywhere.
Compiled Java code can run on all platforms that support Java without
the need to recompile.
Java was designed by James Gosling at Sun Microsoft Systems
It was released in May 1995 as a core component of Sun's Java
Platform.
• It is owned by Oracle, and more than 3 billion devices run Java.
2
Java Programming Language Cont’d…
It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
3
Why Use Java?
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc.)
It is one of the most popular programming languages in the world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has huge community support (tens of millions of developers)
Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
As Java is close to C++ and C#, it makes it easy for programmers to
switch to Java or vice versa
4
Java Programming Language Cont’d…
Form:Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
5
Java Programming Language Cont’d…
1. Public
It is an Access modifier, which specifies from where and who can
access the method. Making the main() method public makes it globally
available. It is made public so that JVM can invoke it from outside the
class as it is not present in the current class.
If the main method is not public, it’s access is restricted
2. Static
It is a keyword that is when associated with a method, making it
a class-related method. The main() method is static so that JVM can
invoke it without instantiating the class. This also saves the
unnecessary wastage of memory which would have been used by the
object declared only for calling the main() method by the JVM.
6
Java Programming Language Cont’d…
3. Void
It is a keyword and is used to specify that a method doesn’t return anything. As
the main() method doesn’t return anything, its return type is void. As soon as
the main() method terminates, the Java program terminates too. Hence, it doesn’t make
any sense to return from the main() method as JVM can’t do anything with its return
value of it.
4. main
It is the name of the Java main method. It is the identifier that the JVM looks for as
the starting point of the Java program. It’s not a keyword.
5. String[] args
It stores Java command-line arguments and is an array of type java.lang.String class.
Here, the name of the String array is args but it is not fixed and the user can use any
name in place of it.
7
Data Types
Primitive Data Types
Primitive data types are the most basic data types available in a programming language. They are
predefined and supported by the language itself. These data types represent single values and are
not composed of other data types.
Primitive Data Types
Non-primitive data types, also known as reference types, are more complex data types that are
derived from primitive data types. They can store multiple values and are created by the
programmer.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.
These can be put in four groups:
Integers: this group includes byte, short, int, and long, which are for whole-valued signed numbers.
Floating-point numbers: this group includes float and double, which represent numbers with fractional
precision.
Characters: this group includes char, which represents symbols in a character set, like letters and numbers.
Boolean: this group includes boolean, which is a special type for representing true/false values.
8
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String , Arrays and Classes
9
Integers
Java defines four integer types: byte, short, int, and long.
byte b, c;
short s;
short t;
int lightspeed;
long days;
10
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
• float hightemp, lowtemp;
• double pi, r, a;
The type float specifies a single-precision value that uses 32 bits of storage.
Double precision, as denoted by the double keyword, uses 64 bits to store a
value.
When you need to maintain accuracy over many iterative calculations, or are
manipulating large-valued numbers, double is the best choice.
11
Characters
In Java, the data type used to store characters
is char.
In C/C++, char is 8 bits wide.
Java uses Unicode to represent characters.
Unicode defines a fully international
character set that can represent all of the
characters found in all human languages.
It is a unification of dozens of character sets,
such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more.
For this purpose, it requires 16 bits.
The range of a char is 0 to 65,536.
char unicodeChar = '\u0041'; // Unicode for 'A'
12
Booleans
Java has a primitive
type, called boolean, for
logical values.
It can have only one of
two possible values,
true or false.
This is the type returned
by all relational
operators.
13
Variables
• The variable is the basic unit of storage in a Java program.
• A variable is defined by the combination of an identifier, a type, and
an optional initializer.
• In addition, all variables have a scope, which defines their visibility,
and a lifetime.
• Declaring a Variable
• type identifier [ = value][, identifier [= value] ...] ;
• The identifier is the name of the variable.
14
The Scope and Lifetime of Variables
Java allows variables to be declared within any
block.
A block is begun with an opening curly brace
{ and ended by a closing curly brace }.
A block defines a scope.
A scope determines what objects are visible to
other parts of your program.
It also determines the lifetime of those objects.
Scopes can be nested.
Variables are created when their scope is entered,
and destroyed when their scope is left.
The lifetime of a variable is confined to its scope.
Local Variables: Limited to the method/block.
Instance Variables: Tied to an instance of the
class.
Class Variables: Shared across all instances of the
class.
Block Variables: Limited to the block of code. 15
Type Conversion and Casting
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will take
place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place.
There are no automatic conversions from the numeric types to char or boolean.
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);
System.out.println(myDouble);}}
16
Casting Incompatible
Types
To create a conversion
between two
incompatible types, you
must use a cast.
A cast is simply an
explicit type conversion.
It has this general form:
(target-type)
value
17
Arrays
An array is a group of like-typed variables that are referred to by a
common name.
Arrays of any type can be created and may have one or more
dimensions.
A specific element in an array is accessed by its index.
One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables.
type var-name[ ];
The general form of new as it applies to one-dimensional arrays
appears as follows:
array-var = new type[size];
18
• Array Initialization
19
Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of arrays.
int twoD[][] = new int[4][5];
20
Alternative Array Declaration Syntax
• There is a second form that may be used to declare an array:
type[ ] var-name;
• For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
• The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
• This alternative declaration form offers convenience when declaring several
arrays at the same time.
int[] nums, nums2, nums3; // create three arrays.
This is similar to
int nums[], nums2[], nums3[]; // create three arrays
21
Decision and Repetition statement
• Repetition statements allow us to execute a statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by boolean
expressions
• Java has three kinds of repetition statements:
• the while loop
• the do loop
• the for loop
• The programmer should choose the right kind of loop for the situation
22
The while Statement
• The while statement has the following syntax:
while ( condition )
statement;
23
Logic of a while Loop
condition
evaluated
true false
statement
24
The while Statement
int count = 1;
while (count <= 5){
System.out.println (count); count++;
}
25
Infinite Loops
• The body of a while loop eventually must make the condition false
• If not, it is an infinite loop, which will execute until the user interrupts
the program
• This is a common logical error
• You should always double check to ensure that your loops will
terminate normally
26
Cont’d…
int count = 1;
while (count <= 25){
System.out.println (count);
count = count - 1;
}
• This loop will continue executing until interrupted or until an
underflow error occurs
27
Nested Loops
• Similar to nested if statements, loops can be nested as well
• That is, the body of a loop can contain another loop
• For each iteration of the outer loop, the inner loop iterates completely
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10){
count2 = 1;
while (count2 <= 20) {
System.out.println ("Here"); count2++;
} count1++;
} 10 * 20 = 200
28
The do-while Statement
A do-while statement (also called a do loop) has the following syntax:
do{
statement;
}
while ( condition )
The statement is executed once initially, and then the condition is
evaluated
The statement is executed repeatedly until the condition becomes
false
29
Logic of a do Loop
statement
true
condition
evaluated
false
• A do loop is similar to a while loop, except that the condition is evaluated after the body of the
loop is executed
• Therefore the body of a do loop will execute at least once 30
Comparing while and do
while loop do loop
statement
condition
evaluated
true
31
The for Statement
• The for statement has the following syntax:
32
Cont’d…
• A for loop is functionally equivalent to the following while loop
structure:
initialization;
while ( condition )
{
statement;
increment;
}
33
Logic of a for loop
initialization
condition
evaluated
true false
statement
increment
Like a while loop, the condition of a for statement is tested prior to executing the loop body
Therefore, the body of a for loop will execute zero or more times 34
Cont’d…
• Each expression in the header of a for loop is optional
35
Choosing a Loop Structure
• When you can’t determine how many times you want to execute the
loop body, use a while statement or a do statement
• If it might be zero or more times, use a while statement
• If it will be at least once, use a do statement
• If you can determine how many times you want to execute the loop
body, use a for statement
36
. Exception Handling
When a program runs into a runtime error, the program terminates abnormally. How can you
handle the runtime error so that the program can continue to run or terminate gracefully? This is
the subject we will introduce in this topic.
What is an Exception?
• An exception is an event that occurs during the execution of a program which interrupts the
normal flow of instructions.
• It is an unwanted or unexpected event that occurs during the execution of a program (i.e.,
at runtime) and disrupts the normal flow of the program’s instructions.
• It occurs when something unexpected things happen, like accessing an invalid index, dividing by
zero, or trying to open a file that does not exist.
Examples:
• Divide a number by 0
• Access an out-of-bounds array element
• Null Pointer reference
• Cannot convert a string to an integer
• .... and lots more. 37
How Java Handles Exception?
Exception in Java is an error condition that occurs when something wrong happens during
the program execution.
When an error occurs within a Java method, the method creates an Exception object and hands
it off to the runtime system.
The runtime system is then responsible for finding some code to handle the error.
In Java terminology, creating an exception object and handing it to the runtime system is
called throwing an exception.
After a method throws an exception, the runtime system will find someone to handle the
exception.
• Exception handling in Java allows developers to manage runtime errors effectively by using
mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception
handling, etc.
38
Example
import java.io.*;
class CS {
public static void main(String[] args)
{
int a = 5;
int b = 0;
int c = a / b;
System.out.println(“Result is : " + c); }}
39
How Java Handles Exception?
The runtime system searches backwards void p() {
try {
through the call stack to find a method that f();
contains an appropriate exception handler }
catch (Exception e) {
(see example at the right). // something to do 3
The exception handler chosen is said to .....
}
catch the exception. }
If no exception handler is found, the Java void f() {
program terminates . g();
} 2
void g() {
h();
}
1
void h() {
// error occurs
throw new
Exception(); 40
......
Throwing an Exception
When an error occurs within a Java method, the method
calls the throw statement to Indicates an exception has
occurred.
if (total < 0)
throw new Exception("Negative Total");
Handle Exception
Some exceptions must be handled.
Exception can be handled in a method in two ways:
1. Use a try-catch block to handle the exception
2. Rethrow the exception
41
try Blocks
• The try block structure
try {
statements that may throw an exception
}
catch ( ExceptionType1 exceptionReference1 ) {
statements to process an exception
}
catch ( ExceptionType2 exceptionReference2 ) {
statements to process an exception
} Optional
......
finally {
statements always executed
}
>java CatchException1
Invalid Number of arguments!
Usage : java AddTwoIntegers <num1>
<num2> 44
Example 1
>java CatchException1 A B
Example 2
• Single catch can handle multiple exceptions
• The catch statement in the next example catches exception
objects of Exception and all its subclasses.
Exception
ArrayIndexOutOfBoundsException NumberFormatException
45
Example 2
public class CatchException2 {
public static void main( String args[] ) { Message stored in the
int num1, num2; Exception object e
try {
num1 = Integer.parseInt(args[0]);
num2 = Integer.parseInt(args[1]);
System.out.println("The sum is " + (num1+num2));
}
catch (Exception e) {
System.out.println("The error : " + e.toString());
System.out.println(
"Usage : java AddTwoIntegers <num1> <num2>");
}
}
}
>java CatchException2
The error : java.lang.ArrayIndexOutOfBoundsException:
0
Usage : java AddTwoIntegers <num1> <num2>
>java CatchException2 A B
The error : java.lang.NumberFormatException: For input
string: "A"
Usage : java AddTwoIntegers <num1> <num2> 46
Throwing an Exception
The throw statement is executed to indicate that an exception
has occurred. This is called throwing an exception.
Example
class ComplexNum {
private double real;
private double imag;
49
Unchecked Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
Unchecked
Many more classes
exception.
50
Chapter 2: Java Applets
Introduction
Java applets are one of three kinds of Java programs:
• An application is a standalone program that can be invoked from the command
line.
• An applet is a program that runs in the context of a browser session(local).
• A servlet is a program that is invoked on a server program, and it runs in the
context of a web server process.
The big difference between both is:
Applications contain enough code to work on their own.
Applets need a controlling program to tell the applet when to do what.
An applet has no means of starting execution because it does not have a
main() method.
51
Introduction…
Java has become very popular because of its natural applicability to programming
network software for the WWW.
Java is best known as a language for programming applets.
An applet is a “mini-application” that runs within the context of a larger application, such
as a network browser.
It is a small Java program that is embedded and ran in some other Java interpreter
program such as:
⚫ a Java technology enabled browser (IE)
⚫ Sun’s applet viewer program called applet viewer that which is a standalone program that
java Applet Support.
52
Introduction…
Java Applets are programs designed to run Web applications
inside a web browser.
Instead of having a “main” method they have a
53
Introduction…
Applets loaded from the internet are run inside a
“sandbox” which restricts for security reasons what they
can do:-
• No Access to local/client’s file system
• Can only open network connections with the site they came
from.
The WWW, which uses a client server framework, is a
virtual network built on top of the Internet.
• The client is called a browser, which requests data from
servers.
• The server is called a Web server.
• A Web server responds to requests by sending HTML
documents back to the browser which are then displayed for
the user. 54
Introduction…
The focus of an applet is the WWW, although several other
tools (such as appletviewer) can also run Java applets. Applets are
normally embedded within HTML documents.
An applet runs in a context that provides windowing
support, multi media support (graphics, sound, etc.) ,network
support and security support.
An applet is a small program that is intended not to be run on its
own, but rather to be embedded inside another application.
55
Applet Execution
An applet program is a written as a inheritance of the java.Applet class
There is no main() method in an Applet, rather have init() method.
Almost every applet you ever write will have an init() method,which is
invoked by the Browser when the applet starts.
Called each time the page is loaded and restarted.
An applet uses AWT for graphics ( draw, paint ,..etc )
An applet can react to major events in the following ways:
• It can initialize itself.
• It can start running.
• It can stop running.
• It can perform a final cleanup, in preparation for being unloaded.
57
Life Cycle of an Applet
init: This method is intended for whatever initialization is needed for an applet.
start: This method is automatically called after init method. It is also called
whenever user returns to the page containing the applet after visiting other pages.
stop: This method is automatically called whenever the user moves away from the
page containing applets.This method can be used to stop an animation.
destroy:This method is only called when the browser shuts down normally, Cleans
up whatever resources are being held.
58
Life Cycle of an Applet…
Browser visits page containing an applet -init() and start()
• browser calls init on that applet, once and browser calls start on that
applet
Browser goes away from that page- stop()
• browser calls stop on that applet
Browser comes back to that page- start()
• browser calls start again on that applet
Browser shuts down-destroy()
• browser calls destroy on the applet, once
59
Basic Applet methods
public void init ()
public void start () init()
public void stop ()
start(
public void destroy ()
)
public void paint
do some work
(Graphics)
Also:
stop(
public void repaint()
)
public void update (Graphics) public destroy
void showStatus(String) public String
()
getParameter(String
The applet is running and rendered on the web page.
Every Applet needs to implement one or more of the init(), the start(
) and the paint( ) methods.
At the end of the execution, the stop( ) method is invoked, followed by
61
Lifecycle Applet-Example
import java.applet.Applet;
import java.awt.Graphics;
64
Sample program
import java.awt.Graphics;
import java.applet.*;
65
import java.awt.*; / / to draw graphics objects
import java.applet. Applet;// to implement java class public class MyApplet extends Applet {
MyApplet.java
public void paint( Graphics g ) {
Or public void paint ( java.awt.Graphics g )
g.drawString( “Java Applet Program Test!", 30, 30 );
}
}
Why we need applet?
The language java is very convenient for :
• Programming involving graphics objects
• Interactive applications
• Network programming
66
Event Handling
What is an Event?
Change in the state of an object is known as event
Events are generated as result of user interaction with the graphical user interface
components.
For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes
an event to happen.
Types of Events:
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user.
• They are generated as consequences of a person interacting with the graphical
components in Graphical User Interface.
• For example, clicking on a button, moving the mouse, entering a character through
keyboard,selecting an item from list, scrolling the page etc.
67
Event Handling…
Background Events - Those events that require the interaction of end
user are known as background events. Operating system interrupts,
hardware or software failure, timer expires, an operation completion are the
example of background events.
What is Event Handling?
• Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism have the code
which is known as event handler that is executed when an event occurs.
• Java Uses the Delegation Event Model to handle the events.
• This model defines the standard mechanism to generate and handle the
events.
68
Event Handling…
•The Delegation Event Model has the following key participants namely:
⚫ Source - The source is an object on which event occurs. Source is
responsible for providing information of the occurred event to it's
handler. Java provide as with classes for source object.
⚫ Listener - It is also known as event handler.Listener is responsible
for generating response to an event. From java implementation point of
view the listener is also an object. Listener waits until it receives an
event. Once the event is received , the listener process the event an
then returns.
69
Sample Program
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
public class Eventap extends Applet implements ActionListener{
Button b;
TextField tf;
Checkbox c1;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
70
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
add(c1);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome Applet programming"); }}
71
Thank you!
72