You are on page 1of 69

JAVA

Course Objectives
Upon

completing the course, you will understand

Create,

compile, and run Java programs


Develop programs using Eclipse
Write simple programs using primitive data types, control
statements, methods, and arrays.
Core Java classes (Swing, exception, multithreading, I/O,
networking, Java Collections Framework)
Develop a GUI interface and Java applets

Chapters - overview
Part I: Fundamentals of Programming
Chapter 1 Introduction to Java
Chapter 2 Primitive Data Types and Operations
Chapter 3 Control Statements
Chapter 4 Methods
Chapter 5 Arrays

Part II: Object-Oriented Programming


Chapter 6 Objects and Classes
Chapter 7 Strings
Chapter 8 Class Inheritance and Interfaces
Chapter 9 Object-Oriented Software Development

Part III: GUI Programming


Chapter 10 Getting Started with GUI Programming
Chapter 11 Creating User Interfaces
Chapter 12 Applets and Advanced GUI

Part IV: Developing Comprehensive Projects


Chapter 13 Exception Handling
Chapter 14 Internationalization
Chapter 15 Multithreading
Chapter 16 Multimedia
Chapter 17 Input and Output
Chapter 18 Networking
Chapter 19 Java Data Structures

Introduction
Evolved into write once run anywhere
Platform independent

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.
For business applications, web services, mission-critical
systems, Transaction processing, databases, distribution.
Java Micro Edition (J2ME).
J2ME can be used to develop applications for mobile devices
such as cell phones.
Very small Java environment for smart cards, pages, phones,
and set-top boxes
Subset of the standard Java libraries aimed at limited size and
processing power

Java Development Kit


javac - The Java Compiler
java - The Java Interpreter
jdb - The Java Debugger
appletviewer -Tool to run the applets
javap - to print the Java byte codes
javadoc - documentation generator
javah - creates C header files

Java IDE Tools


Forte by Sun MicroSystems
Borland JBuilder
Microsoft Visual J++
WebGain Caf
IBM Visual Age for Java
Netbeans (Sun)
JBuilder (Borland)
Eclipse (IBM and others)

Characteristics of Java
Portable - Write Once, Run Anywhere
Security has been well thought through
Robust memory management
Designed for network programming
Multi-threaded (multiple simultaneous tasks)
Dynamic & extensible (loads of libraries)
Classes stored in separate files
Loaded only when needed

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.

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

How to get it running


Type the file and save it as filename.java
To compile:
javac filename.java
To run / execute:
java classname

Note:
Java is CASE SENSITIVE!!
Whitespace is ignored by compiler.
For public class File name has to be the same as class name in
file.

First Application
Welcome.java
public class Welcome
{
public static void main (String args[])
{
System.out.println ("Welcome to Java programming");
} //end main
} //end class

Anatomy of a Java Program


Comments
Package
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method

Comments
When the compiler sees comments, it ignores text
//text
The compiler ignores everything from // to the end of the line
/*text*/
The compiler ignores everything from /* to */.
/**documentation*/
Documentation comments allow you to embed information
about your program into the program itself. You can then use the
javadoc utility program to extract the information and put it into an
HTML file.
Eg: /** * This class calculates CGPA.
* @author Myname
* @version 1.2 */
javadoc filename.java

Variables
all variables must be declared before they can be used
Local variables
Instance variables
Class/static variables

Variables:
Type
Name
Value
Naming:
May contain numbers, underscore, dollar sign, or letters
Can not start with number
Can be any length
Reserved keywords
Case sensitive

Scoping
As in C/C++, scope is determined by the placement of
curly braces {}.
A variable defined within a scope is available only to the
end of that scope.

{ int x = 12;
/* only x available */
{ int q = 96;

This is ok in C/C++ but not in Java.


{ int x = 12;

/* both x and q available */

{ int x = 96; /* illegal */

}
/* only x available */
/* q out of scope */
}

}
}

Methods,argumentsandreturnvalues
Java methods are like C/C++ functions. General case:
returnType methodName ( arg1, arg2, argN) {
methodBody
}
The return keyword exits a method optionally with a value
intstorage(Strings){returns.length()*2;}
booleanflag(){returntrue;}
floatnaturalLogBase(){return2.718f;}
voidnothing(){return;}
voidnothing2(){}

Primitive data types


Byte

-27

27-1

Short

16

-215

215-1

Int

32

-231

231-1

Long

64

Float

32

Double

64

Boolean

Char

16

Strings
Not a primitive class, its actually something called a wrapper class
To find a built in classs method use API documentation.
String is a group of chars
A character has single quotes
char c = h;
A String has double quotes
String s = Hello World;
Method length
int n = s.length;
public class hello{
public static void main (String [] args) {
String s = Hello World\n;
System.out.println(s); //output simple string
} //end main
}//end class hello

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

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."

Statements
A simple

statement is a command terminated by a semi-

colon:
name = Fred;
A block is a compound statement enclosed in curly brackets:
{
name1 = Fred; name2 = Bill;
}
Blocks may contain other blocks

public class Test {


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

Class block
Method block

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

An example of a class
class Person {
String name;
int age;

void birthday ( )
{
age++;
System.out.println (name +
' is now ' + age);
}

Variable
Method

Extending a class
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
public double cx, cy;
// A new constructor method to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle(double r, double x, double y) {
super(r);
// Invoke the constructor of the superclass, Circle()
this.cx = x;
// Initialize the instance field cx
this.cy = y;
// Initialize the instance field cy
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the circle
// Note that it uses the inherited instance field r
public boolean isInside(double x, double y) {
double dx = x - cx, dy = y - cy;
// Distance from center
double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem
return (distance < r);
// Returns true or false
}
}

main Method
The main method provides the control of program flow. when you
execute a class with the Java interpreter, the runtime system starts by
calling the class's main() method. .
The main method looks like this:
public static void main(String[] args) {
// Statements;
}
The main() method is static because they can then be invoked by the
runtime engine without having to create an instance of the class.
The modifiers public and static can be written in either order (public
static or static public), but the convention is to use public static as
shown above. You can name the argument anything you want, but most
programmers choose "args" or "argv
The main method accepts a single argument: an array of elements of
type String

System.out.println:
println is a method in the PrintStream class.
out is a static final variable in System class which is of the type
PrintStream (a built-in class, contains methods to print the different
data values).
out here denotes the reference variable of the type PrintStream
class.
static fields and methods must be accessed by using the class
name, so ( System.out ).
println() is a public method in PrintStream class to print the data
values.

Overloading, overwriting, and shadowing


Overloading occurs when Java can distinguish two procedures
with the same name by examining the number or types of their
parameters.
Shadowing or overriding occurs when two procedures with the
same signature (name, the same number of parameters, and the
same parameter types) are defined in different classes, one of
which is a super class of the other.

Access control
Access to packages
Java offers no control mechanisms for packages.
If you can find and read the package you can access it
Access to classes
All top level classes in package P are accessible anywhere in P
All public top-level classes in P are accessible anywhere
Access to class members (in class C in package P)
Public: accessible anywhere C is accessible
Protected: accessible in P and to any of Cs subclasses
Private: only accessible within class C
Package: only accessible in P (the default)

The static keyword


Java methods and variables can be declared static
These exist independent of any object
This means that a Classs
static methods can be called even if no objects of that class have been
created
static data is shared by all instances (i.e., one value per class instead
of one per instance
class StaticTest {static int i = 47;}
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
// st1.i == st2.I == 47
StaticTest.i++;
// or st1.I++ or st2.I++
// st1.i == st2.I == 48

public class Circle {


// A class field
public static final double PI= 3.14159; // A useful constant
// A class method: just compute a value based on the arguments
public static double radiansToDegrees(double rads) {
return rads * 180 / PI;
}
// An instance field
public double r;
// The radius of the circle
// Two methods which operate on the instance fields of an object
public double area() {
// Compute the area of the circle
return PI * r * r;
}
public double circumference() { // Compute the circumference of the circle
return 2 * PI * r;
}
}

Abstract classes and methods


Abstract vs. concrete classes
Abstract classes can not be instantiated
public abstract class shape { }
An abstract method is a method w/o a body
public abstract double area();
(Only) Abstract classes can have abstract methods
In fact, any class with an abstract method is automatically an
abstract class

public abstract class Shape {


public abstract double area(); // Abstract methods: note
public abstract double circumference();// semicolon instead of body.
abstract
}

Example

class Circle extends Shape {


public static final double PI = 3.14159265358979323846;
protected double r;
// Instance data
public Circle(double r) { this.r = r; }
// Constructor
public double getRadius() { return r; }
// Accessor
public double area() { return PI*r*r; }
// Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}
class Rectangle extends Shape {
protected double w, h;
public Rectangle(double w, double h) {
this.w = w; this.h = h;
}
public double getWidth() { return w; }
public double getHeight() { return h; }
public double area() { return w*h; }
public double circumference() { return 2*(w + h); }
}

// Instance data
// Constructor

//
//
//
//

Accessor method
Another accessor
Implementations of
abstract methods.

class

Displaying Text in a Message Dialog Box


you can use the showMessageDialog method in
the JOptionPane class. JOptionPane is one of the
many predefined classes in the Java system,
which can be reused rather than reinventing the
wheel.

Source

Run

showMessageDialog Method
JOptionPane.showMessageDialog(null,
"WelcometoJava!",
"Example1.2",
JOptionPane.INFORMATION_MESSAGE));

Flow of Control
Java executes one statement after the other in the order
they are written
Many Java statements are flow control statements:
Alternation:
if, if else, switch
Looping:
for, while, do while
Escapes:
break, continue, return

If else
The if else statement evaluates an expression
and performs one action if that evaluation is true
or a different action if it is false.
if (x != oldx) {
System.out.print(x was changed);
}
else {
System.out.print(x is unchanged);
}

Nested if else
if ( myVal > 100 ) {
if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(myVal is in range);
}

else if
Useful for choosing between alternatives:
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed,
execute code block #3
}

A Warning

System.out.print(
i equals
k);
else

CORRECT!
if( i == j ) {
if ( j == k )
System.out.print(
i equals
k);
}
else

System.out.print(
i is not equal
to j);

System.out.print(
i is not equal
to j);//
Correct!

WRONG!
if( i == j )
if ( j == k )

The switch Statement


switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail then
//execute code block #4
break;
}

The for loop


Loop n times
for ( i = 0; i < n; n++ ) {
// this code body will execute n times
// ifrom 0 to n-1
}
Nested for:
for ( j = 0; j < 10; j++ ) {
for ( i = 0; i < 20; i++ ){
// this code body will execute 200 times
}
}

while loops
while(response == 1) {
System.out.print( ID = + userID[n]);
n++;
response = readInt( Enter );
}

What is the minimum number of times the loop


is executed?
What is the maximum number of times?

do { } while loops
do {
System.out.print( ID = + userID[n] );
n++;
response = readInt( Enter );
}while (response == 1);

What is the minimum number of times the loop


is executed?
What is the maximum number of times?

Break
A break statement causes an exit from
the innermost containing while, do, for or
switch statement.
for ( int i = 0; i < maxID, i++ )
{
if ( userID[i] == targetID ) {
index = i;
break;
}
} // program jumps here after break

Continue
Can only be used with while, do or for.
The continue statement causes the innermost loop
to start the next iteration immediately
for ( int i = 0; i < maxID; i++ ) {
if ( userID[i] != -1 ) continue;
System.out.print( UserID + i + : +
userID);
}

Arrays
An array is a list of similar things
An array has a fixed:
name
type
length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution of the
code
myArray has room for 8 elements
the elements are accessed by their index
in Java, array indices start at 0

myArray
=

Declaring Arrays
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory, labelled myArray[0] to
myArray[7]
int myArray[] = new int[8];
combines the two statements in one line

Assigning Values
refer to the array elements by index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};

Iterating Through Arrays


for loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length;i++)
myArray[i] = getsomevalue();
}

Arrays of Objects
So far we have looked at an array of primitive types.
Integers & could also use doubles, floats,
characters
Often want to have an array of objects
Students, Books, Loans
Need to follow 3 steps.
1. Declare the array
private Student studentList[];
this declares studentList
2 .Create the array
studentList = new Student[10];
this sets up 10 spaces in memory that can hold
references to Student objects
3. Create Student objects and add them to the array:
studentList[0] = new Student("Cathy",
"Computing");

Declaring the Array


1. Declare the array
private Student studentList[];
this declares studentList
2 .Create the array
studentList = new Student[10];
this sets up 10 spaces in memory that
can hold references to Student objects
3. Create Student objects and add them to the
array: studentList[0] = new
Student("Cathy", "Computing");

Constructors

Classes should define one or more methods to create or construct


instances of the class
Their name is the same as the class name
note deviation from convention that methods begin with lower case
Constructors are differentiated by the number and types of their
arguments
An example of overloading
If you dont define a constructor, a default one will be created.
Constructors automatically invoke the zero argument constructor of
their superclass when they begin (note that this yields a recursive
process!)

Exceptions
Java exception object.
java.io.Exception
most general one.
Some exception like in Throwable class define methods to get the
message.

System.exit()
One method in java.lang.System
Defined:
public static void exit ( int status)
Terminates currently running Java VM
Status is status code, non zero will usually mean something
abnormal.
Used at end to indicate success, or in middle to signal problems.

Echo.java
drive:\path> type echo.java
// This is the Echo example from the Sun tutorial
class echo {
public static void main(String args[]) {
for (int i=0; i < args.length; i++) {
System.out.println( args[i] );
}
}
}

drive:\path>javac echo.java
drive:\path> java echo this is pretty silly
this
is
pretty
silly

Syntax Notes
No global variables
class variables and methods may be applied to any instance of
an object
methods may have local (private?) variables
No pointers
but complex data objects are referenced
Other parts of Java are borrowed from PL/I, Modula, and other
languages

Useful Resources
Useful resources on the web
Java home (http://java.sun.com)
Articles, Software and document downloads, Tutorials

Java Developer Services


http://developer.java.sun.com
Early access downloads, forums, newsletters, bug database

Javaworld (http://www.javaworld.com)
Java magazine site, good set of articles and tutorials

IBM developerWorks
(http://www.ibm.com/developerWorks)
Technology articles and tutorials

Object class
Super class of all java classes

System.out.println()
println is a method in the PrintStream class.
out is a static final variable in System class which is of the type
PrintStream (a built-in class, contains methods to print the different
data values).
out here denotes the reference variable of the type PrintStream class.
static fields and methods must be accessed by using the class name,
so ( System.out ).
println() is a public method in PrintStream class to print the data
values.
class System
{
public static PrintWriter out;
}
class PrintWriter
{
println()
{
}
}

String Comparison
String strVal= polytechnic
String strVal1= polytechnic
==
Equals

true
true

(String strVal1= strVal)


String strVal= polytechnic
String strVal1= new String(polytechnic)
==
Equals

false
true

String strVal= new String(polytechnic)


String strVal1= new String(polytechnic)
==
Equals

false
true

Abstract
Methods wont have implementation overridden by
sub class
Cant create objects to abstract class
Can create reference
All methods inside abstract class should be abstract
Cannot use final and abstract keyword at a time

final
Method cannot be overridden
Class cannot be inherited
Variable constant
If a class is declared as final, all methods inside classes
are final default

Interfaces
All variables are constant
All methods are abstract and public no concrete
methods
If a class implements a interface, the class should
override all the methods in the interface
A class implements more than one interfaces, it should
give implementation to all methods in all interfaces

static
Class variables / methods
For static variables, only one time memory is allocated
irrespective of creating objects.
Non static variables, memory will be allocated for
every time creating objects for class
Inside static methods cannot access non static members.
Can access only static variables and methods

Singleton class
Create only one object
using private constructor

Static Initializer
Initial value to static member inside static initializer
A class file enter into memory when a object is created
or static method is called.

Instance Initializer
When creating object for the class, instance initializer
will be executed

Constructor
Called when object is created
Provide initial value to data members
Wont return any value
If we dont keep any constructor inside class, run time
system will provide constructor with out args.

You might also like