You are on page 1of 91

Programming in Java

Fundamental Concepts

Java Programming K.S.Mahara 1


san
Introduction

• Object Oriented Programming Language from Sun


Microsystems
• Started out in 1991 as Project Green, OS
development for consumer electronic devices
• James Gosling headed the project team
• First named as OAK and later changed as Java
(Copyright issue)
• It is simple and platform independent
• Can be used to develop applications that run on
the Internet
Java Programming K.S.Mahara 2
san
Features of Java

• It's Simple
• It's Object Oriented
• It's Safe
• It's Secure
• It's Portable
• It's Fast (potentially)
• It's Multi-threaded
• It is platform independent

Java Programming K.S.Mahara 3


san
C / C++ Compilation Process
• Compilers use the traditional compile/link/run
strategy

Java Programming K.S.Mahara 4


san
Java Uses a Virtual Machine
• Virtual machines use an intermediate byte code rather than native object
code

Java Programming K.S.Mahara 5


san
The Java Development Kit (JDK)

• Collection of tools that aid a java developer


• JDK includes
– Compiler (javac)
– Interpreter (java)
– Debugger (jdb)
– Bytecode disassembler (javap)
– Applet viewer (appletviewer)
– Documentation tool (javadoc)
– And more

Java Programming K.S.Mahara 6


san
Java Language Basics

• Tokens (Identifiers, Keywords, Literals, Operands &


Separators)
• Data Types (Byte, Short, Integer, Long, Float, Double,
Boolean & Char)
• Operators
• Flow Controls (conditional, looping & exception flow
controls)
• Conversions

Java Programming K.S.Mahara 7


san
Java Language Tokens

• Keywords: Words used as a part of the language


definitions (ex. Abstract, int, null, catch, etc) Total : 56
• Identifiers: Names chosen by the programmer to
represent classes, constants, objects, etc.,
• Literals: Used to enter explicit values are
entered for variables & constants. ( “Hello”, 414)
• Separators:Symbols to indicate grouping. (() {}[];)
• Operators: Arithmetic, Assignment, Increment &
Decrement, Comparison, etc

Java Programming K.S.Mahara 8


san
Data Types
• It declares the type of information to be stored in a variable
• 8 primitive data types are available in java
• Byte, short, int, long, float, double, char & boolean
• Bits Occupied:
– Byte 8 - Short 16
– Int 32 - Long 64
– Float 32 - Double 64
– Boolean 8 - Char 16

Java Programming K.S.Mahara 9


san
Operators

Special symbols used in expressions

• Arithmetic Operators ( + - * / %)
• Assignment Operators (+= -= *= /= %= =)
• Increment & Decrement Operators ( ++ -- :
Pre & Post)
• Logical Operators [AND (& or &&), OR (| or ||), XOR (^)
NOT (!) ]
• Comparison Operators [ == != < > <= >= ]
• Bitwise Operators ( AND: & OR : | XOR : ^ Compliment: ~ )

Java Programming K.S.Mahara 10


san
Flow Controls
- Conditional if .. else
• if else construct : Simplest One
• Syntax
– if (Condition) { Statement Block}
– if (condition) {stmt1 / stmt set 1} else {stmt2 /stmt set 2}
– if statements can be nested
– Ternary Operator (?) : Alternative for if else construct
• Examples
– if (age < 17) { dishes = 2}
– if (sales >= target) {bonus = 150} else {bonus = 50}
– if (sales >= target) {bonus = 150; leave = 3} else {bonus = 50; leave = 1}
– a= x<y?x:y;

Java Programming K.S.Mahara 11


san
Flow Controls
- Conditional switch()

• Transfers control based on the value of a single


variable or expression
• Syntax :
– switch (v) { case <v1> : stmts1; break;
case<v2> : stmts2; break;
default: stmtsn; break; }
• Example: switch (x) { case 1 : y = 2; break;
case2 : y = 3; break;
default: y = 10; break; }

Java Programming K.S.Mahara 12


san
Flow Controls
- Looping
• Indeterminate Loops: Iterations not known
– Syntax:
while (condition) { block} & do {block} while (condition)
• Determinate Loops: Iterations are known
– Syntax:
for(initialization; test; expression) { statements; }
• break & continue:
– break: Halts the current loop execution & transfers
control out of the loop
– continue: It starts the next iteration
– labels can be used to refer a block by name
Sample Programs .. .. ..

Java Programming K.S.Mahara 13


san
Flow Controls
- Exceptional Conditions
• Exception: An abnormal condition that occurs
while executing a program.
• try{} / catch{} / finally{} are the mechanisms to
handle exceptions
• Syntax:
try { statements; }
catch(some exception) { handle the exception; occurs N
times}
finally { statements; }
• More information is available in Exception
Handling part

Java Programming K.S.Mahara 14


san
Structure of a Java Program
• Source code consists of one or more compilation units
(.java files)
• Each compilation unit can contain:
o a package statement
o import statements
o class declarations
o interface declarations
• Java compiler reads a Java compilation unit and produces
one or more binary bytecode files (.class files)
o Named according to the names of the classes or interfaces
in the compilation unit
o Case is always significant

Java Programming K.S.Mahara 15


san
Java Program Structure
Documentation section
Package statements
Import statements
Interface statements
Class definitions
Main method class
{
body;
}
Java Programming K.S.Mahara 16
san
Hello World!
// First program, to get experience with using the Java tools

import java.io.*;
class HelloWorld {
public static void main (String args[])
{ System.out.println("Hello, World!");
}
}

Save the file as : HelloWorld.java


To compile this program, enter the command:
javac HelloWorld.java
This will produce the binary bytecode file HelloWorld.class as output.
To execute this program, enter the command:
java HelloWorld
  Hello, World!
should appear on your terminal 

Java Programming K.S.Mahara 17


san
Hello World! – An Analysis
• An import statement, that imports the required package
• A class statement, which introduces the class to be defined.
• Identifier following the class keyword is the name by which the class
will be referenced. (Program Name)
• A main method, the 1st method to run, when a program is executed.
• A void method must not return a value.
• Public indicates that the method is global, static denotes that main()
is a class method and can be called without creating an object.
• Note that String is part of the Java language, so no special headers
or declarations are needed to use it.
• A call to the method println, which is defined in the Java library.
Java run-time system will use the System class to perform the
println method

Java Programming K.S.Mahara 18


san
Sample Programs for ..
• Variable declaration, initialization & display
• Arithmetic operators
• Assignment operators
• Increment & Decrement Operators
• if else constructs
• Ternary operator
• while & do while loops
• for loops
• switch case
Black Board

Java Programming K.S.Mahara 19


san
Parsing Numeric Strings
• String to int
Integer.parseInt(strExpression)
• String to float
Float.parseFloat(strExpression)
• String to double
Double.parseDouble(strExpression)
* strExpression: expression containing
a numeric string (in.readLine())

Java Programming K.S.Mahara 20


san
Parsing Strings

• Character
(char)System.in.read()
• String
in.readLine()

Java Programming K.S.Mahara 21


san
Java Mathematical Functions
available in java.lang.Math class

sin(x) cos(x) tan(x) asin(x) acos(x)

atan(x) pow(x,y) exp(x) log(x) sqrt(x)

ceil(x) floor(x) abs(x) max(x,y) min(x,y)

and more ..

Java Programming K.S.Mahara 22


san
OOPS – an overview
• Procedural programming doesn't have
sophisticated modularization
• Procedural programming gives importance to
functions and not on data on which these
functions work
• Chances for data corruption is more
• Real world problem design is difficult

Java Programming K.S.Mahara 23


san
OOPS – an overview contd..

• OOPS concentrates more on data than on


procedures
• Programs are divided into objects
• No direct dada access; access is only through
functions
• An object’s data is tied with its functions
• Function of one object can access / communicate
with the function of another object
• Easy addition of new data and functions

Java Programming K.S.Mahara 24


san
OOPS – an overview contd..

Java Programming K.S.Mahara 25


san
OOPS – an overview : Basic Concepts

• Objects
• Classes
• Encapsulation
• Constructors
• Inheritance
• Polymorphism
• Abstraction

Java Programming K.S.Mahara 26


san
Type Conversion (Casting)

• Used to avoid implicit type coercion


• Syntax :-
(dataTypeName) expression
• Expression evaluated first, then type
• converted to dataTypeName
• Examples:
(int)(7.9 + 6.7) = 14
(int)(7.9) + (int)(6.7) = 13

Java Programming K.S.Mahara 27


san
Classes & Objects
• Class declaration : Syntax
class classname {
body of the class
}

• Class declaration : Example


class Book {
String title;
String author;
int pages;
float price;
String output() {
System.out.println(“Title: “ + title);
}
}

Java Programming K.S.Mahara 28


san
Class creation : Example
import java.io.*;
class sample {
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);
int a = 10, b = 0, c = 0;
System.out.println(“a = “ + a);
try
{ System.out.println(“Enter an Integer”);
b = Integer.parseInt(in.readLine()); }
catch(Exception e) {}
c = a + b;
System.out.println( “ a + b is : “ + c);
}
}

Java Programming K.S.Mahara 29


san
Instance Creation : Example
class insCr {
int a = 5;
public static void main(String(args[]) {
insCr ic = new insCr();
// a single instance of the class is created and a
// reference is returned to that object
System.out.println(“a = “ + ic.a);
}}
Multiple references of the same object is possible
insCr ic = new insCr();
incCr ic1 = ic;

Java Programming K.S.Mahara 30


san
Methods
• Functions that operate on instances of classes in which
they are defined
• Objects communicate with each other (intra & inter class)
using methods
• Method Definition : Syntax
<returntype> <methodname> (<type1> <arg1>, ..<typen> <argn>)
{ set of statements }
• Method Calling : Syntax
Object.methodname(parameters);
• ClassMethods: Similar to class variables, available to class
instances and toother classes; instances are not required
Syntax: static <ret type> <methname> (argmts) {stmts; }
• Sample Programs on Black Board

Java Programming K.S.Mahara 31


san
This keyword & Method Overloading
• This: a Special reference value used inside any instance
to refer the current object
• It’s value refers to the object on which the current method has been
called
• Class methods (ie. Static) cannot use this
• Method Overloading: Different method definitions with
same name but different parameter list
– Overloaded methods are differentiated based on the number &
type of parameters of that method and not on return type
– The compiler returns an error if the chosen methods have the
same name and parameter list, but different return types
– Sample program on black board; Exception Handling Trial

Java Programming K.S.Mahara 32


san
Arrays
• An ordered collection of primitives, object references and
other arrays; homogeneous in nature
• Java supports multidimensional arrays (arrays of arrays)
• Array Creation & Usage
– Declare eg: int marks[];
– Construction eg: marks = new int[29];
– Initialization eg: marks[] = {55,66,77,88,93,45}

– Multidimensional Arrays : available as array of arrays


• Construction eg: int mat1[][] = new int[2][2];

On the Blackboard : Syntax & Sample Programs

Java Programming K.S.Mahara 33


san
Vectors
• Problems with arrays
– Array size should be fixed at compile time ( c & c++)
– In java runtime setting of array size is possible,
changing is difficult
• Vectors
– Array like objects that can shrink & grow automatically
– Can hold elements of multiple data types
• Syntax: Vector vector-name = new Vector()
• Available in java.util package
• Vector handling methods are available
• Sample Program
Java Programming K.S.Mahara 34
san
String Manipulations
• Java uses String & StringBuffer classes to encapsulate
strings of characters
• Java does not have built in string type, but available as a
String Class under langpackage
• Syntax: String str = new String(“java”); OR String str =
“java”
• Built-in methods are available to work with Strings
– (charAt(int index), concat(..), toUpperCase(),toLowerCase()
• StringBuffer class is used to manipulate String contents
dynamically
– Constructors: StringBuffer(), StringBuffer(int Capacity) &
StringBuffer(String initialString)
– Methods: append(String str), insert(..), setCharAt(.), setLength()

Java Programming K.S.Mahara 35


san
Other Important Classes in java.util
• Date: Date & Time information
• Calendar: Provides support for date conversions
• GregorianCalendar: Calendar’s subclass; supports
calendar operations for most of the world
• TimeZone: Local & other time zones can be used
• SimpleTimeZone: Extends TimeZone to provide
support for GregorianCalendar object

Java Programming K.S.Mahara 36


san
Constructors
• A kind of initialized, automatically called when an
object of any class is initialized
• Special Properties :
– Name is same as the class
– No return type
– Automatic invocation
– Explicit calling is not allowed
• A constructor can be called from another constructor
• Constructors can be overloaded
• Finalize() method’s operation is opposite to constructor
• Syntax & Examples on Blackboard

Java Programming K.S.Mahara 37


san
Inheritance
• Properties of one class (Base / Super) is used by
another class (Derived/Sub)
• Te derived class possess the features of the
base class in addition to its own properties,
leading to more number of properties than the
base class
• Base class remains unaltered
• Code reusability is the main advantage
• Physical availability of data & methods of a
super class to its sub class
• Availability of access specifiers (public, private
& protected)
• Availability of super keyword

Java Programming K.S.Mahara 38


san
Inheritance contd..
Types

• Single
– Subclass is derived from a single super super class
• Hierarchical
– Single super class is used to derive number of subclasses of the
same level
• Multilevel
– A derived class acting as a super class for another sub class
• Multiple (Not supported by java)
– A subclass derived from more than one super class

Java Programming K.S.Mahara 39


san
Inheritance contd..
Single Inheritance
• Syntax:class superclassname { data & methods; }
class baseclassname extends superclassname { data & methods}
• extends is the keyword to indicate inheritance
• Example:
class parent
{ int a;
void getP(int x) { a = x}
void putP() ( {System.out.println(“From Parent ” + a);}}
class child extends parent { int b;
void getC(int x, int y) { a = x; b = y; /* OR { getP(x); c = y; } */ }
int sum() { int tot = a + b; return(tot); }
void putC() { System.out.println(“From Child”);
System.out.println(“A & B” + a + “& “ + b);
System.out.println(“Sum = “ + tot); } } }
class Main { public static void main(String args[])
{ child C = new child(); C.getC(4,6); C.putP();c.putC(); }
}

Java Programming K.S.Mahara 40


san
Inheritance contd..
Hierarchical Inheritance
• More than one sub class can be derived from one main
class
• Syntax is same as single inheritance
• Example:
– class a { dada & methods }
class b extends a { data & methods }
class c extends a { data & members } ... ..

class a

class b class c .. ..
Java Programming K.S.Mahara 41
san
Inheritance contd..
Multilevel Inheritance
• The derived class of one base class acts as the base class
for another derived class
• ie. class a {..}
class b extends a {..}
class c extends d {..} .. ..
• Example programs on black board

Java Programming K.S.Mahara 42


san
Method Overriding
• Derived class’s methods can have the same
name as the base class
• Overriding is the creation of a method in the
subclass that has the same signature as a super
class’s method
• The new method of the derived class hides the
super class’s method

Java Programming K.S.Mahara 43


san
Interfaces
• Multiple inheritance is not supported by java
• Interface is the alternate (implements is the keyword)
• It is a collection of method definitions, the implementing
class should provide the code for all its methods
• It should not contain implementation for its methods
• Variables of an interface will become final & static
• Syntax: <access> <interfacename> {
<ret type> <methodName1>(<par list>);
:
<ret type> <methodNameN>(<par list>);
<type> <varName1> = <value>;
:
<type> <varNameN> = <value>; }
• Multiple inheritance: class A extends x implements y

Java Programming K.S.Mahara 44


san
Interfaces : Implementation
contd. from previous slide
• File 1: Interface
public interface ifacedemo {
public String method1(); }
• File 2: Implementing Program
public class ifaceclass implements ifacedemo {
public static void main(String args[]) {
System.out.println(“ Hi”); }
public String method1() { return “str”; } }

Java Programming K.S.Mahara 45


san
Final modifier
Final is the keyword indicates that further alterations are
not allowed

• Can be applied to classes, variables & methods


• Final classes can not be used to derive sub classes
– String, Boolean, Math & Character are some final classes

• Final variables can not be altered (ex. final int a = 4;)


• Final methods can not be overridden by subclasses
• Usage of final before a method helps in faster
compilation because the compiler knows that final
methods cannot be overridden
• Sample Programs ; Another Keyword finally !

Java Programming K.S.Mahara 46


san
Abstract Classes
• Classes from which instances are not created, contains
common characteristics of its derived class (incomplete)
• Generally it acts as a super class
• Methods of an abstract class should be abstract
• Abstract method’s implementation is essential

Java Programming K.S.Mahara 47


san
Exception Handling
• An abnormal condition that occurs while
executing a program
• Erroneous events like division by zero, array
index out of bounds, IO exception, etc
• Java contains various classes to handle
exceptions
• Purpose: to provide a means to detect and report
an exceptional circumstance for appropriate
action
• Sequence
• Find the problem (HIT)
• Report the problem (THROW)
• Receive the error report (CATCH)
• Take corrective action (HANDLE)

Java Programming K.S.Mahara 48


san
Exception Handling contd..
Catching Exceptions
Exception Handler’s blocks: try, catch & finally
try: handles the exceptions, comes first and wraps
the code to be monitored for exceptions
catch: immediately follows the try block, multiple
catch blocks are permitted
syntax: try { code to be monitored }
catch(Exceptiontype e)
{ handler code}
finally: Only one block is allowed; should immediately follow
the last catch block; control passes to this block after
handling the exception and also if there is no catch block
to handle the exception
syntax: finally { statements; }

Java Programming K.S.Mahara 49


san
Exception Handling contd..
throw & throws
• Throw: Used to explicitly throw an exception
– Requires a throwable object as its argument
– Syntax: throw<throwable instance>
– The execution stops immediately after the throw
statement and matching is done with the nearest catch
block for exception handler
• Throws: Used when a program does not want to
use try block for handling exceptions
– This clause contains the possible exceptions that may
occur in the program
– Syntax: class classname {
Public static void main(String args[]) throws Exceptiontype
{ body }
}

Java Programming K.S.Mahara 50


san
Exception Handling contd..
User-defined exceptions
• User’s can handle exceptions, that are application specific
• Subclasses of Exception class; extends the Exception class
• throw clause is used for throwing these exceptions
• Syntax: class Uexp extends Exception
{ code }
• Example: class uex extends Exception {
uex() {System.out.println(“Positive Number”);}
uex(String s) {System.out.println(s);}}// end of class uex
class Main { Public static void main(String args[])
{ int n = integer.parseInt(String args[0]); // command line arg
try { if (n<0) throw new uex(); }
catch(uex e) { System.out.println(e); }
} // End of Main class

Java Programming K.S.Mahara 51


san
Exception Handling contd..
• On the black board
List of system exceptions
Sample programs

Java Programming K.S.Mahara 52


san
Packages
• Containers for classes
• Java contains lot of packages, each having its own set of
classes
• Class names are unique within a package
• Stored in a hierarchical manner
• Explicitly called using import statement
• Once a package is imported, its classes can be used by
the importing program
• java.lang is the package, that gets imported by default
• A specific class or all the classes can be imported
• Java contains built–in packages & permits user defined
packages
Java Programming K.S.Mahara 53
san
Packages contd..
• Some classes in a package may have usage restrictions ,
they may be hidden from other classes
• Naming Conventions
• Package Name: Starts with lowercase
• Class Name starts : Starts with Upper Case
• Example: java.lang.Math.*

Java Programming K.S.Mahara 54


san
Packages contd..
Creating a Package
• Create a directory having the package name as
it’s name
• This directory should be created as a
subdirectory of the directory where java files are
stored
• Include package command along with the
package name as the first statement in the
program
• Include class declarations with public access
level
• The program has no main method
• Save and compile the program
Java Programming K.S.Mahara 55
san
Packages contd..
Accessing a Package
• Move to the current working directory (Under which the
directory containing packages is present)
• Import the desired package proceed as usual
Adding a class to an existing package
• Create a new class in the package’s directory
• Include the package’s name as the first statement
• Follow the steps of creating a package
Programming Exercise
• Package Creation
• Accessing a Package
• Adding a class to an existing package

Java Programming K.S.Mahara 56


san
Multithreading
• An important feature of Java
• Process: A program in execution
• Thread:A smallest unit of code that is dispatched by
the scheduler, a single sequential flow of control
within a program
• Multithreaded program performs different jobs at the
same time.
• Threads exist in different states
• Different methods are available
• Possess priority levels
• Inter thread communication is possible
• Efficient than processes
Java Programming K.S.Mahara 57
san
Multithreading

Priority Levels (min,normal,max:1,5,10)


Priority Methods setPriority(int pri) & getPriority()
Thread Scheduling: Preemptive & Time Sharing

Java Programming K.S.Mahara 58


san
Multithreading
Implementation
• Two ways
– Creating objects for java.lang.Thread class
– Using the Runnable interface
• Using Runnable interface is easier
• Syntax: Runnable Implementation
class classname implements runnable {contains run() method }
public class mainclass{ public static void main(args[])
{ classname cn =new classname(); Thread t = new Thread(cn); t.start(); }
}
• Syntax: Thread Class Implementation
class classname extend thread {contains run() method
public static void main(args[])
{ classname cn =new classname(); Thread t = new Thread(cn); t.start(); }
}

• Sample Programs & more

Java Programming K.S.Mahara 59


san
Applets
• Four definitions of applet:
– A small application
– A secure program that runs inside a web browser
– A subclass of java.applet.Applet
– An instance of a subclass of java.applet.Applet

• According to SUN “"An applet is a small program that


is intended not to be run on its own, but rather to be
embedded inside another application....The Applet
class provides a standard interface between applets
and their environment."
• A small application mainly used for internet
applications, executed using Appletviewer or any java
enabled web browser.
Java Programming K.S.Mahara 60
san
Applets Contd..
Types of Applets
• Local
– Available in the local memory
– Internet connection is not required for execution
– Mostly created by users for personal use
• Remote
– Downloaded from the Internet & embedded in the webpage
– Internet connection is a must
– Mostly developed by someone else
Applet Vs Applications
• No main() method
• Can’t run independently, needs HTML tags
• Can’t read or write to files in the local computer
• Can’t communicate with other servers on the network
• Can’t execute any program from the local computer
• Can’t use the libraries of other languages like C & C++

Java Programming K.S.Mahara 61


san
Applet Life Cycle

Information Passing
• Applets can accept parameters from the HTML document
• <param> tag of HTML is used to pass parameters
• Applet uses getParameter() method to receive the values sent from HTML
document
• Applet Interfaces: AppletContext, AudioClip & AppletStub
• AWT can be used to create GUI based applets
» Sample programs
Java Programming K.S.Mahara 62
san
Applets contd.. Applet Development
• Import java.applet & java.awt packages for using applet
methods & displaying the results respectively
• Include the necessary statements & Save the file (no
main() method)
• Compile the file using javac
• Create a webpage having <applet> tag & embed the
applet’s class file in it.
• Execute the applet using Appletviewer or any java enabled
web browser (difference?)
• General Structure of an applet
import statements for awt , applet & etc.,
publicpublic class appCName extends Applet
{ .. .. .. Public void paint(Graphics g) { applet operation code }
}
• HTML <applet code = .. .. .class width = int height = int> </applet>

Java Programming K.S.Mahara 63


san
Sample Applet
// HelloWorldApplet.java
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet
extends Applet{
public void paint (Graphics gr) {
gr.drawString("Hello, World!", 10, 100); }}
// Running the applet
  <HTML>  <HEAD> 
<TITLE> A Simple Program </TITLE>
</HEAD>       <BODY>
    Here is the output of my program:· 
   <APPLET code="HelloWorldApplet.class"
height=100 width=300>
       If you see this text, it means that you are
not running a Java-capable browser.
</APPLET>   </BODY></HTML>

Java Programming K.S.Mahara 64


san
Graphics, Colour & Font
• java.awt package provides necessary support for graphical
operations through its classes & methods
• Graphics class contains methods to draw strings, lines,
rectangles ,polygons, arcs and other geometrical shapes
• Font class offers a variety of font styles for display inside
an applet
• Color class can be used to apply colour to the shapes &
text drawn & background using Graphics & Font classes
• Image creation and manipulation are possible with the help
of suitable methods available
• Sample Programs demonstration

Java Programming K.S.Mahara 65


san
Java Graphics Contd..
• Graphics Class Some selected methods:
• Color getColor()
• void setColor(Color c)
• Font getFont()
• void setFont(Font f)
• void drawLine(int fromX, int fromY, int toX, int toY)
• void drawRect(int ulx, int uly, int width, int height)
• void drawString(String s, int baselineX, y)
• void drawOval(int ulx, int uly, int width, int height)
• void drawArc(int ulx, int uly, int width, int height, int
startAngle, int angleDeg)
• void clearRect(int ulx, int uly, int width, int height)
• void fillRect(int ulx, int uly, int width, int height)
• And more..
Java Programming K.S.Mahara 66
san
User Interface Components
• A place where various drawing needs are provided is
the container
• Container is derived from java.awt.Container class
• User Interface’s elements are called as components
• Components are derived from java.awt.Component
class, it contains all the UI components
• MORE

Java Programming K.S.Mahara 67


san
User Interface Components Contd..
• Label : to make annotations in the window
• TextField : to permit the user to input text
• Button : a push-button to cause an action
• TextArea : similar to TextField, but
o may contain a large amount of text
o permits viewing with scroll bars
• Choice : uses pop-up menu for selecting an item
• List : A scrolling text list for selecting single / multiple items
• CheckBox : possess dual state property (checked & unchecked)
• Scrollbar : used to select a value between a specified minimum &
maximum
• ScrollPane : implements automatic horizontal and / or vertical
scrolling with display options as as needed, always & never
• Canvas : a blank rectangular area onto which the application can
draw or trap user input events
• FileDialog : displays a dialog window for file selection
– Syntax & Examples : Black Board & Demo

Java Programming K.S.Mahara 68


san
User Interface Components Contd..
usage procedure
• Create the UI Component using its constructor
• Add the component to a container by using the add()
method
• Include event handling routines to handle the events
generated by the components
UI component’s methods
• Each UI component has its own set of methods for
changing their attributes

More information on User Interface Components is


available in the reference slide # ..

Java Programming K.S.Mahara 69


san
More on AWT ( User Interfaces)
• AWT
– Abstract Windowing Toolkit
• Java’s library for graphical elements
– Makes EXTENSIVE use of inheritance and OO
techniques!
– Hierarchical approach to developing “Components”
– The AWT is platform independent
• presents the same components on all platforms
Information on AWT Classes : next slide..

Java Programming K.S.Mahara 70


san
AWT Classes
• AWT contains two main classes namely
– Component
– Container
• Component
– nearly all the “widgets” in the AWT inherit
from Component
• Container
– a placeholder
– a Container can “contain” other Components
– a Container is a Component
Java Programming K.S.Mahara 71
san
Layout Managers
• Available in java.AWT.LayoutManager interface
• Helps in positioning the AWT components in the
container
• Tells the AWT where to position a component or a
container
• Tells the AWT what to do when application / applet is
resized
• Types
– Flow Layout (Default)
– Grid Layout
– Border Layout
– Gridbag Layout
– Card Layout

Java Programming K.S.Mahara 72


san
Flow layout
• Default layout
• lays the components in a row; when row is full, starts on
the next row
• each row is justified
• rows are placed starting at the top
• each component is given its natural size (if there is
room)
• FlowLayout(): creates a FlowLayout with CENTER
alignment
• FlowLayout(int align): creates a FlowLayout with
specified alignment (LEFT, CENTER, RIGHT)
• add(Component c): adds the component after any
existing components

Java Programming K.S.Mahara 73


san
Grid Layout
• Lays out the components in row – column fashion
• Component’s size is adjusted to the cell’s size
• All components will have the same size
• Order of addition determines the component’s position in
the grid
• if enough components are not added, number of columns
is decreased
• number of rows or columns is increased as needed
• GridLayout(int nrows, int ncols): create a grid of the
specified size.
• add(Component c): adds the component to the next
available slot (fills from left to right, top to bottom)

Java Programming K.S.Mahara 74


san
Border Layout
• Lays out the components as per the user’s specification
• Used when the components are to be grouped on the
borders of a container
• only one component in a location
• if a location is empty, the space is given to the Center.
• if a Center is empty, there is a empty space in the
middle
• each component is sized to fit the available space
• BorderLayout() : Creates border layout
• add(String location, Component c): adds the component
in the specified location (Center, East, South, West,
North)

Java Programming K.S.Mahara 75


san
Gridbag Layout
• Component’s position can be specified by mentioning
the coordinate values
• The container is divided into a grid of equally sized cells
• A component can occupy more than one cell
• Component’s size is adjustable if the size is less that the
cell’s size (H & V stretching constraints are available)
• GridBagLayout(): Creates gridbag layout
• Add(componentn,constraints): adds the component
including the constraints, which are already set

Java Programming K.S.Mahara 76


san
Card Layout
• only one component is visible at a time
• each component is sized to fit the available space
• Each component is considered as a card
• Methods are available to view the first , last,previous,next
or any component by specifying its name
• CardLayout() : creates card layout
• add(String name, Component c): adds the component to
the card deck, component is given the specified name

Java Programming K.S.Mahara 77


san
Files & Streams : Overview

• Common feature of any programming language


• Java.io contains a class called “File” to perform file
operations
• Objects of File class can be created in three ways
• File fo = new File(string); where string may be “d:/maha/demo”
• File fo = new File(dirpath, File Name);
• File fo = new File(dir. name,File Name);
• File class contains methods to access the properties of
files (getName(),getPath(),exists() & more)

Sample Programs & Demonstration


Refer text book for more information

Java Programming K.S.Mahara 78


san
Other Features
• Swings ( Improved AWT)
• Network programming
• Database connectivity (JDBC)
• Remote Method Invocation (RMI)
• Component Reusability (Beans)
• Java Server Pages (JSP)
• Enterprise Java Beans (EJB)

Java Programming K.S.Mahara 79


san
Swings
• Supercharged alternative for AWT
• More powerful and flexible than AWT components
• Contains the basic components and additional components
• Available under javax.swing package
• Written entirely using Java (light weight)
• One part of Java Foundation Classes
• Provides pluggable look & feel (Easy substitution of appearance
& behaviour for an element)

Java Programming K.S.Mahara 80


san
Swing Component Classes

• AbstractButton : Abstract super class for Swing


buttons
• ButtonGroup : Encapsulates a mutually exclusive
set of buttons
• ImageIcon : Encapsulates an icon
• JApplet : Swing version of Applet
• JButton : Swing push button class
• JCheckBox : Swing check box class
• JComboBox : Encapsulates a combo box
• Jlabel : Swing version of label
• JRadioButton : Swing version of radio button
contd..

Java Programming K.S.Mahara 81


san
Swing Component classes contd..
• JScrollPane : Encapsulates a scrollable window
• JTabbedPane : Encapsulates a tabbed window
• Jtable : Encapsulates a table-based control
• JTextField : Swing version of text field
• JTree : Encapsulates a tree-based control

For more information refer Chapter 26 of the


text book

Java Programming K.S.Mahara 82


san
Java beans
• Component based programming approach
• Can be created on own or obtained from vendors
• Defines an architecture, that specifies the usage of
building blocks
• Reusability is the main concept
• Definition: A software component designed to be
reusable in a variety of ways
• Can be used to perform tasks of varying complexity
• Can operate independently and with other components
• Set of procedures are available for developing and using
beans

Java Programming K.S.Mahara 83


san
Java Beans contd..

Advantages
• The properties, events and methods of a bean that are
exposed to an application builder tool can be controlled
• Bean configuration support software is available (not
needed during run-time)
• Bean’s configuration settings can be stored
• A Bean may receive from and send events to other
objects. (Registration is required)

Java Programming K.S.Mahara 84


san
Application Builder Tools
• An utility to configure, integrate and develop
bean based applications
• Available beans are listed in a palette
• Beans can be positioned on a GUI using
Worksheet
• Beans can be configured to a particular
environment using special editors and
customizers
• A bean’s state and behaviour can be inquired
• Beans can be interconnected
• Complete information of a fully configured bean
can be stored in a persistent storage
Java Programming K.S.Mahara 85
san
BDK

• Bean Development Kit


• Tool for creating, configuring and connecting a
set of beans
• Needs to be installed and started before usage
• Refer text book for examples Ch.25

Java Programming K.S.Mahara 86


san
JAR Files
• Java Archive files
• Allows a developer to efficiently deploy a set of classes and their associated resources
• Beans should be packaged within JAR files
• Java.util.zip contains the classes that read and write JAR files
• Makes Software delivery and installation easy
• Available as a compressed file
Manifest Files
• Used to indicate which components in a JAR file are Java Beans
• Can refer many .class files
• Special entry to indicate java bean class file is essential
(Java-Bean : True)
• Example:
Name: sunw/demo/slides/slideo.gif
Name: sunw/demo/slides/slideo.gif
Name: sunw/demo/slides/slideo.class
Name: sunw/demo/slides/jbean.class
Java-Bean : True

Java Programming K.S.Mahara 87


san
The JAR Utility
• JAR file generation Utility Syntax: jar options files
• Set of commands are available to handle JAR Files
• JAR File Creation : jar cf jarfn.jar *.class *.gif
• JAR File Creation with a manifest file :
jar cf jarfn.jar mffn.mf *.class *.gif
• Tabulating JAR File’s contents: jar tf jarfn.jar
• Extracting a JAR file’s contents : jar xf jarfn.jar
• Updating an existing JAR File with another file:
jar –uf jarfn.jar newfile.class
• Recursing directories (Adding flies in a dir to a JAR
File)
jar –uf jarfn.jar n-C directoryX.*
Java Programming K.S.Mahara 88
san
Introspection
• Analyzing a bean to determine its capabilities
• Provides information about a bean to the
developer
• A Java Bean cannot operate without it
• A developer can specify a bean’s information to
be exposed by an application developer tool
– Use simple naming convention and allow the
introspection mechanisms to infer a bean’s information
– An additional class explicitly specifies the information

Java Programming K.S.Mahara 89


san
Java Bean creation steps

• Create a directory for a new bean


• Create the java source files
• Compile the source file
• Create a manifest file
• Generate a JAR file
• Start the BDK
• Test

Java Programming K.S.Mahara 90


san
Information about References
• Java IO
• AWT components
• Event Handling
• Layout Managers
• JDBC
• JavaScript
• Sample Programs

Programming in Java

Java Programming K.S.Mahara 91


san

You might also like