Java
for
beginners
Scope
Java language fundamentals
concepts of classes and inheritance
Packages & Interfaces
Exception handling
Applet programming
String handling
Three important packages: lang, I/o, util
Basics of JDBC
Eventhandling, AWT & Swing
Thursday, December Java Programming 2
9, 2021
What we will not cover….
Multithreaded programming
Java Networking
Bean programming
Rest of the packages than the three
mentioned .
Thursday, December Java Programming 3
9, 2021
Agenda
Day1: The language basics,classes,inheritance
Day2: Packages & Interfaces, Exception
handling, Inner classes
Day3: Applet Programming, String handling
Day4: Java.lang,Java.util
Day5: Java.I/o, JDBC basics
Day6: Event handling & Swing
Thursday, December Java Programming 4
9, 2021
Prerequisites
Knowledge of programming.
Knowledge of C Language basics.
Fundamental concepts of OOP
Desire to learn
Thursday, December Java Programming 5
9, 2021
The Genesis of JAVA
Conceived by a team of people at Sun
Microsystems Inc. in 1991
Originally named "Oak" , renamed to "JAVA" in
1995 and announced to public.
Thursday, December Java Programming 6
9, 2021
Why was JAVA created?
Is JAVA developed for Internet?
The answer is NO
The primary motivation was the need for a
platform-independent (I.e., architecture neutral)
language that could be used to create software to
be embedded in various consumer electronic
devices, such as microwave ovens and remote
controls.
Thursday, December Java Programming 7
9, 2021
Java Buzzwords
Simple
Architecture-Neutral
Secure
Interpreted
Portable
High Performance
Object-Oriented
Distributed
Robust
Dynamic
Multithreaded
Thursday, December Java Programming 8
9, 2021
The Java Language
The JAVA Language
Objectives
Quick look at the C-like parts of the language
OOP and Java
some useful packages and tools
Thursday, December Java Programming 10
9, 2021
On Completion ...
On completion of this topic, you should be able to:
List the major design objectives of Java
Describe its syntax and how it’s related to C.
Design and code methods for a simple class
Thursday, December Java Programming 11
9, 2021
What’s been taken out of C
pre-processor, typedefs, structs, unions or enums
goto
pointers
functions
implicit coercions (and only limited casting)
Thursday, December Java Programming 12
9, 2021
Applet vs Application
Java application is a stand alone code which could
be executed as like other language compiled code.
Java Applet is special type of Java class which
needs a Web Browser to interpret that.
Java application can be executed in the OS
command prompt.
Java Applet can be executed using Web Browser
or appletviewer.
Thursday, December Java Programming 13
9, 2021
A Simple JAVA Program
/* This is a simple Java Program */
class MyJavaProg {
public static void main(String args[]) {
System.out.println("Hello! ");
} //end of main method
} //end of class
Thursday, December Java Programming 14
9, 2021
Compiling a java program
To compile this simple application we must:
create a file, whose name should be Test.java, containing the
lines above
compile the application, by issuing the command:
javac Test.java
which will create a file called Test.class
run the application, by issuing the command:
java Test
Thursday, December Java Programming 15
9, 2021
The architecture of Java
Thursday, December Java Programming 16
9, 2021
The Byte Code
The java compiler gives Byte Code as the output.
The byte code is interpreted by the Java Virtual
Machine or the Java Run Time.
JIT - Just in time compilers (compiles the byte
code during run time and keeps using the compiled
code till the application ends)
Regular compilers are also available.
Thursday, December Java Programming 17
9, 2021
The Basics - Lexical Issues
Identifiers(Variables)
An identifier may be any descriptive sequence of
uppercase and lowercase letters, numbers or the
underscore and dollar sign characters.
Must not start with a number.
Java is case sensitive
Thursday, December Java Programming 18
9, 2021
Literals
Five types of Literals:
integer values
in base 10, 16 or 8, as in C.
Floating point values
either single precision float (force with a F or f suffix)
or double (the default now - force with D or d) e.g.
3.1e2
Thursday, December Java Programming 19
9, 2021
Literals
Boolean values
either true or false
character values
‘a’ , '\r' , '\u1234'
strings -
"AX" , “this is a string”
Thursday, December Java Programming 20
9, 2021
Data types (atomic)
The Simple Types
Integers - whole valued signed numbers
byte, short, integer, long
Floating-point Numbers - numbers with fractional
precision
float, double
Characters - symbols in a character set
char
Boolean - true / false
Thursday, December Java Programming 21
9, 2021
Data Size
Width Name
Java provides machine
8 byte independent width for data
16 short types.
32 int
Java does not support
unsigned integers (positive
64 long only integers)
IEEE 754 floating point
Width Name
32 float
64 double
Thursday, December Java Programming 22
9, 2021
Data Size
Java uses unicode to represent characters.
The width of storage for a character is 16 bits.
String is a separate class in Java and it is not a
primitive data type.
Boolean takes values either true or false
Note/Caution : Boolean do not map to numbers as
in C.
Thursday, December Java Programming 23
9, 2021
Type Casting
Java is strictly type cast
Rules:
byte and short are promoted to int
if one operand is long, then entire expression is
promoted to long
if one is float, then then entire expression is
promoted to float
if one is double, then entire expression is
promoted to double
Thursday, December Java Programming 24
9, 2021
Operators
unary integer operators:
–- negation
–~ bitwise complement
– ++ increment
– -- decrement
These operators may be combined with the
assignment operator, as in C:
a -= b; /* same as a = a - b */
Thursday, December Java Programming 25
9, 2021
Operators -- contd
binary integer operators:
+ addition
- subtraction
* multiplication
/ division
% modulus ( can be applied to float also as against C/C++)
& bitwise AND
| bitwise OR
^ bitwise XOR
<< left shift
>> right shift (arithmetic)
Thursday, December Java Programming 26
9, 2021
Operators -- contd
integer and boolean relational operators:
! not (can be combined with < or > or =)
> greater than (can be combined with =)
< less than (can be combined with =)
== equal
& bitwise AND
| bitwise OR
^ bitwise XOR
&& boolean AND (short-cut - avoids evaluation of right-hand
operand)
|| boolean OR (short-cut - avoids evaluation of right-hand operand)
Thursday, December Java Programming 27
9, 2021
Operators -- contd
ternary conditional operator:
?: as in C/C++ this is an abbreviated if-else
Thursday, December Java Programming 28
9, 2021
Object Oriented
Programming
An Introduction and overview
Programming Paradigms
P r o g r a m m in g
P r o c e s s -O r ie n te d O b je c t-O r ie n te d
c o d e a c tin g o n d a ta d a ta c o n tr o llin g a c c e s s to c o d e
Thursday, December Java Programming 30
9, 2021
Abstraction
In real world humans visualize,
think of anything as a whole object.
For example, do we think of the
hundreds of parts in a car? But we
do think about the behavior of the
car, the object. You can treat these
objects a concrete entities that
respond to messages telling them to
! ?
do something. This is the essence of
OOP.
Thursday, December Java Programming 31
9, 2021
The three OOP Principles
Encapsulation
Inheritance
Polymorphism
Thursday, December Java Programming 32
9, 2021
The three OOP Principles
Encapsulation
Binding the data and code
together
Inheritance
Prevents arbitrary access
Polymorphism of code / data by another
code
In JAVA the basis of
encapsulation is the class.
Thursday, December Java Programming 33
9, 2021
The three OOP Principles
Encapsulation
Inheritance is a process by
which one object acquires
Inheritance the properties of another
Polymorphism object.
The new class inherited is
called the subclass and
the parent class is called
the superclass
Thursday, December Java Programming 34
9, 2021
The three OOP Principles
Encapsulation
One interface multiple
methods
Inheritance
Same object / method
Polymorphism behaving in different ways
depending on the input
object .
Thursday, December Java Programming 35
9, 2021
Class Modifiers
Abstract
An Abstract class cannot be instantiated.
An Abstract class cannot be final.
Final
Cannot have subclasses.
Public
Can be referred to by other packages.
Thursday, December Java Programming 36
9, 2021
Interface
Interfaces provide some features of multiple inheritance:
Like an abstract class, an interface defines a set of methods (and
perhaps constants as well), but no implementation.
By using the implements keyword, a class can indicate that it
implements that set of methods.
This makes it unnecessary for related classes to share a common
superclass or to directly subclass object.
It’s possible for a class to implement several interfaces.
Thursday, December Java Programming 37
9, 2021
Variable
public accessible anywhere the class is
protected accessible in package defining class and within
body of any subclass
private accessible only within the class within which it is
defined.
static belongs to the class, not to instances. Sometimes
called class variables as opposed to instance variables.
final must have an initializer - this is the only way of setting
its value - it’s a constant.
Thursday, December Java Programming 38
9, 2021
Method definition
[methodmodifiers] resulttype methodname (arglist)
[throws throwlist]
{
method body
}
Thursday, December Java Programming 39
9, 2021
Method Modifiers
Public
Private
Abstract
Final
Protected
Synchronized
Static
Thursday, December Java Programming 40
9, 2021
Invoking Methods
Syntax to invoke a method is:
object.methodname(argumentlist);
Thursday, December Java Programming 41
9, 2021
Method invoking -- contd
implied:
mymethod(...);
simple:
myobject.mymethod(...);
static class method:
myclass.classmethod(...);
create an object, then invoke a method on it:
(new myclass(...)).mymethod;
Thursday, December Java Programming 42
9, 2021
Method invoking -- contd
indirect reference
myobject.methodreturninghisobject(..).hismethod(..);
Here’s a specific example of the last form:
String s;
double d;
s = “43.4”;
d = Double.valueOf(s).doubleValue(); // set d to
43.4
Thursday, December Java Programming 43
9, 2021
Some Differences
Because integers are signed, there’s a new shift operator:
>>> zero-fill right shift (treats value as unsigned)
Because booleans are not numeric, the following is illegal:
int i, j;
if (i = j) ... /* i = j is an int, not boolean */
The + and += operators have been overloaded for strings -
concatenating as in BASIC. Note that operator overloading, as
implemented in C++, is not available.
Thursday, December Java Programming 44
9, 2021
Arrays
Arrays are objects, so you create them using new:
int i[];
i = new int[10];
creates an array of 10 integers, indices run from 0 to 9. You can of
course create arrays of any class.
No multi-dimension arrays, instead use arrays of arrays:
int j[][] = new int[3][4];
Array subscripts checked to ensure they are valid integers. If not, a
run-time error occurs.
Thursday, December Java Programming 45
9, 2021
Arrays -- contd
Dimensions determined at run-time:
int i[];
int j;
...
j = i.length;
length is not a method, but a “predefined” instance variable
N.B. array dimensions are not dynamically changeable - once
created, dimensions are fixed.
Thursday, December Java Programming 46
9, 2021
Strings
Strings are also objects - the String class has methods
with similar functionality to C’s strxxx of functions:
String s1, s2;
int i;
s2 = new String("this is a short string");
s1 = s2.toUpperCase();
if (s2.equals(s1)) {// s2 was in upper case
}
Thursday, December Java Programming 47
9, 2021
Strings -- contd
i = s1.length();// sets i to 22
// length is a method
s2 = String.valueOf(i); // sets s2 to "22"
s1 = s2.concat("abc2"); // sets s1 to "22abc2"
s2 = s1.substring(2,3);// sets s2 to "a"
// 2nd index is exclusive
i = s1.indexOf("2",3); // sets i to 5
Thursday, December Java Programming 48
9, 2021
Wrapper Classes
As well as the basic data types, such as int, there’s
also a set of matching “wrapper” classes:
Integer
Long
Float
Double
Boolean
Character
Thursday, December Java Programming 49
9, 2021
This and super
this and super
A subclass inherits the methods of its super class.
When a subclass overrides such methods, it’s often
necessary to invoke the equivalent method in the
parent class and the keyword super lets you do
this:
Thursday, December Java Programming 50
9, 2021
This and super
class mybutton extends Button {
public void setLabel(String label) {
setFont(myspecialfont); // change the font
super.setLabel(label); // label the button
}
}
Note that in a constructor any invocation of a superclass
constructor must be the first statement - if not present:
super();
is added by the compiler.
Thursday, December Java Programming 51
9, 2021
this and Super
The keyword this refers to the current object -
useful when you want to pass the current object to
another to allow the latter to execute the former’s
methods.
Thursday, December Java Programming 52
9, 2021
Instanceof
The type comparison operator, instanceof, that lets you determine
if an object is of a specific class:
Button b;
MyButton mb;// where MyButton extends Button
if (b instanceof Button) // is true
if (mb instanceof MyButton) // is true
if (mb instanceof Button) // is true
if (b instanceof MyButton) // is false
Thursday, December Java Programming 53
9, 2021
JAVA Tools
The following tools are provided as part of the Java package:
appletviewer runs an applet (i.e. a class derived from
applet) as though in a browser. The OS/2 version is called
applet.
java runs an application (i.e. a class with a main method).
The OS/2 port also has a javapm tool -use in place of java to
run a PM application.
Thursday, December Java Programming 54
9, 2021
JAVA Tools -- contd
javac compiles a .java file into classes
javadoc produces documentation from a .java files (or a
whole package)
javah produces C header/source file glue for native classes
from a class file
javap disassembles classes
jdb debugger
Thursday, December Java Programming 55
9, 2021
Exceptions
Exceptions
Run-time errors are called exceptions - handled
using try-catch:
At run-time, this will display the message:
"Exception ‘java.lang.ArithmeticException: / by zero’
raised - i must be zero"
Thursday, December Java Programming 56
9, 2021
Exceptions -- contd
int i, j;
i = 0;
try {
j = 3/i; // attempt to divide by zero
} catch (java.lang.ArithmeticException e) {
// exception handler
System.out.println("Exception ‘" + e +
“‘ raised - i must be zero");
j = Integer.MAX_VALUE; // max value of an int
}
Thursday, December Java Programming 57
9, 2021
Exceptions -- contd
If you use methods that have a throws (throwlist)
clause on the method statement, you must:
handle it yourself by enclosing such method
invocations in try/catch clauses
or declare that your method can throw the
exception(s) by giving it a throws throwlist clause.
Thursday, December Java Programming 58
9, 2021
HTML page
A Simple HTML page with an APPLET tag
<html>
<head>
<title>Dave's Jumping Button</title> </head>
<body>
Thursday, December Java Programming 59
9, 2021
HTML page
<h1>A Simple Java Button</h1>
<p>Press the button to make it jump.
<hr>
<applet code="BBJump.class" width=600 height=200>
<param name=TITLE value="Press Me!">
<p>This page is Java-enhanced.
</applet>
</body>
</html>
Thursday, December Java Programming 60
9, 2021
Network Programming
URL and URLConnection provide ways of opening streams
to read from (and write to?) URLs
Socket is the basic class for socket programming (client to
server or server to client)
ServerSocket provides facilities needed in server to listen for
connection requests
InetAddress provides network addressing
Thursday, December Java Programming 61
9, 2021
netscape
Thursday, December Java Programming 62
9, 2021
Appletviewer
Thursday, December Java Programming 63
9, 2021
Syntax of Applet tag
Syntax of the APPLET Tag
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
Thursday, December Java Programming 64
9, 2021
Syntax of Applet tag
>
[< PARAM NAME = appletAttribute1 VALUE = value >]
[< PARAM NAME = appletAttribute2 VALUE = value >]
...
[alternateHTML]
</APPLET>
Thursday, December Java Programming 65
9, 2021
Syntax of Applet tag
N.B. You can suggest an alternative location for class
files using:
<ARCHIVE=“archiveURL”> uncompressed ZIP
and/or:
<PARAM NAME=“cabbase” VALUE=“vendor.cab”>
ARCHIVE is currently supported by Navigator 3.0 and
CAB files by Internet Explorer 3.0
Thursday, December Java Programming 66
9, 2021
Structure of an Applet
class Myapplet extends Applet {
public void init() {
// invoked when applet is created
}
public void start() {
// invoked when document referring to applet
// is visited
}
Thursday, December Java Programming 67
9, 2021
Structure of an Applet
public void stop() {
// invoked when document referring to applet is left
}
public void destroy() {
// invoked (after stop) when applet’s
// resources are being cleaned up
}
}
Applet does not have to die when stop is invoked - can persist on another
thread.
Thursday, December Java Programming 68
9, 2021
Thank You
Thursday, December Java Programming 70
9, 2021
Encapsulation
Public Private
methods instance
variables
Public
instance
variables
Private
methods
Thursday, December Java Programming 71
9, 2021
Inheritance
Automobile
Two Wheeler Four Wheeler
100cc Vehicle 50cc Vehicle
Hero Honda Kawasaki-Bajaj
Splendor Sleek Caliber
Thursday, December Java Programming 72
9, 2021
Polymorphism
BARK
!&
Chase
Smell
Thursday, December Java Programming 73
9, 2021
Polymorphism
Salivate
& Run
to Bowl
Smell
Thursday, December Java Programming 74
9, 2021
Overriding
Vehicle
Color
Weight
Length
move()
Car Ship Truck
Color Color Color
Weight Weight Weight
Length Length Length
move() move() move()
Thursday, December Java Programming 77
9, 2021