You are on page 1of 79

Introduction to

Java Programming

Ashwinth.J
Anna University Chennai
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

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

3
JDK 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.

4
Getting Started with Java
Programming

• Overview of Java
• Simple Java Application
• Compiling Programs
• Executing Applications

5
Overview of Java

6
How does Java work?
 Java source code is compiled into Java Source code
machine independent “bytecodes”
 The bytecodes can be run directly by
an interpreter Compiler
 The bytecodes can be converted to
machine code and executed (“Just in
Time (JIT)” compilation). Java “Bytecodes”
 An optimizing interpreter can
dynamically identify program
“hotspots” and create code optimized
for the specific machine/environment. Mac Unix PC
– Optimizing interpreter coming soon
JIT
from SUN.
Bytecode Compiler
Interpreter
Machine Code

7
Java Data Types
• Sizes fully specified by Java standard.
• Java is a very strongly typed language
• Integer types
– int (4 bytes signed)
– short (2 bytes signed)
– long (8 bytes signed) use suffix L (eg 1000000000L)
– byte (1 byte signed)
• Floating-point types
– float (4 bytes) use suffix F (eg 1.28F)
– double( 8 bytes)
Additional Data Types
• char
– Two-byte unicode
– Assignment with ‘ ‘
• e.g. char c = ‘h’;
• boolean
– true or false
e.g. boolean x = true;
if (x){…};
Operators/Control Flow
• Almost exactly like regular ANSI C.
• +, *, -, /, %, ++, --, +=, etc.
• ==, !=, >, < , etc.
• if statements, for loops, while loops, do loops, switch
statements, etc.
• continue, break, return, System.exit(0).
• Read pp 54– in Core Java.
• No need to spend class time going over these.
Scoping
• Braces are used as in C to denote begin/end of
blocks
• Be careful of the following:
int j = 0;
if ( j <1 ){
int k = 2;

}
k = 3; //Error! k inaccessible here
• Declarations do not propogate upwards.
Adding datatypes -- classes
• Java has handful of built-in datatypes just discussed
(int, float, etc.)
• Just like in C, user typically creates own homemade
datatypes to work with particular application (ie
structs and enums).
• In Java these are called classes.
• Many class definitions come as a standard part of the
Java distribution. Most common Example is String
class.
Strings
• Java provides a class definition for a type called
String
• Since the String class is part of the java.lang package,
no special imports are required to use it (like a
header file in C).
• Just like regular datatypes (and like C), variables of
type String are declared as:
String s1;
String s2, s3; //etc.
• Note that String is uppercase. This is the Java
convention for classnames.
Strings
• Initializing a String is painless
s1 = “This is some java String”;
• Note that double quotes are required.
• Memory is allocated dynamically.
• Think of above method as shortcut for more
standard way (assuming s1 has been declared):
s1 = new String(“This is some java String”);
• new operator required to create memory for new
String object.
Anatomy of a Java Program
• Comments
• Package
• Reserved words
• Modifiers
• Statements
• Blocks
• Classes
• Methods
• The main method
15
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 /*, it
scans for the next */ and ignores any text between /*
and */.

16
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 are public,
static, and void. Their use will be introduced later in
the book.

17
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. Modifiers are discussed
in Chapter 6, "Objects and Classes."

18
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 with a semicolon
(;).

19
Writing first program
• To keep things simple our first few programs
will all be written as just a single main
program.
• In java, the file in which your program resides
must contain a .java extension (e.g.
MyFirstProgram.java).
Writing first program
• Then, the program must be wrapped in a class
definition which is the same as the file
basename (MyFirstProgram). Careful, Java is
case-sensitive.
class MyFirstProgram { … }
• Finally, main is defined similar to C, but with a
few more modifiers:
public static void main(String[] args){ … }
These are all required. No shortcuts.
A Simple Application
Example 1.1
//This application program prints Welcome
//to Java!

Public class Welcome {


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

22
Compiling/running first java program
• Create source code file (call it for example
MyFirstProgram.java).
• To compile:
prompt >> javac MyFirstProgram.java
• This produces byte code file named
MyFirstProgram.class
• To run:
prompt >> java MyFirstProgram
Creating and Compiling Programs
Create/Modify Source Code

• On command line
– javac file.java Source Code

Compile Source Code


i.e. javac Welcome.java

If compilation errors

Bytecode

Run Byteode
i.e. java Welcome

Result

If runtime errors or incorrect result

24
Executing Applications
• On command line
– java classname

Bytecode

Java Java Java


Interpreter Interpreter Interpreter
...
on Windows on Linux on Sun Solaris

25
Example
javac Welcome.java

java Welcome

output:...

26
Observations
• .class file is not machine code. It is intermediate form
called Java Byte code. Can run on any platform as
long as platform has a Java Virtual Machine (JVM).
• The second step on previous slide invokes the JVM to
interpret the byte code on the given platform.
• In theory, byte code can be moved to another
platform and be run there without recompiling – this
is the magic of applets.
• Leave off the .class part when invoking the JVM.
Observations
• This is an old-fashioned command-line
program. Java also supports GUI applications
and web-browser hosted programs called
applets.
• After the first couple of weeks we will use
graphical rather than scripting front-ends.
Parsing Strings
• Recall that the args array is an array of Strings. Thus,
to accept key input as integers, float, etc. we must
convert.
• To convert to int, use the Integer.parseInt(String)
function.
Ex. String s1 = “32”;
int j = Integer.parseInt(s1); // j now holds 32
• Converting to double is analogous:
Ex. String s1 = “32”;
double j = Double.parseDouble(s1); // j now holds 32
Parsing Strings
• Note that the conversion methods are just regular
procedural functions. That is, no object was created
in order to call the method. The entity before the ‘.’
is _not_ an object. More on this later.
• What if the String is unparseable? (e.g. “andrew”
rather than “32”).
• Study the Integer and Double classes and look for a
description of the errors that are thrown by the
various methods. Does anything stand out? See
example Looper.java. More on this later.
The Virtual Machine
• Java is both compiled and interpreted
– Source code is compiled into Java bytecode
– Which is then interpreted by the Java Virtual Machine (JVM)
– Therefore bytecode is machine code for the JVM
• Java bytecode can run on any JVM, on any platform
– …including mobile phones and other hand-held devices
• Networking and distribution are core features
– In other languages these are additional APIs
– Makes Java very good for building networked applications,
server side components, etc.
Features of the JVM
• The Garbage Collector
– Java manages memory for you, the developer has no control over the
allocation of memory (unlike in C/C++).
– This is much simpler and more robust (no chance of memory leaks or
corruption)
– Runs in the background and cleans up memory while application is
running
• The Just In Time compiler (JIT)
– Also known as “Hot Spot”
– Continually optimises running code to improve performance
– Can approach the speed of C++ even though its interpreted
Blocks
A pair of braces in a program forms a block that
groups components of a program.

public class Test {


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

33
Classes
The class is the essential Java construct. A class is a
template or blueprint for objects. To program in Java,
you must understand classes and be able to write and
use them. The mystery of the class will continue to be
unveiled throughout this book. For now, though,
understand that a program is defined by using one or
more classes.

34
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 different message.

35
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) {
// Statements;
}

36
The exit Method
Use Exit to terminate the program and stop all
threads.

NOTE: When your program starts, a thread is


spawned to run the program. When the
showMessageDialog is invoked, a separate thread
is spawned to run this method. The thread is not
terminated even you close the dialog box. To
terminate the thread, you have to invoke the exit
method.
37
Object Orientation

38
Introduction to OOP
 Java is an object oriented – Encapsulation
programming language, so some  Variables/Functions can be declared:
rudimentary knowledge of OO – private
terminology is required • only functions within same class
or superclass can access them
– Classes (e.g. “Employee”, “Track”)
(c.f. C++ protected)
 Objects – public
– specific instances of a class (e.g. • any function can access them
“Tony Johnson”, “Track 5”)  Java also implements
 In Java all functions are contained
– static
within classes
• Applies to class not object
 For largely historical reasons functions
are often called methods or member – final
functions • Cannot be overridden by
– Inheritance (aka subclassing) subclass
 e.g. “Associate Director”, “Drift
Chamber Track”

39
What is OOP?
• Modelling real-world objects in software
• Why design applications in this way?
– We naturally classify objects into different types.
– By attempting to do this with software aim to make it
more maintainable, understandable and easier to reuse
• In a conventional application we typically:
– decompose it into a series of functions,
– define data structures that those functions act upon
– there is no relationship between the two other than the
functions act on the data
What is OOP?
• How is OOP different to conventional programming?
– Decompose the application into abstract data types by
identifying some useful entities/abstractions
– An abstract type is made up of a series of behaviours and
the data that those behaviours use.
• Similar to database modelling, only the types have
both behaviour and state (data)
What is an OO program?
• What does an OO program consist of?
– A series of objects that use each others behaviours in order to carry
out some desired functionality
– When one object invokes some behaviour of another it sends it a
message
– In Java terms it invokes a method of the other object
– A method is the implementation of a given behaviour.
• OO programs are intrinsically modular
– Objects are only related by their public behaviour (methods)
– Therefore objects can be swapped in and out as required (e.g. for a
more efficient version)
– This is another advantage of OO systems
Object-Oriented Programming
• Understanding OOP is fundamental to writing good Java
applications
– Improves design of your code
– Improves understanding of the Java APIs
• There are several concepts underlying OOP:
– Abstract Types (Classes)
– Encapsulation (or Information Hiding)
– Aggregation
– Inheritance
– Polymorphism
Objects and Classes
• OO Programming Concepts
• Creating Objects and Object Reference Variables
– Differences between primitive data type and object type
– Automatic garbage collection
• Constructors
• Modifiers (public, private and static)
• Instance and Class Variables and Methods
• Scope of Variables
• Use the this Keyword
• Case Studies (Mortgage class and Count class)
class Employee
Classes Class Declaration
{
public Employee (String n, double s) Constructor
{
name = n;
salary = s;
}
public Employee (String n) Overloaded Constructor
{
name = n;
salary = 0;
}
public void raiseSalary(double byPercent)
{
salary *= 1 + byPercent / 100;
}
public double getSalary() Access Method
{
return salary;
}
private String name;
private double salary;
Private Member Variables
}
Objects
• Objects represent instances of classes
Employee javaExpert = new Employee(“Joe”,100000);
javaExpert.RaiseSalary(10); // Raise salary by 10%
system.out.println(“Salary is” + javaExpert.GetSalary());
• Note that Java uses the keyword new for creation of new objects.
• Unlike C++ there is no delete keyword for the deletion of objects.
– Java handles deletion of objects (and recovery of the memory they occupy)
automatically as soon as there are no longer any references to them.
– This makes writing code much easier, it is “impossible” to create a memory
leak in Java..
– The process of keeping track of when objects are unreferenced and deleting
them is called “garbage collection”. It does impose some processing overhead
which slows down Java programs compared to equivalent programs in C or C+
+.
Inheritance
class Manager Extends Employee Class Declaration
{
public Manager (String n, double s, Employee e) Constructor
{
name = n;
salary = s;
secretary = e;
}
public String GetSecretary() New Access Method
{
return secretary;
}
public void RaiseSalary(double byPercent) Overridden Method
{
double bonus = 10;
super.RaiseSalary(byPercent + bonus);
}
private Employee secretary; New member variables
}
Interfaces
• Interfaces in Java are a replacement • Interfaces
for the concept of “multiple – Objects can implement any number of
inheritance” in C++. interfaces
• Suppose we want to sort managers – Can have hierarchies of interfaces
by the number of employees they – Interfaces cannot have methods
have. – Cleaner but not quite as powerful as
multiple inheritance
Employee – Only way to implement “callbacks” in
Java
Manager
Sortable
 In C++ both Employee and Sortable
can be classes
 In Java one (probably sortable) must
be an “interface”
Abstract Data Types
• Identifying abstract types is part of the modelling/design
process
– The types that are useful to model may vary according to the
individual application
– For example a payroll system might need to know about Departments,
Employees, Managers, Salaries, etc
– An E-Commerce application may need to know about Users, Shopping
Carts, Products, etc
• Object-oriented languages provide a way to define abstract
data types, and then create objects from them
– It’s a template (or ‘cookie cutter’) from which we can create new objects
– For example, a Car class might have attributes of speed, colour, and
behaviours of accelerate, brake, etc
– An individual Car object will have the same behaviours but its own values
assigned to the attributes (e.g. 30mph, Red, etc)
----- ----- -----
----- ----- -----
----- ----- -----
----- ----- -----

" C o n v e n t i o n a l P r o g r a m m in g " - -
F u n c t io n s o r P r o c e d u r e s o p e r a t in g o n in d e p e n d e n t d a t a

" O O P r o g r a m m in g " - -
A b s t r a c t T y p e s c o m b in e d a t a a n d b e h a v io u r
Encapsulation

• The data (state) of an


object is private – it " T h e D o u g h n u t D ia g r a m "
cannot be accessed S h o w in g t h a t a n o b je c t h a s
p r iv a t e s t a t e a n d p u b lic
directly. b e h a v io u r . S t a t e c a n o n ly b e
c h a n g e d b y in v o k in g s o m e
b e h a v io u r
• The state can only be
changed through its P r iv a t e D a t a

behaviour, otherwise
known as its public P u b lic I n t e r f a c e

interface or contract
• This is called
encapsulation
Encapsulation
• Main benefit of encapsulation
– Internal state and processes can be changed independently of the
public interface
– Limits the amount of large-scale changes required to a system
Aggregation
• Aggregation is the ability to create new classes out of existing
classes
– Treating them as building blocks or components
• Aggregation allows reuse of existing code
– “Holy Grail” of software engineering
• Two forms of aggregation
• Whole-Part relationships
– Car is made of Engine, Chassis, Wheels
• Containment relationships
– A Shopping Cart contains several Products
– A List contains several Items
Inheritance
• Inheritance is the ability to define a new class in terms of an
existing class
– The existing class is the parent, base or superclass
– The new class is the child, derived or subclass
• The child class inherits all of the attributes and behaviour of
its parent class
– It can then add new attributes or behaviour
– Or even alter the implementation of existing behaviour
• Inheritance is therefore another form of code reuse
OO Programming Concepts

An object A Circle object

Data Field
data field 1
radius = 5

... State
Method
data field n findArea

method 1

... Behavior

method n
Class and Objects

Circle UML Graphical notation for classes

radius: double UML Graphical notation for fields

UML Graphical notation for methods


findArea(): double

new Circle() new Circle()

circle1: Circle circlen: Circle UML Graphical notation


for objects
radius = 2 ... radius = 5
Class Declaration
class Circle {
double radius = 1.0;

double findArea(){
return radius * radius * 3.14159;
}
}
Declaring Object Reference Variables
ClassName objectReference;

Example:
Circle myCircle;
Creating Objects
objectReference = new ClassName();

Example:
myCircle = new Circle();

The object reference is assigned to the object


reference variable.
Declaring/Creating Objects
in a Single Step
ClassName objectReference = new ClassName();

Example:
Circle myCircle = new Circle();
Differences between variables of
primitive Data types and object types

Primitive type int i = 1 i 1

Object type Circle c c reference

c: Circle
Created using
new Circle() radius = 1
Copying Variables of Primitive Data
Types and Object Types

Primitive type assignment Object type assignment


i=j c1 = c2

Before: After: Before: After:

i 1 i 2 c1 c1

j 2 j 2 c2 c2

c1: Circle c2: Circle

radius = 5 radius = 9
Garbage Collection
Consider, c1=c2. After the assignment
statement c1 = c2, c1 points to the same
object referenced by c2. The object
previously referenced by c1 is no longer
useful. This object is known as garbage.
Garbage is automatically collected by JVM.
Garbage Collection, cont
TIP: If you know that an object is no longer
needed, you can explicitly assign null to a
reference variable for the object. The Java
VM will automatically collect the space if the
object is not referenced by any variable.
Accessing Objects
• Referencing the object’s data:
objectReference.data
myCircle.radius

• Invoking the object’s method:


objectReference.method
myCircle.findArea()
Constructors
Circle(double r) {
radius = r;
} Constructors are a
special kind of
Circle() { methods that are
radius = 1.0; invoked to construct
} objects.

myCircle = new Circle(5.0);


Constructors, cont.
A constructor with no parameters is referred to as
a default constructor.
·       Constructors must have the same name as the
class itself.
·       Constructors do not have a return type—not
even void.
·       Constructors are invoked using the new
operator when an object is created. Constructors
play the role of initializing objects.
Visibility Modifiers and
Accessor Methods
By default, the class, variable, or data can be
accessed by any class in the same package.
 public
The class, data, or method is visible to any class in any
package.
 private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
Instance
Variables, and Methods

Instance variables belong to a specific instance.

Instance methods are invoked by an instance of


the class.
Class Variables, Constants,
and Methods

Class variables are shared by all the instances of the


class.

Class methods are not tied to a specific object.


Class constants are final variables shared by all the
instances of the class.
Class Variables, Constants,
and Methods, cont.

To declare class variables, constants, and methods,


use the static modifier.
Scope of Variables
• The scope of instance and class variables is the
entire class. They can be declared anywhere
inside a class.
• The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must
be declared before it can be used.
The Keyword this
• Use this to refer to the current object.
• Use this to invoke other constructors of the
object.
1d Arrays
• Arrays in Java are dynamic; they are allocated
with the new operator.
• Creating a (1d) array is a two-step process:
int[] x; //declare x to be an array of ints
//x has the value of null right now
x = new int[100]; //allocate 100 ints worth
• At this point the values of x are all zeroes.
• Assignment is then just like C.
1d Arrays
• Note that in Java, unlike C, the compiler will not let
you overrun the bounds of an array. Give it a try.
• Note that you must use the new operator to size the
array. It cannot be done statically as in C. Until this is
done, the array reference has a value of null.
• The array comes with a field called length which
stores the number of elements in the array. Try
printing x.length in the previous example. This is a
simple but nice convenience.
Array of Objects
Circle[] circleArray = new Circle[10];

An array of objects is actually an array of


reference variables. So invoking
circleArray[1].findArea() involves two levels of
referencing as shown in the next figure.
circleArray references to the entire array.
circleArray[1] references to a Circle object.
Array of Objects, cont.
Circle[] circleArray = new Circle[10];

circleArray reference circleArray[0] Circle object 0


circleArray[1]

… Circle object 1

circleArray[9] Circle object 9


Class Abstraction
Class abstraction means to separate class
implementation from the use of the class. The
creator of the class provides a description of the
class and let the user know how the class can be
used. The user of the class does not need to
know how the class is implemented. The detail
of implementation is encapsulated and hidden
from the user.
Thank You

79

You might also like