Basic Java Programming 1
Basic Java Programming 1
Our Agenda
Introduction to OOPS What is Java? The building Blocks of Java-- JDK Java architecture The java.lang. package Basic program constructs Applets v/s Applications
Agenda Continued
The Utilities in util package User interface & Event Handling Exceptions Handling
Introducing to OOPS
You need to familiarize yourself with some terms like Class, Object, Inheritance, Polymorphism etc etc.
The programming style that you use in C where importance is given for functions can be called as structured programming
Class..Objects.
What is a Class?
A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind.
So what is an Object?
An object is a software bundle of related variables and methods. Software objects are often used to model real-world objects you find in everyday life.
Representation of Object
The Object
The object diagrams show that the object's variables make up the center, or nucleus, of the object
Methods surround and hide the object's nucleus from other objects in the program. Packaging an object's variables within the protective custody of its methods is called encapsulation
Somebody calling a method on an object and the method getting executed by making use of current state is invoking the behavior
10
Inheritance
Now you have understood a Class let us look at what is inheritance.
A class inherits state and behavior from its super-class. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs.
11
Inheritance
However, subclasses are not limited to the state and behaviors provided to them by their superclass.
Subclasses can add variables and methods to the ones they inherit from the superclass.
12
Overriding
Subclasses can also override inherited methods and provide specialized implementations for those methods.
You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed.
13
Inheritance
Inheritance offers the following benefits:
Subclasses provide specialized behaviors from the basis of common elements provided by the super class
Programmers can implement super-classes called abstract classes that define "generic" behaviors.
The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented
14
What is Java?
A language developed at Sun Microsystems
A general-purpose language
High-level language
Supported today by most of the big players like IBM, Netscape, Oracle, Inprise etc.
15
Features Of Java
Object-oriented Simple Robust Secure Architecture Neutral / Portable Multithreaded Distributed
16
17
Hello World
We will have the source code first
Type this into any text editor
public class HelloWorldApp { public static void main(String[]args){ System.out.println(Hello World!); } } Save this as HelloWorldApp.java (take care case matters..)
18
Some Rules
The name of the file must always be the name of the public class
You can have only one public class in a file(i.e. in one .java file)
Every stand alone Java program must have a public static void main defined
it is the starting point of the program.
19
To Compile
Open a command prompt
20
To execute
21
22
Platform independence...
Java is a language that is platform independent. A platform is the hardware or software environment in which a program runs Once compiled code will run on any platform without recompiling or any kind of modification. This is made possible by making use of a Java Virtual Machine a.k.a. JVM
23
24
Platform independence
The JVM interprets the .class file to the machine language of the underlying platform .
The underlying platform processes the commands given by the JVM and returns the result back to JVM which displays it for you.
25
With the compiler, first you translate a program into an intermediate language called Java bytecodes-the platform-independent codes interpreted by the interpreter on the Java platform
26
A Diagrammatic Representation
27
JDK
JDK or Java Development Kit is a free software that can be used to write and compile Java programs.
Currently version 1.3 has been released but we will be using version 1.2.2
It has lots of examples and the Standard Java Class Library also called the API
28
JDK
We will be making use of the Classes defined in the standard library by creating objects or inheriting from those classes.
We have tools like javadoc, rmiregistry, appletviewer etc which we may make use of
Copyright 2005, Infosys Technologies Ltd 29
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
30
Simple, Architecture-neutral, Object-oriented, Portable, Distributed, Highperformance, Interpreted, Multithreaded, Robust, Dynamic and Secure
31
Constituents of a Class
Variables or Data Members
Constructors
Functions or Methods
32
Data Types
Strongly typed language
33
34
char
A single character
boolean false
35
References..
Arrays, classes, and interfaces are reference types
The Java programming language does not support the explicit use of addresses like other languages do
36
Reference...
37
Access Specifiers
There are four access specifiers:
public
private
- package
protected
38
39
Modifiers in Java
Access specifiers
static
final
abstract
native
synchronized
Copyright 2005, Infosys Technologies Ltd 40
final Modifier
final modifier has a meaning based on its usage
For variable:
Primitives: read-only Objects: reference is read-only use all upper case letters
41
abstract Modifier
abstract modifier is used to defer an operation
A concrete class can be made abstract by using the modifier for the class
42
Rules to Follow
The following cannot be marked with abstract modifier
Constructors
Static methods
Private methods
43
native Modifier
native modifier is used to indicate implementation of the method in a non-Java language, like C/C++
The library where the method is implemented should be loaded before invoking native methods synchronized Modifier Discussed in the module on threading
44
Variables
The Java programming language has two categories of data types: primitive and reference.
A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value
45
Scope of variables
A variable's scope is the region of a program within which the variable can be referred to by its simple name.
Scope also determines when the system creates and destroys memory for the variable
Scope.
47
Member Variables
A member variable is a member of a class or an object.
48
Local Variables
You declare local variables within a block of code
The scope of a local variable extends from its declaration to the end of the code block in which it was declared
49
Parameter Scope
Parameters are formal arguments to methods or constructors and are used to pass values into methods and constructors. The scope of a parameter is the entire method or constructor for which it is a parameter. Exception-handler parameters are similar to parameters but are arguments to an exception handler rather than to a method or a constructor
50
Final variables
You can declare a variable in any scope to be final . The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other programming languages. To declare a final variable, use the final keyword in the variable declaration before the type: final int Var = 0;
51
Visibility
Visibility is set with an access modifier Applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. The access modifiers are public, protected, private and default(when none specified) The default scope is Package.
52
Public-Private
Public variables and methods are those which can be accessed from any where i.e. From the class, outside the class and outside the package.
Private variables are those which can be accessed only within the class.
53
Protected
Protected variables re those which are visible only inside the class and the children classes of that class.
If your class extends a base class then your derived class will be able to access the variables and methods of the base class that are declared as protected ( and public of course.)
54
Default Scope
The default Scope i.e. if you dont specify any access modifiers the scope is package scope.
It means that within the package the class is it will be accessible but outside the package it is not accessible.
55
Friendly
Protected Public
Yes No No No No
The syntax...
Java follows exactly the syntax of C with some minor differences.
57
Interfaces
( Inheritance in Java ]
Class A
Class A
Class B
Class B
Interface
Following are the code for the diagram in the slide shown before : Class ClassB Bextends extendsA A {{ }} Class ClassC Cextends extendsB B {{ }} Class Class C C extends extendsA A, ,B B {{ }}
Inter A
Inter B
Inter C Class E can inherit from interface A, B and C in the following manner : Class Class EE implements implements A, A,B, B,C C {{ . .. .. .. .. .. .. .. .. .. .. .. .; ; }}
INTERFACE
Class E
60
Class A
E X T E N D S
inter B
Inter C Class E can inherit from classes A,& implements B and C in another way as shown here :
INTERFACE
Class E
61
public publicinterface interfacemyinterface myinterface {{ public publicvoid voidadd(int add(intx, x,int inty) y); ; }}
When the code for interface is executed as given below : javac d c:\JavaProgs\ myinterface . java
Copyright 2005, Infosys Technologies Ltd 62
Interfaces Contd
Comparable to a pure abstract class
64
Just think of Writing the code from the scratch, each time you create an application Youll end up spending your precious time and energy and finally land up with a Huge code accumulated before you.
Copyright 2005, Infosys Technologies Ltd 65
Reusing The Existing Code Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency.
A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program.
66
Concept of Packages In Java, the codes which can be reused by other programs is put into a Package. A Package is a collection of classes, interfaces and/or other packages. Packages are interfaces essentially a packag es means of classe organizing s classes together Packa as groups. ge
Copyright 2005, Infosys Technologies Ltd 67
Features of Packages
Packages are useful for the following purposes: Packages allow you to organize your classes into smaller units ( such as folders ) and make it easy to locate and use the appropriate class file. It helps to avoid naming conflicts. When you are working with a number of classes, it becomes difficult to decide on names of the classes & methods. At times you would want to use the same name, which belongs to an another class. Package, basically hides the classes and avoids conflicts in names. Packages allow you to protect your classes, data and methods in a larger way than on a class-to-class basis. Package names can be used to identify your classes.
68
Import
To find the area of a circle on the front face of the cube, we need not write a code explicitly to find the area of the circle We will import the package into our program and make use of the area method already present in the package circle.
69
Importing a Package
In Java, the Packages (where the required method is already created) can be imported into any program where the method is to be used. We can import a Package in the following manner : import package_name . class_name ; Suppose you wish to use a class say My_Class whose location is as follows :
My_Package
My_Sub_Package
My_Class
Creating a Package
In Java Packages are created in the following manner : Package package_name ; Method to add( ) package packagemypackage mypackage;; public publicclass classcalculate calculate { { public publicint intadd(int add(intx, x,int int y) y) { { return( return(x x+ +y y));; } } } } mypackage
Copyright 2005, Infosys Technologies Ltd 71
gs JavaPro
kage c a p y m
c Cal
ula
Cla te .
ss
72
java java. .lang lang java java. .io io java java. .util util
java .lang Contains classes that form the basis of the design of the programming language of Java java .io The use of streams for all input output operations in Java is handled by the java.io package
java . util Contains classes and interfaces that provide additional utility but may not be always vital.
73
java.lang package
One of the most important classes defined in this package is Object and it represents the root of the java class hierarchy. This package also holds the wrapper classes such as Boolean, Characters, Integer, Long, Float and Double. Many a times it is necessary to treat the non-object primitive datatypes of int, char, etc. as objects. Thus Java defines wrapper classes that enable us to treat even primitive data types as objects.These wrapper classes are found in the package java.lang. Other classes found in this package are : Math which provides commonly used mathematical functions like sine, cosine and square root. String & String Buffer Encapsulate commonly used operations on character strings.
74
int abs(int i) -- returns the absolute value of I long abs(long l) -- returns the absolute value of l float abs(float f) -- returns the absolute value of f double abs(double d) -- returns the absolute value of d double ceil(double d) -- returns as a double the smallest integer that is not less than d double floor(double d) --- returns as a double the largest integer
75
java.io package
This package has two very important abstract classes : Input Stream This class defines the basic behavior required for input. Output stream This class is the basis of all the classes that deal with output operations in Java.
Since these are abstract classes, they cannot be used directly but must be inherited, so that the abstract methods can be implemented. All I/O stream classes are derived from either of these classes.
76
java.io package
The classes derived in Inputstream and Outputstream can only read from or write to the respective files. We cannot use the same class for both reading and writing operations. An exception to this rule is the class RandomAccessFile. This is the class used to handle files that allow random access and is capable of mixed reading and writing operations on a file. There are two additional interface to this package : Data input Data output These classes are used to transfer data other than bytes or characters
77
Java.util package
One of the most important package in this package is the class Date, which can be used to represent or manipulate date and time information. In addition, the class also enable us to account for time zones . Java helps us to change the size of an array which is usually fixed, by making use of the class Vector. This class also enable us to add, remove and search for items in the array.
78
LEG AL
ILLEGA L
package mypackage ;
79
java.io
java.applet
java.awt java.util
java.net
Arrays
An array is a data structure which defines an ordered collection of a fixed number of homogeneous data elements The size of an array is fixed and cannot increase to accommodate more elements In Java, array are objects and can be of primitive data types or reference types All elements in the array must be of the same data type
82
Arrays
Declaring Arrays Variables <elementType>[] <arrayName>; or <elementType> <arrayName>[]; where <elementType> can be any primitive data type or reference type Example: int IntArray[]; Pizza[] mediumPizza, largePizza;
83
Arrays
Constructing an Array
<arrayName> = new <elementType>[<noOfElements>];
Example:
IntArray = new int[10]; mediumPizza = new Pizza[5]; largePizza = new Pizza[2];
84
Arrays
Initializing an Array
<elementType>[] <arayName> = {<arrayInitializerCode>};
Example:
int IntArray[] = {1, 2, 3, 4}; char charArray[] = {a, b, c}; Object obj[] = {new Pizza(), new Pizza()}; String pets[] = {cats, dogs};
85
IO Facilities in Java
Overview
IO Streams in Java Understanding some fundamental streams Creating streams for required functionality Some advanced streams
87
Streams
Streams are channels of communication Provide a good abstraction between the source and destination Could also act as a shield to lower transport implementation Most of Javas IO is based on streams
Byte-oriented streams Character-oriented streams
88
Concatenating Streams
Data InputStream
File InputStream
File Object
89
Streams
A stream can be thought of as a Conduit (pipe) for data between a source and the destination. Two types of Streams are 1. Low level streams 2. High level streams
91
Streams which carries bytes are called low level streams. Examples are FileInputStream and FileOutputStream.
Streams which carries primitive data types are called high level streams. Examples are DataInputStream and DataOutputStream.
92
InputStreams are used for reading the data from the source.
93
int,float,double.
Java program
Destination bytes
FileOutputStream bytes
DataOutputStream
94
95
Filter Streams
Filter contents as they pass through the stream Filters can be concatenated as seen before Some filter streams
Buffered Streams LineNumberInputStream PushBackInputStream PrintStream
96
Conversion Streams
InputStreamReader: bridge from byte streams to character streams
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
97
Review
Streams are the basis of Javas IO Pre-defined streams for many situations Streams need to be concatenated Conversion streams available for byte to character and vice-versa conversion
98
String class
A string is a collection of characters Has equals( ) method that should be used to compare the actual string values Lot of other methods are available which are for the manipulation of characters of the string
99
public class Stringcomparison { public static void main(String args[]) { String ss1=new String("Rafiq"); String ss2=new String("Rafiq"); String s1="Rafiq"; String s2="Rafiq"; System.out.println(" == comparison for StringObjects: "+(ss1==ss2)); System.out.println(" == comparison for StringLiterals: "+(s1==s2)); System.out.println(" equals( ) comparison for StringObjects: "+(ss1.equals(ss2))); System.out.println(" equals( ) comparison for StringLiterals: "+(s1.equals(s2))); } }
Copyright 2005, Infosys Technologies Ltd 100
class checkstring { public static void main(String args[]){ String str="HELLO guys & girls"; System.out.println("The String is:"+str); System.out.println("Length of the String is:"+str.length()); System.out.println("Character at specified position:"+str.charAt(4)); System.out.println("substring of the String is:"+str.substring(6,10)); System.out.println("Index of the specified character:"+str.indexOf("g")); System.out.println("conversion to uppercase:"+str.toUpperCase()); System.out.println("conversion to uppercase:"+str.toLowerCase()); } }
101
String Buffer
The prime difference between String & StringBuffer class is that the stringBuffer represents a string that can be dynamically modified. StringBuffers capacity could be dynamically increased eventhough its capacity is specified in the run time. Constructors StringBuffer() StringBuffer(int capacity) StringBuffer(String str) Methods int length() int capacity() void setLength(int len)
102
String Buffer
char charAt(int where) void setCharAt(int where, char ch) StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) StringBuffer insert(int index,String str) StringBuffer insert(int index,char ch) StringBuffer insert(int index,Object obj) StringBuffer reverse()
Copyright 2005, Infosys Technologies Ltd 103
java.util Package
Has utility classes like Date Properties HashTable Vector e.t.c
104
Vector
Vector( ) Vector(int size) Vector(int size, int incr) The following are few Vector methods: final void addElement(Object element) final int capacity() final boolean contains(Object element) final Object elementAt(int index) final Object firstElement()
105
Vector
final void insertElementAt(Object element, int index) final Object lastElement() final boolean removeElement(Object element) final void removeElementAt(int index) final int size()
106
Date
import java.util.Date; class DateDemo{ public static void main(String args[]) { //Instantiating a Date Object Date date=new Date(); System.out.println("current date is"+date); System.out.println("current day is"+date.getDay()); System.out.println("current month is"+date.getMonth()); System.out.println("current Year is"+date.getYear()); long msec=date.getTime(); System.out.println("Milliseconds since Jan. 1,1970 ="+msec); } }
Copyright 2005, Infosys Technologies Ltd 107
1. 2. 3.
Standalone program. Applications can run by itself. Since it can be run independently, so utilities like event handling, user interface, etc. should be explicitly written by the programmer.
1. 2.
Used for Internet programming. Applications cannot run by itself and requires a Browser software to run it.
3.
Since applets runs inside the Browser, it enjoys all the inbuilt facilities of some event handling.
Applet
What is an applet? A small Java program that runs on a Browser The applet runs on JVM embedded in the browser
import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }
109
Applet Born
Initialization state
Applet Working
stop( )
Applet Destroyed
110
111
112
Applet...
You need to override only the methods you want, the others are redirected to the base class. If you need to repaint the applet display you can do it by calling repaint().(You are not supposed to call directlypublic void paint(Graphics g))
Why?????????????
113
We used import statements We inherited from Applet class We did some overriding We called some behavior We learnt to embed Java programs in HTML
114
Exception Handling
Errors indicate serious problems and abnormal conditions that most applications should not try to handle
116
Overview
What is an Exception?
117
Exceptions
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
The exception object contains information about the exception, including its type and the state of the program when the error occurred.
118
Exceptions
The Java programming language provides a mechanism known as exceptions to help programs report and handle errors.
It means that the normal flow of the program is interrupted and that the runtime attempts to find an exception handler--a block of code that can handle a particular type of error
119
Exceptions
The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program.
Java enforces exceptions to be handled by the programmer, resulting in compile errors otherwise
120
statement(s)
122
When an exception, it is executed after the handler or before propagation as the case may be
123
Throwing Exceptions
Exceptions in Java are compulsorily of type Throwable Use the throw clause to throw an exception
124
125
126
Throws-Throw
These are two key words that you may use The Throws keyword is used along with the declaration of a method that can throw an exception. This makes it mandatory for anyone calling the method to have it in try block. Else the compiler will give an error.
127
Throw
All Java methods use the throw statement to throw an exception.
If you attempt to throw an object that is not throwable, the compiler refuses to compile your program
128
Throw
It is used as follows- in a case where you want to throw an exception
129
The Hierarchy
130
Errors
When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws an Error.
Typical Java programs should not catch Errors. In addition, it's unlikely that typical Java programs will ever throw Errors either.
131
133
134
135
AWT hierarchy
Component Button Canvas Checkbox Choice Container Panel ScrollPane Window Dialog FileDialog Frame Label List Scrollbar TestComponent TextArea TextField
136
137
Frame : It is a fully functioning window with its own title and icons. Other containers: Panel : A pure container and not a window in itself. Sole purpose is to organize the components on to a window. Dialog : pop-up window that pops out when an error message has to be displayed. Not a fully functioning window like the Frame.