Java Basic
Java Basic
Java Basic
LECTURER
DEPARTMENT OF CSE
A LOOK PROCEDURE-ORIENTED
PROGRAMMING
High level languages such as COBOL,FORTRAN and C
Characteristics
Emphasis is on doing things(algorithems)
Large programs are divided into smaller programs
known as functions.
Most of the function share global data
Data move openly around the system from function to
function
Functions transforms data from one form to another
Employs top-down approach in program design
OBJECT-ORIENTED PROGRAMMING
PARADIGM
Some of the striking features of object-oriented programming are:
Emphasis is on data rather than procedure
Programs are divided in to what are known as objects
Data structures are designed such that they characterize the
objects
Functions that operate on the data of an object are tied together in
the data structure
Data is hidden and cannot be accessed by external functions
Objects may communicate with each other through functions
New data and functions can be easily added whenever necessary
Follows bottom-up approach in program design
PROGRAMMING
Objects
Classes
Data Abstraction
Data Encapsulations
Inheritance
Polymorphism
Dynamic buinding
Message passing
Java - An Introduction
Java - The new programming language
developed by Sun Microsystems in 1991.
Originally called Oak by James Gosling, one of
the inventors of the Java Language.
Originally created for consumer electronics
(TV, VCR, Freeze, Washing Machine, Mobile
Phone).
Features of JAVA
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
Java is Compiled and Interpreted
Hardware and
Programmer
Operating System
JAVA COMPILER
(translator)
JAVA INTERPRETER
(one for each different system)
C++
C Java
Java better than C++ ?
No Typedefs, Defines, or Preprocessor
No Global Variables
No Goto statements
No Pointers
No Unsafe Structures
No Multiple Inheritance
No Operator Overloading
Java Applications
We can develop two types of Java programs:
Stand-alone applications
Web applications (applets)
Applications v/s Applets
Different ways to run a Java executable
are:
Application- A stand-alone program that can be invoked from
command line . A program that has a “main”
main method
Text Editor
Java Source
javadoc HTML Files
Code
javac
java jdb
Outout
Java Program Structure
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Declarations
import java.lang.Math;
class SquareRoot
{
public static void main(String args [])
{
double x = 4;
double y;
y = Math.sqrt(x);
System.out.println("y= "+y);
}
}
Basic Data Types
Types
boolean either true or false
char 16 bit Unicode 1.1
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)
long 64-bit integer (singed)
float 32-bit floating point (IEEE 754-1985)
double 64-bit floating point (IEEE 754-1985)
String (class for manipulating strings)
Java uses Unicode to represent characters
internally
Variables
e.g. int x = 1;
Variables can be defined just before their usage (unlike C)
e.g., for( int i = 0; i < 10; i++)
Constants
do {
squared = lo * lo; // Calculate square
System.out.println(squared);
lo = lo + 1; /* Compute the new lo value */
} while (squared <= MAX);
Control Flow - Examples
if-else loop
if ( i < 10) {
System.out.println(“i is less than 10” );
}
else {
System.out.println(“i is greater than or equal to 10”);
}
Control Flow - Examples
switch statement
switch (c) {
case ‘a’:
System.out.println (“ The character is ‘a’” );
break;
case ‘b’;
System.out.println (“ The character is ‘b’” );
break;
default;
System.out.println (“ The character is not ‘a’ or
‘b’” );
break;
}
Command Line Arguments
Command line arguments provide one of the ways for supplying input data at the
time of execution instead of including them in the program. They are supplied as
parameters to the main() method:
public static void main(String args[])
“args” is declared of an array of strings (aka string objects).
args[0] is the first parameter, args[1] is the 2nd argument and so on
The number of arguments passed identified by:
args.length
E.g. count = args.length;
Example Invocation and values:
java MyProgram hello melbourne
args.length will be 2
args[0] will be “hello” and args[1] will be “melborune”
Printing command line arguments
// ComLineTest.java: testing command line arguments
class ComLineTest
{
public static void main(String args[])
{
int count, i = 0;
String myString;
count = args.length;
System.out.println("Number of Arguments = "+count);
while( i < count )
{
myString = args[i];
i = i + 1;
System.out.println(i + " : " + "Java is "+myString+ " !");
}
}
}
Circle
centre
radius
circumference()
area()
Classes
A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
The basic syntax for a class definition:
Circle aCircle;
Circle bCircle;
Class of Circle cont.
aCircle, bCircle simply refers to a Circle object,
not an object itself.
aCircle bCircle
null null
bCircle = aCircle;
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
Automatic garbage collection
Q
The object does not have a reference
and cannot be used in future.
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
double area;
aCircle.r = 1.0;
area = aCircle.area();
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
Invoking:
There is NO explicit invocation statement
needed: When the object creation statement is
executed, the constructor method will be
executed automatically.
Defining a Constructor: Example
// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
Trace counter value at each statement and What is the
output ?
class MyClass {
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
counter1.increase();
int b = counter1.getCounterIndex();
if ( a > b )
counter1.increase();
else
counter1.decrease();
System.out.println(counter1.getCounterIndex());
}
}
A Counter with User Supplied Initial Value ?
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
{
x = centreX;
y = centreY;
r = radius;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Constructors initialise Objects
Recall the following OLD Code Segment:
circleA = new Circle(10, 12, 20) circleB = new Circle(10) circleC = new Circle()
int a = 10;
int b = 20;
nCircles = Circle.numCircles;
Static Variables - Example
Using static variables:
// Constructors...
Circle (double x, double y, double r){
this.x = x;
this.y = y;
this.r = r;
numCircles++;
}
}
Class Variables - Example
Using static variables:
numCircles
Instance Vs Static Variables
class MyClass {
public static void main(String args[])
{
String s1 = "Melbourne";
String s2 = "Sydney";
Directly accessed using ClassName (NO Objects)
String s3 = "Adelaide";
int a = 10;
int b = 20;
Child
Inheritance: Introduction
The inheritance allows subclasses to inherit all
properties (variables and methods) of their parent
classes. The different forms of inheritance are:
Single inheritance (only one super class)
Multiple inheritance (several super classes)
Hierarchical inheritance (one super class, many sub classes)
Multi-Level inheritance (derived from a derived class)
Hybrid inheritance (more than two types)
Multi-path inheritance (inheritance of some properties from two
sources).
Forms of Inheritance
A A B A
B C B C D
A A
A
B c B c
B
C D D
}
Subclasses & Constructors
default constructor
for Circle class is
called
class A {
int j = 1;
int f( ) { return j; }
}
class B extends A {
int j = 2;
int f( ) {
return j; }
}
Overriding Methods
class override_test {
public static void main(String args[]) {
B b = new B();
System.out.println(b.j); // refers to B.j prints 2
System.out.println(b.f()); // refers to B.f prints 2
Object Type Casting
A a = (A) b;
System.out.println(a.j); // now refers to a.j prints 1
System.out.println(a.f()); // overridden method still refers to B.f() prints 2 !
}
}
Person
name: String
sex: char
age: int
Display ( ) : void
Subclass
class. Superclass
class
Student
RollNo: int
Branch: String
Display() : void
Person class: Parent class
// Student.java: Student inheriting properties of person class
class person
{
private String name;
protected char sex; // note protected
public int age;
person()
{
name = null;
sex = 'U'; // unknown
age = 0;
}
person(String name, char sex, int age)
{
this.name = name;
this.sex = sex;
this.age = age;
}
String getName()
{
return name;
}
void Display()
{
System.out.println("Name = "+name);
System.out.println("Sex = "+sex);
System.out.println("Age = "+age);
}
}
Student class: Derived class
class student extends person
{
private int RollNo;
String branch;
student(String name, char sex, int age, int RollNo, String branch)
{
super(name, sex, age); // calls parent class's constructor with 3 arguments
this.RollNo = RollNo;
this.branch = branch;
}
void Display() // Method Overriding
{
System.out.println("Roll No = "+RollNo);
System.out.println("Name = "+getName());
System.out.println("Sex = "+sex);
System.out.println("Age = "+age);
System.out.println("Branch = "+branch);
}
void TestMethod() // test what is valid to access
{
// name = "Mark"; Error: name is private
sex = 'M';
RollNo = 20;
}
}
System.out.println("Student 1 Details...");
s1.Display();
System.out.println("Student 2 Details...");
s2.Display();
}
}
Parent
Inherited
capability
Child
Final Members: A way for Preventing Overriding of
Members in Subclasses
Shape
Circle Rectangle
The Shape Abstract Class
public abstract class Shape {
public abstract double area();
public void move() { // non-abstract method
// implementation
}
}
<<Interface>>
Speaker
speak()
interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – only method body
}
Example:
interface Speaker {
public void speak( );
}
Implementing Interfaces
Interfaces are used like super-classes who
properties are inherited by classes. This is
achieved by creating a class that implements
the given interface as follows:
Student Sports
extends
Exam
implements
extends
Results
Software Implementation
class Student
{
// student no and access methods
}
interface Sport
{
// sports grace marks (say 5 marks) and abstract methods
}
class Exam extends Student
{
// example marks (test1 and test 2 marks) and access methods
}
class Results extends Exam implements Sport
{
// implementation of abstract methods of Sport interface
// other methods to compute total marks = test1+test2+sports_grace_marks;
// other display or final results access methods
}
Interfaces and Software Engineering
Interfaces, like abstract classes and methods, provide templates
of behaviour that other classes are expected to implement.
Separates out a design hierarchy from implementation hierarchy.
This allows software designers to enforce/pass common/standard
syntax for programmers implementing different classes.
Pass method descriptions, not implementation
Java allows for inheritance from only a single superclass.
Interfaces allow for class mixing.
Classes implement interfaces.
A Summary of OOP and Java Concepts
Learned So Far
Summary
Class is a collection of data and methods that operate
on that data
An object is a particular instance of a class
Object members accessed with the ‘dot’ (Class.v)
Instance variables occur in each instance of a class
Class variables associated with a class
Objects created with the new keyword
Summary
Objects are not explicitly ‘freed’ or destroyed. Java
automatically reclaims unused objects.
Java provides a default constructor if none defined.
A class may inherit the non-private methods and
variables of another class by subclassing, declaring
that class in its extends clause.
java.lang.Object is the default superclass for a class. It
is the root of the Java hierarchy.
Summary
Method overloading is the practice of defining multiple
methods which have the same name, but different
argument lists
Method overriding occurs when a class redefines a
method inherited from its superclass
static, private, and final methods cannot be overridden
From a subclass, you can explicitly invoke an
overridden method of the superclass with the super
keyword.
Summary
Data and methods may be hidden or encapsulated
within a class by specifying the private or protected
visibility modifiers.
An abstract method has no method body. An abstract
class contains abstract methods.
An interface is a collection of abstract methods and
constants. A class implements an interface by
declaring it in its implements clause, and providing a
method body for each abstract method.
Exceptions:
An OO Way for Handling Errors
Introduction
Rarely does a program runs successfully at its very
first attempt.
It is common to make mistakes while developing as
well as typing a program.
Such mistakes are categorised as:
syntax errors - compilation errors.
semantic errors– leads to programs producing unexpected
outputs.
runtime errors – most often lead to abnormal termination of
programs or even cause the system to crash.
Common Runtime Errors
Dividing a number by zero.
Accessing an element that is out of bounds of an array.
Trying to store incompatible data elements.
Using negative value as array size.
Trying to convert from string data to a specific data value (e.g.,
converting string “abc” to integer value).
File errors:
opening a file in “read mode” that does not exist or no read
permission
Opening a file in “write/update mode” which has “read only”
permission.
Corrupting memory: - common with pointers
Any more ….
Without Error Handling – Example 1
class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
Program does not reach here
System.out.println(“Result is “ + a/b);
System.out.println(“Program reached this line”);
}
}
No compilation errors. While running it reports an error and stops without
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
Traditional way of Error Handling -
Example 2
class WithErrorHandling{
public static void main(String[] args){
int a,b;
a = 7; b = 0;
if (b != 0){
System.out.println(“Result is “ + a/b);
}
Program reaches here
else{
System.out.println(“ B is zero);
}
System.out.println(“Program is complete”);
}
}
Error Handling
try Block
Throws
exception
Object
catch Block
Statements that
handle the exception
Syntax of Exception Handling Code
…
…
try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
With Exception Handling - Example 3
class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
Program Reaches here
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Finding a Sum of Integer Values Passed as Command
Line Parameters
// ComLineSum.java: adding command line parameters
class ComLineSum
{
public static void main(String args[])
{
int InvalidCount = 0;
int number, sum = 0;
class WithExceptionCatchThrow{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program Does Not
reach here
catch(ArithmeticException e){
when exception occurs System.out.println(“ B is zero);
throw e;
}
System.out.println(“Program is complete”);
}
}
With Exception Handling - Example 5
class WithExceptionCatchThrowFinally{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program reaches here catch(ArithmeticException e){
System.out.println(“ B is zero);
throw e;
}
finally{
System.out.println(“Program is complete”);
}
}
}
User-Defined Exceptions
Problem Statement :
Consider the example of the Circle class
Circle class had the following constructor
public Circle(double centreX, double centreY,
double radius){
x = centreX; y = centreY; r = radius;
}
import java.lang.Exception;
class InvalidRadiusException extends Exception {
private double r;
class Circle {
double x, y, r;
class CircleTest {
public static void main(String[] args){
try{
Circle c1 = new Circle(10, 10, -1);
System.out.println("Circle created");
}
catch(InvalidRadiusException e)
{
e.printError();
}
}
}
User-Defined Exceptions in standard format
class MyException extends Exception
{
MyException(String message)
{
super(message); // pass to superclass if parameter is not handled by used defined exception
}
}
class TestMyException {
…
try {
..
throw new MyException(“This is error message”);
}
catch(MyException e)
{
System.out.println(“Message is: “+e.getMessage());
}
}
}
java
lang “java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt
Graphics awt Package containing
Font classes
Classes containing
Image
methods
…
Accessing Classes from Packages
There are two ways of accessing the classes stored in packages:
Using fully qualified class name
java.lang.Math.sqrt(x);
Import package and use class name directly.
import java.lang.Math
Math.sqrt(x);
Selected or all classes in packages can be imported:
import package.class;
import package.*;
Implicit in all programs: import java.lang.*;
package statement(s) must appear first
Creating Packages
package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB {
// class body
}
Using a Package
Within the current directory (“abc”) store the
following code in a file named “ClassX.java”
import myPackage.ClassA;
package secondPackage;
public class ClassC {
// class body
public void display()
{
System.out.println("Hello, I am ClassC");
}
}
Using a Package
Within the current directory (“abc”) store the
following code in a file named “ClassX.java”
import myPackage.ClassA;
import secondPackage.ClassC;
public class ClassY
{
public static void main(String args[])
{
ClassA objA = new ClassA();
ClassC objC = new ClassC();
objA.display();
objC.display();
}
}
Output
[raj@mundroo] package % java ClassY
Hello, I am ClassA
Hello, I am ClassC
[raj@mundroo] package %
Protection and Packages
All classes (or interfaces) accessible to all others in the
same package.
Class declared public in one package is accessible
within another. Non-public class is not
Members of a class are accessible from a difference
class, as long as they are not private
protected members of a class in a package are
accessible to subclasses in a different class
Visibility - Revisited
Public keyword applied to a class, makes it
available/visible everywhere. Applied to a method or
variable, completely visible.
Private fields or methods for a class only visible within
that class. Private members are not visible within
subclasses, and are not inherited.
Protected members of a class are visible within the
class, subclasses and also within all classes that are in
the same package as that class.
Visibility Modifiers
Non-subclass Yes No No No
different package
Adding a Class to a Package
Consider an existing package that contains a class
called “Teacher”:
package pack1;
public class Teacher
{
// class body
}
import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}
Summary
Packages allow grouping of related classes
into a single united.
Packages are organised in hierarchical
structure.
Packages handle name classing issues.
Packages can be accessed or inherited without
actual copy of code to each program.