Final Merge OOPS Material
Final Merge OOPS Material
PROGRAM SYSTEM
DEPARTMENT OF CSE
PREPARED BY
Mrs.S.BOOVANESWARI
Java features – Java Platform – Java Fundamentals – Expressions, Operators, and Control
Structures – Classes and Objects, Constructors – Destructors - Packages and Interfaces –
Internationalization.
The popularity of java is due to its unique technology that is designed on the basis of three key elements.
They are the usage of applets, powerful programming language constructs and rich set of significant object
classes.
When a program is compiled, it is translated into machine code or processor instructions that are specific
to the processor. In the Java development environment, there are two parts: a Java compiler and a Java
Interpreter. The compiler generates bytecode (asset of instructions that resemble machine code but are not
specific to any processor) instead of machine code and the interpreter executes the Java program.
The disadvantage of using bytecode is the execution speed. Since system specific programs run directly
on the hardware, they are faster than the Java byte codes that is processed by the interpreter. In order to write
a Java program, an editor, a Java compiler and a Java Runtime Environment are needed.
History of Java:
James Gosling initiated the Java language project in June 1991 for use in one of his many set- top box
projects. The language, initially called Oak after an oak tree that stood outside Gosling's
office, also went by the name Green and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once,
Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open-source software under the terms of
the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source, aside
from a small portion of code to which Sun did not hold the copyright.
As of December 2008, the latest release of the Java Standard Edition is 6 (J2SE). With the advancement
of Java and its widespread popularity, multiple configurations were built to suite various types of platforms.
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.
Platform independent: Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever
platform it is being run.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be
easy toaster.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time
error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks
simultaneously. This design feature allows developers to construct smoothly running interactive
applications.
Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental and
light weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high performance.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry extensive amount of run-time information that can be used to
verify and resolve accesses to objects on run-time.
SWING is a set of user interface components that is implemented entirely in java. The user can use a
look and feel that is either specific to a particular operating system.
Collections are group of objects. Java provides several types of collection, such as linked lists, dynamic
arrays, and hash tables, for our use. Collections offer a new way to solve several common programming
problems.
Various tools such as java, java and Javadoc have been enhanced. Debugger and profiler interfaces for
the JVM are available.
Performance improvements have been made in several areas. A Just-In-Time (JIT) compiler is included
in third.
Policy files can define the permission for code from various sources. These determine if a particular file
or directory may be accessed, or if a connection can be established to a specific host and port.
Digital certificates provide a mechanism to establish the identity of a user, which can be referred as
electronic passports.
The Java 2D library provides advanced features for working with shapes, images and text.
Various security tools are available that enable the user to create and store cryptographic keys and
digital certificates, sign Java Archive (JAR) files, and check the signature of a JAR file.
The user can now play audio files such as MIDI, AU, WAV and RMF files using Java programs
JAVAPLATFORM
The computer world currently has many platforms, among them Microsoft Windows, Macintosh,
OS/2, UNIX® and NetWare®; software must be compiled separately to run on each platform. The binary
file for an application that runs on one platform cannot run on another platform, because the binary file is
machine specific.
The Java Platform is a software platform for delivering and running highly interactive, dynamic,
and secure applets and applications on networked computer systems. But what sets the Java Platform
apart is that it sits on top of these other platforms, and compiles to bytecodes, which are not specific to
any physical machine, but are machine instructions for a virtual machine.
A program written in the Java Language compiles to a bytecode file that can run wherever the
Java Platform is present, on any underlying operating system. In other words, the same exact file can run
on any operating system that is running the Java Platform. This portability is possible because at the core
of the Java Platform is the Java Virtual Machine.
The Java Platform is therefore ideal for the Internet, where one program should be capable of
running on any computer in the world.
The Java Platform is designed to provide this “Write Once, Run Anywhere” capability.
Developers use the Java Language to write source code for Java-powered applications. They
compile once to the Java Platform, rather than to the underlying system. Java Language source code
compiles to an intermediate, portable form of bytecodes that will run anywhere the Java Platform is
present.
Developers can write object-oriented, multithreaded, dynamically linked applications using the
Java Language. The platform has built-in security, exception handling, and automatic garbage collection.
Just-in-time compilers are available to speed up execution by converting Java bytecodes into machine
language. From within the Java Language, developers can also write and call native methods—methods in
C, C++ or another language, compiled to a specific underlying operating system—for speed or special
functionality.
The Java Language is the entry ramp to the Java Platform. Programs written in the Java Language
and then compiled will run on the Java Platform.
Java Virtual Machine - The Java Virtual Machine is a “soft” computer that can be implemented in
software or hardware. It’s an abstract machine designed to be implemented on top of existing processors.
The porting interface and adapters enable it to be easily ported to new operating systems without being
completely rewritten.
Java API - The Java API forms a standard interface to applets and applications, regardless of the
underlying operating system. The Java API is the essential framework for application development.
This API specifies a set of essential interfaces in a growing number of key areas that developers
will use to build their Java-powered applications.
The Java Base API provides the very basic language, utility, I/O, network, GUI, and applet
services; OS companies that have licensed Java have contracted to include them in any Java
Platform they deploy.
The Java Standard Extension API extends the capabilities of Java beyond the Java Base API.
Some of these extensions will eventually migrate to the Java Base API. Other nonstandard
extension APIs can be provided by the applet, application, or underlying operating system. As
each new extension API specification is published, it will be made available for industry review
and feedback before it is finalized.
A Java Language development environment includes both the compile-time and runtime
environments, as shown in below figure. The Java Platform is represented by the runtime environment.
The developer writes Java Language source code (.java files) and compiles it to bytecodes (.class
files). These bytecodes are instructions for the Java Virtual Machine.
To create an applet, the developer next stores these bytecode files on an HTTP server, and adds an
<applet code=filename> tag to a Web page, which names the entry-point bytecode file.
When an end user visits that page, the <applet> tag causes the bytecode files to be
transportedoverthenetworkfromtheservertotheenduser’sbrowserintheJavaPlatform.Atthisend, the
bytecodes are loaded into memory and then verified for security before they enter the Virtual Machine.
Once in the Virtual Machine, the bytecodes are interpreted by the Interpreter, or optionally turned
into machine code by the just-in-time (JIT) code generator, known more commonly as the JIT Compiler.
The Interpreter and JIT Compiler operate in the context of the runtime system (threads, memory,
other system resources). Any classes from the Java Class Libraries (API) are dynamically loaded as
needed by the applet.
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what can
be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can store integers, decimals, or
characters in these variables.
Primitive Datatypes
Reference/Object Datatypes
There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.
byte:
short:
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is -2,147,483,648. (-2^31)
Maximum value is 2,147,483,647(inclusive). (2^31-1)
Int is generally used as the default data type for integral values unless there is a concern about
memory.
The default value is0.
Example: int a = 100000, int b =-200000
long:
double:
Boolean:
char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or0).
Maximum value is '\off' (or 65,535inclusive).
Char data type is used to store any character.
Example: char letter='A'
Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation.
For Example:
byte a = 68; char a = „A‟
byte, int, long, and short can be expressed in decimal (base 10), hexadecimal (base 16) oroctal
(base 8) number systems as well. Different Types of literals are:
Number literals
Character literals
Boolean literals
String literals
Number
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number
systems for literals.
For Example:
String literals in Java are specified like they are in most other languages by enclosing a sequence
of characters between a pair of double quotes.
For Example:
String and char types of literals can contain any Unicode characters.
For Example:
They are:
\n - newline
\t - tab
\” - Double Quote
\r - Carriage Return
\s - Space
OPERATORS IN JAVA
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into
the following groups:
Arithmetic Operators
Relational Operators
BitwiseOperators
Logical Operators
Assignment Operators
Mis Operators
THE ARITHMETIC OPERATORS:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Checks if the values of two operands are equal or not, if yes (A == B) is not true.
== then condition becomes true.
Checks if the values of two operands are equal or not, if values
!= are not equal then condition becomes true. (A! = B) is true.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13;
now in binary format they will be as follows:
a = 0011 1100
b = 00001101
~a = 1100 0011
The following table lists the bitwise operators:
Binary AND Operator copies a bit to the (A & B) will give 12 which is 0000
& result if it exists in both operands. 1100
Binary OR Operator copies a bit if it exists
| in either operand. (A | B) will give 61 which is 0011 1101
Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is 0011 0001
^ set in one operand but not both.
Assume Boolean variables A holds true and variable B holds false, then:
Called Logical AND operator. If both the operands are non- zero,
&& then the condition becomes true. (A && B) is
false.
Simple assignment operator, assigns values from right side C = A + B will assign
= operands to left side operand value of A + B into C
C <<= 2 is same as C
<<= Left shift AND assignment operator = C << 2
C >>= 2 is same as C
>>= Right shift AND assignment operator = C >> 2
C &= 2 is same as C =
&= Bitwise AND assignment operator C&2
C ^= 2 is same as C =
^= bitwise exclusive OR and assignment operator C^2
C |= 2 is same as C =
|= bitwise inclusive OR and assignment operator C
|2
MISC OPERATORS
There are few other operators supported by Java Language.
Example:
Value of b is : 30
Value of b is : 20
Instance of Operator:
This operator is used only for object reference variables. The operator checks whether the object is
of a particular type (class type or interface type). Instance of operator is written as:
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is the example:
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
if statements
switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if (Boolean expression)
{
//Statements will execute if the Boolean expression is
true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be
executed.
Example:
public class Test
{
public static void main(String args[])
{
int x =10;
if( x < 20 )
{
System.out.print("This is if statement");
}
}
}
Syntax:
The syntax of an if...else is: if (Boolean expression)
{
//Executes when the Boolean expression is true
}
else
{
//Executes when the Boolean expression is false
}
Example:
public class Test {
if (x<20) {
System.out.print("This is if statement");
}
else {
System.out.print("This is else statement");
}
}
}
When using if, else if, else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many else if's and they must come before theses.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else is:
if (Boolean expression 1) {
//Executes when the Boolean expression 1 is true
} else if (Boolean expression 2) {
//Executes when the Boolean expression 2 is true
} else if (Boolean expression 3) {
//Executes when the Boolean expression 3 is true
} else {
//Executes when the none of the above condition is true.
}
Example:
This would produce the following result: Value of X is 30
It is always legal to nest if-else statements which means you can use one if or else if statement
inside another if or else if statement.
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test {
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements }
switch(grade)
{
case 'A’: System.out.println("Excellent!"); break;
case 'B':
case 'C':
System.out.println("Well done"); break;
case 'D':
System.out.println("You passed"); case 'F':
System.out.println("Better try again"); break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Compile and run above program using various command line arguments. This would produce the following
result:
$ java Test
Well done
Your grade is
$
There may be a situation when we need to execute a block of code several number of times, and is often
referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of a while loop is:
while (Boolean expression)
{
//Statements
}
When executing, if the Boolean expressionresult is true, then the actions inside the loop will be executed.
This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested
and the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example:
public class Test {
public static void main (String rags []) {int x = 10;
Syntax:
The syntax of a do...while loop is:
do
{
//Statements
} while (Boolean expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Syntax:
The syntax of a for loop is:
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update statement. This
statement allows you to update any loop control variables. This statement can be left blank, as long as a
semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false,
the for loop terminates.
Example:
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce the following result: value of x :10
value of x :11
value of
x:12
values of x:13 values of x:14 values of x:15 values of x:16 values of x:17 values of x:18 values of x :19
Syntax:
The syntax of enhanced for loop is:
for (declaration: expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block
and its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can
be an array variable or method call that returns an array.
Example:
public class Test {
public static void main (String rags []) {
int [] numbers = {10, 20, 30, 40,50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
Example:
10
20
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, thecontinuekeywordcausesflowofcontroltoimmediatelyjumptotheupdate
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class test {
for (int x:numbers) {System.out.print(x); System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"}; for (Stringname:names) {
System.out.print(name); System.out.print(",");
}
}
}
This would produce the following
result:
public static void main(String args[])
{ int [] numbers = {10, 20, 30, 40,
50}; for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n"
);
}
}
}
This would produce the following result: 10
20
40
50
OBJECT:
An object is areal-world entity that has its own properties (or) state and actions (or) behavior
EX:
a pen, a person, a student
A class is a template/blue print of objects those have similar properties (or) state and actions (or)
behavior
Ex:
Pen, Person, Student
CLASS MODEL:
<access-specifiers> class name
{
access-specifiers data-typevariable-name1;
access-specifiers data-typevariable-name2;
access-specifiers return-type method_name1(arg1, arg2, arg3)
{
……….
……….
}
access-specifiers return-type method_name2(arg1)
{
……….
……….
}
}
EX
public class Sample
{
private int a;
public double average; double total;
public void adds ()
{
System.out.println(“METHOD 1”);
}
void display (int k, double j)
{
System.out.println(“METHOD 2”);
}
}
ACCESS SPECIFIERS:
Access specifiers specifies the type of access levels for the classes, variables, methods
and constructor.
Types of access-specifiers:
VARIABLES:
Variable is name of reserved area allocated in memory. Ex: int data=50; //data is variable Types of
variables:
Local Variable:
A variable that is declared inside the method is called local variable
Instance Variable:
A variable that is declared inside the class but outside the method is called instance variable.
It is not declared as static
Static Variable:
A variable that is declared as static is called static variable. It is common to all objects
Ex:
class A
{
int data=50;//instance variable static int m=100;//static variable void method ()
{
int n=90; //local variable
}
}//end of class
METHODS:
A Java method is a collection of statements that are grouped together to perform an operation
Methods are also known as Procedures or Functions
Syntax:
Method definition consists of a method header and a method body
General Form:
Object reference (.) Variable name
Object Reference is a reference to an object and variable name is the name of the instance.
Ex:
pox=10; pay=20;
EXAMPLE PROGRAM:
import javitri. *;
class Student
{
private int Rengo, m1, m2, m3, total; private String name, dept, res; Scanner s=new Scanner
(System.in);
public void gets Details ()
{
System.out.println("Enter Register No."); Rengo=sextant ();
System.out.println("Enter Name:"); name=sanest (); System.out.println("Enter
Department"); dept=sanest ();
System.out.println("Enter Mark1"); m1=sextant (); System.out.println("Enter
Mark2"); m2=sextant (); System.out.println("Enter Mark3"); m3=sextant ();
}
}
}
public static void main (String rag [])
{
CHARACTERISTICS OF CONSTRUCTOR:
TYPES OF CONSTRUCTORS:
Default Constructor
Parameterized Constructor
Default constructor:
<class name> ()
{
………
}
EX: class Car
{
public Car ()
{
System.out.println(“Car created”);
}
public static void main (String rag [])
{
Car c= new Car ();
}
}
OUTPUT:
Car created
Parameterized constructor:
Syntax:
class Student
{
intend;
String name;
A destructor is a special method typically used to perform cleanup after an object is no longer
needed by the program. C++ supports destructors, but JAVA does not support destructors.
JAVAsupportsanothermechanismforreturningmemorytotheoperatingsystemwhenit is no longer
needed by an object.
Sometimes an object will need to perform some action when it is destroyed. For example,
If an object is holding some non-Java resource such as a file handle or window character
font, then you might want to make sure these resources are freed before an object is destroyed.
To handle such situations, Java provides a mechanism called finalization.
By using finalization, you can define specific actions that will occur when an object is just about
to be reclaimed by the garbage collector.
Example of finalize () method:
Garbage Collection
o Since objects are dynamically allocated by using thenew operator, you might be wondering how such
objects are destroyed and their memory released for later reallocation. In some languages, such as
C++, dynamically allocated objects must be manually released by use of a delete operator.
o Java takes a different approach; It handles deallocation for you automatically. The technique that
accomplishes this is called garbage collection.
o It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need to
destroy objects as inch++.
o Garbage collection only occurs sporadically (if at all) during the execution of your program. It will not
occur simply because one or more objects exist that are no longer used.
o Furthermore, different Java run-time implementations will take varying approaches to garbage
collection, but for the most part, you should not have to think about it while writing your programs.
CONSTRUCTORS IN JAVA WITH AN EXAMPLE PROGRAM
SYNOPSIS
Constructors
Characteristics Of Constructors Types Of Constructors
Default Constructor With Syntax And Example
Parameterized Constructor With Syntax And Example
Constructor Overloading Sample Program
Difference Between Constructor And Method
CONSTRUCTORS:
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation.
Itconstructsthevaluesi.e.providesdatafor theobjectthatiswhyitis known as constructor
CHARACTERISTICS OF CONSTRUCTOR:
TYPES OF CONSTRUCTORS:
Default Constructor
Parameterized Constructor
Default constructor:
<class name> ()
{
………
}
Ex:
class Car
{
public Car ()
{
System.out.println(“Car created”);
}
public static void main (String rag [])
{
Car c= new Car ();
}
}
OUTPUT:
Car created
Parameterized constructor:
Syntax:
EXAMPLE:
class Student
{
int id;
String name;
CONSTRUCTOR OVERLOADING
Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists
The compiler differentiates these constructors in two ways
the different number of parameters
the different type of parameters
EXAMPLE:
class Student
{
int id, age; String name;
Student (int I, String n)
{
id = I;
name = n;
}
Student (int I, Stringninth a)
{
id = I; name = n; age = a;
}
void display ()
{
System.out.println(id+" "+name+” “+age);
}
INTRODUCTION:
Packages provide a mechanism for grouping a variety of classes and / or interfaces together.
Grouping is based on functionality Benefits of Packages:
The classes contained in the packages of other programs can be reused.
In packages, classes can be unique compared with classes in other packages.
Packages provides a way to hide classes
Types of packages:
Pre-defined packages or Java API packages
User-defined packages
Examples:
1. java. Lang
2. javitri
3. java.io
4. jamaat5.java.net
6.java. applet etc.
Import statement must appear at the top of the file, before any class declaration
1. Declare the package at the beginning of a file using theform packagepackage name;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory with same name as package name under the directory where the main
source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory
Syntax:
package [Package Name];
public class [Class Name]
{
//Body of the class
}
Example:
package first Package; public class First-class
{
//Body of the class
}
Example:
Creating Packages:
Consider the following declaration: package firstPackage. secondPackage;
This package is stored in subdirectory named firstPackage.secondPackage.
A java package can contain more than one class definitions that can be declared as public.
Only one of the classes may be declared public and that class name with .java extension is the
source filename.
Default Package:
If a source file does not begin with the package statement, the classes contained in the source
file reside in the default package
The java compiler automatically looks in the default package to find classes
Finding Packages:
1. By default, java runtime system uses current directory as starting point and search all the
subdirectories for the package.
2. Specify a directory path using CLASSPATH environmental variable
Types of access-specifiers:
Non- Yes No No No
subclass
in
another
package
Example 1:
package my_package;
classA // package scope
{
// A’s public & private members
}
publicclassB // publicscope
{
// B’s public and private members
}
Example 2:
INTERFACES
Aninterfaceinjavaisablueprintofaclass.Ithasstaticconstantsandabstract methods only.
Theinterfaceinjavaisamechanismtoachievefullyabstraction.Therecanbeonly abstract
methods in the java interface not method body.
It is used to achieve fully abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
USE OF INTERFACE:
There are mainly three reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
As shown in the figure given below, a class extends another class, an interface extends another interface
but a class implements an interface
DIFFERENCE BETWEEN CLASSES AND INTERFACES
CLASS INTERFACE
The members of a class can be constant or The members of an interface are always declared as
variables. constant, i.e., their values are final.
The class definition can contain the code for each of The methods in an interface are abstract in nature,
its methods. That is, the methods can be abstract i.e., there is no code associated with them. It is later
orlon-abstract. defined by the class that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.
It can use various access specifiers like public, It can only use the public access specifier.
private or protected.
INTERFACE SYNTAX:
interface interface Name
{
Variables declaration; Method declaration;
}
interface - keyword.
interfacename - any valid java variable.
public static void main (String args []) {A6 obj = new A6();
obj.print ();
}
}
Output: Hello
MULTIPLE INHERITANCE IN JAVA BY INTERFACE
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.
interface Printable {
void print ();
}
interface Showable {
void show ();
}
public static void main (String args []) {A7 obj = new A7();
obj.print ();
obj. show ();
}
}
Output:
Hello
Welcome
INTERNALIZATION INJAVA
INTERNATIONALIZATION AND LOCALIZATION IN JAVA
o Internationalization is also abbreviated asI18N because there is total 18 characters between the
first letter 'I' and the last lettering'.
o Internationalizationisamechanismtocreatesuchanapplicationthatcanbeadaptedto different
languages and regions.
o Internationalization is one of the powerful concepts of java if you are developing an application
and want to display messages, currencies, date, time etc. according to the specific region or
language.
o Localization is also abbreviated as I10N because there is total 10 characters between the first
letter 'L' and last lettering'.
o Localization is the mechanism to create such an application that can be adapted to a specific
language and region by adding locale-specific text and component.
System.out.println(locale.getDisplayCountry()); System.out.println(locale.getDisplayLanguage());
System.out.println(locale.getDisplayName()); System.out.println(locale.getISO3Country());
System.out.println(locale.getISO3Language()); System.out.println(locale.getLanguage());
System.out.println(locale.getCountry());
}
}
Outpu: United States English
English (United States) USA
eng en US
UNIT-II
Overloading - Inheritance – Files and Stream – Multithreading – Exception Handling
METHOD OVERLOADING
SYNOPSIS
Method Overloading
Different Ways to Overload The Method Different No. Of Arguments
Different Types of Arguments Overloading Main Method
Method Overloading and Type promotion
METHOD OVERLOADING:
o If a class have multiple methods by same name but different parameters, it is known as
method overloading.
o If we have to perform only one operation having same name of the methods increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior of the
method because its name differs. So, we perform method overloading to figure out the program quickly.
class calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new calculatiom(); obj.sum(10,10,10);
obj.sum(20,20);
}
}
OUTPUT:
30
40
class calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
class overloading
{
public static void main(inta)
{
System.out.println(a);
}
public static void main(String args[])
{
System.out.println(“main method() inv oked”);
main(10);
}
}
OUTPUT:
Main method() invoked 10
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int,long,float or double. The char datatype can be promoted to
int,long,float or double and so on
class OverloadingCalculation1
{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
OUTPUT:
40
60
INHERITANCE INJAVA
SYNOPSIS
INTRODUCTION
USE OF INHERITANCE FORMS OF INHERITANCE
WHY NO MULTIPLE INHERITANCE SUPER KEYWORD
EXAMPLE PROGRAMS
INTRODUCTION:
The mechanism of deriving a new from a from an old one is called inheritance
The old class is known as the base class or super class or parent class
The new class is called the subclass or derived class or child class
The inheritance allows subclasses to inherit all the variables and methods of their parent classes
USE OF INHERITANCE:
Code Reusability
Method Overriding (so runtime polymorphism can be achieved).
FORMS OF INHERITANCE:
Java does not directly implement multiple inheritance but by using the concept of secondary
inheritance path in the form of interfaces.
2) AMBUIGUITY IN MULTI-PATHINHERITANCE:
DEFINING A SUBCLASS :
• The keyword extends signifies that the properties of the superclassname are extended to
thesubclassname.
• Now, the subclass contains its own variables and methods as well those of thesuperclass
EXAMPLE:
OUTPUT:
Parent Method
Child Method
SUPER KEYWORD:
• The super keyword in java is a reference variable that is used to refer immediate parent class object.
• Wheneveryoucreatetheinstanceofsubclass,aninstanceofparentclassiscreatedimplicitly
i.e. referred by super reference variable.
USE OF SUPER :
• super is used to refer immediate parent class instancevariable
• super() is used to invoke immediate parent classconstructor
• super is used to invoke immediate parent classmethod
1) super is used to refer immediate parent class instancevariable:
class Vehicle
{
int speed=50;
}
class Bike3 extends Vehicle
{
int speed=100; void display()
{
System.out.println(super.speed); //will print speed of Vehicle System.out.println(speed);//will
print speed of Bike
}
public static void main(String args[])
{
Bike3 b=new Bike3(); b.display();
}
}
OUTPUT:
50
100
class Person
{
void message()
{
System.out.println("welcome");
}
}
void display()
{
message();//will invoke current class message() method super.message();//will invoke parent
class message() method
}
public static void main(String args[])
{
Student s=new Student(); s.display();
}
}
OUTPUT:
Welcome to java
Welcome
ClassVehicle
{
Vehicle()
{
System.out.println("Vehicle is created");
}
}
}
public static void main(String args[])
{
Bike b=new Bike();
}
}
OUTPUT:
Vehicle is created
Bike is created
MULTITHREADING INJAVA
MULTITHREADEDPROGRAMMING
Multithreading is a powerful programming tool that makes java distinctly different from its
fellow programming languages.
USES OF MULTITHREADING
• Enables programmers to do multi things at a time.
• A long program can be divided into threads and execute them inparallel.
• Extensively used in java-enabled browsers as Hot.Java
CREATING THREADS
• Threads are implemented in the form of objects that contain a method called run().
• The run() method is the heart and soul of any thread.
• It makes up the entire body of the method.
• It’s the only method in which the thread’s behavior can be implemented.
• The run() method should be invoked by an object of the concerned thread.
• This can be done by creating a thread and initializing it with the help of another method called
start().
Syntax:
public void run()
{
……………….. (statements)
………………..
}
1. Newborn state.
2. Runnablestate
3. Running state
4. Blockedstate
5. Deadstate
NEWBORNSTATE:
• When we create the Thread object, the thread is born and is said to be in Newborn state.
• At this state we can do only one of the following,
1. Schedule it for running using start() method.
2. Kill it using stop() method.
RUNNABLESTATE:
• The runnable state means that the thread is ready for execution and is waiting for the availability of
the processor.
• The process of assigning time to threads is known as time-slicing.
• The first-come, first-serve manner is used here.
• If we want to relinquish control to another thread to equal the priority before it comes, we can use the
yield()method
RUNNING STATE :
• Running means that the processor has given its time to the thread for its execution.
• A running thread may relinquish its control in one of the following situations:
1. It has been suspended using suspend() method. A suspended thread can be resumed by using
the resume() method.
2. It has been made to sleep by using the sleep() method.
3. It has been told to wait until some event occurs using the wait() method.
BLOCKED STATE:
• A thread is said to be blocked when it is prevented from entering into the runnable state and the
running state.
• A blocked thread is considered “not runnable” but not dead, and is fully qualified to run again.
DEAD STATE:
• A running thread ends its life when it has completed executing its run()method.
• It is natural death!.
• A thread can be killed as soon as it is born, or while running or even when it is in “not runnable
“condition.
The Thread class can be extended as follows: class My Thread extends Thread
{
…………………
………………....
}
Now we have a new type of thread MyThread.
EXAMPLE PROGRAM:
import java.lang.*;
m1.start();
m2.start();
}
}
FILES AND STREAM IN JAVA
INTRODUCTION:
• Java I/O (Input and Output) is used to process the input and produce the output based on the input.
• Java uses the concept of stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
• We can perform file handling in java by java IOAPI.
STREAM
• A stream is a sequence of data. In Java a stream is composed of bytes. It's called a stream because it's
like a stream of water that continues to flow.
• In java, 3 streams are created for us automatically. All these streams are attached with console
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
System.out.println("simple message"); System.err.println("errormessage");
Let's see the code to get input fromconsole.
int i=System.in.read();//returns ASCII code of 1st character System.out.println((char)i);//will
print the character
TYPES OF STREAM
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file, an array,
peripheral device or socket.
STREAM CLASS
1) public void write(int)throws IOException: is used to write a byte to the current output
stream.
2)public void write(byte[]) throws is used to write an array of byte to the current
IOException: output stream.
4) public void close()throws IOException: is used to close the current output stream.
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input
stream of bytes.
2) public int available()throws IOException: returns an estimate of the number of bytes that
can be read from the current input stream.
3) public void close()throws IOException: is used to close the current input stream.
FILEOUTPUTSTREAM
EXAMPLE:
USE OF PRINTSTREAM
FILEINPUTSTREAM
EXAMPLE:
import java.io.*; public class FDemo
{
public static void main(String arg[]) throws IOException
{
FileInputStream in=new FileInputStream("Sample.txt"); int i;
while((i=in.read())!=-1)//read() will return -1 if it reaches end of file
{
System.out.println((char)i);
}
}
}
USE OF BUFFEREDREADER EXAMPLE:
import java.io.*; public class FDemo
{
public static void main(String arg[]) throws IOException
{
FileReader in=new FileReader("Sample.txt"); BufferedReader br=new BufferedReader(in);
String s=br.readLine();//reads a line from the file System.out.println(s);
}
}
The exception handling in java is one of the powerful mechanisms to handle the runtime errors so
that normal flow of the application can be maintained.
Exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program.
EXCEPTION HANDLING
Exception Handling is a mechanism to handle runtime errors such as Class NotFound, IO, SQL,
Remote etc.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun micro system says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between checked and unchecked exceptions
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend Runtime Exception are known as unchecked exceptions e.g. Arithmetic Exception,
Null Pointer Exception, Array Index out of Bounds Exception etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemory Error, Virtual Machine Error, Assertion Error etc. Common
scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where Arithmetic Exception occurs
If we divide any number by zero, there occurs an Arithmetic Exception.
int a=50/0;//Arithmetic Exception
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;System.out.println(s.length());//NullPointerException
tr
y
{ //code that may throw exception
EXAMPLE PROGRAM
public class Testtrycatch2
{
public static void main(String args[])
{
tr
y
{ int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
EXAMPLE PROGRAM
class ExceptionThrowDemo
{
public static void main(String args[ ])
{
Syntax:
return_type method_name() throws exception_class_name
{
...
}
UNIT-III
GUI Components - AWT package – Layouts - Containers – Event Package – Event Model –
Painting - Garbage Collection – Java Applets – Applet Application – Swing Fundamentals –
Swing Classes.
11 MARKS
INTRODUCTION
AWT API was introduced in JDK 1.0. Most of the AWT components have become obsolete and
should be replaced by newer Swingcomponents.
AWT API consists of set of classes needed to create GUI application injava
Swing API, a much more comprehensive set of graphics libraries that enhances the AWT, was
introduced as part of Java Foundation Classes (JFC) after the release of JDK1.1.
JFC, which consists of Swing, Java2D, Accessibility API, Internationalization, and Pluggable Look-
and-Feel Support, was an add-on to JDK 1.1 but has been integrated into core Java since JDK1.2.
Java Graphics APIs - AWT and Swing - provide a huge set of reusable GUI components, such as
button, text field, label, choice, panel and frame for building GUI applications. You can simply reuse
these classes rather than re-invent the wheels.
Many AWT classes are now obsolete and they are used only in exceptional circumstances.
AWT Packages
AWT is huge. It consists of 12 packages. But only 2 packages - java.awt and java.awt.event -
arecommonly-used.
1. Component: Components are elementary GUI entities (such as Button, Label, and Text Field.)
2. Container: Containers (such as Frame, Panel and Applet) are used to hold components in a specific
layout. A container cans also hold sub-containers.
In the below example, there are three containers: a Frame and two Panels.
A Frame is the top-level container of an AWT GUI program. A Frame has a title bar (containing an
icon, a title, and the minimize/maximize(restore-down)/close buttons), an optional menu bar and the
content display area.
A Panel is a rectangular area (or partition) used to group related GUI components in a certain
layout. In the above example, the top-level Frame contains two Panels.
There are five components: a Label (providing description), a Text Field (for users to enter text),
and three Buttons (for user to trigger certain programmed actions).
In a GUI program, a component must be kept in a container. You need to identify a container to
hold the components. Every container has a method called add(Component c). A container (says a
Container) can invoke a Container.add(a Component) to add a Component intoitself.
For example,
Each GUI program has a top-level container. The commonly-used top-level containers in AWT are
Frame, Dialog and Applet:
Frame:
A Frame provides the "main window" for the GUI application, which has a title bar (containing
an icon, a title, minimize, maximize/restore-down and close buttons), an optional menu bar, and
the content displayarea.
To write a GUI program, we typically start with a subclass extending from java.awt.Frame to
inherit the main window asfollows:
Dialog:
An AWT Dialog is a "pop-up window" used for interacting with the users. A Dialog has a title-
bar (containing an icon, a title and a close button) and a content display area, as illustrated.
Applet:
An AWT Applet (in package java.applet) is the top-level container for an applet, which is a Java
program running inside a browser.
Secondary containers are placed inside a top-level container or another secondary container. AWT
also provide these secondary containers:
Panel: a rectangular box (partition) under a higher-level container, used to layout a set of
related GUI components. See the above examples for illustration.
ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child
component.
AWT provides many ready-made and reusable GUI components. The frequently-used are: Button,
TextField, Label, Checkbox, CheckboxGroup (radio buttons), List, and Choice, as illustratedbelow.
AWT ComponentS:
Label
A java.awt.Label provides a text description message. Take note that System.out.println() prints to
the system console, not to the graphics screen. You could use a Label to label another component (such
as text field) or provide a text description.
Button
A java.awt.Button is a GUI component that triggers a certain programmed action upon clicking.
TextField
A java.awt.TextField is single-line text box for users to enter texts. (There is a multiple-line text
box called TextArea.) Hitting the "ENTER" key on a TextField object triggers anaction-event.
EXAMPLEPROGRAM:
import java.awt.*; public class AWTDemo
{
public static void main(String args[])
{
Frame f=new Frame("AWTDemo"); f.setSize(500, 500); f.setVisible(true);
p.add(l);
p.add(tf);
p.add(b);
f.add(p);
}
APPLET PROGRAMMING INJAVA
SYNOPSIS
DEFINITION CATEGORIES OF APPLET
STEPS TO CREATE AND EXECUTE AN APPLET APPLET TAG IN HTML
APPLET LIFE CYCLE COLOR CONTROL FONT CONTROL GRAPHICS CLASS
EXAMPLE PROGRAM
DEFINITION
Applets are small applications that are accessed on an internet server.
They are small, dynamic and graphical user interactive program that can execute inside a
webpage displayed by JAVA capable browser such as IE, Netscape navigator etc.
Application:
Animation
multimediapresentation
Real timegames
CATEGORIES OF APPLET
i) Local Applet
ii) Remote Applet
Local Applet :
Remote Applet :
Eg : c:\jdk1.2\bin>javac appl.java
(now the class file (appl.class) is created)
Create a .html file and write html code for getting class file forappl.class
Eg : c:\jdk 1.2\bin>edit appl.html Example code:
<HTML>
<applet code = “appl.class” height=400 width=400 >
</applet>
</html>
Height
Width,
Codeetc.,
There are four stages in the applet life cycle. They are
SYNTAX:
RUNNING STATE
Applet enters the running state when the system calls the start() method of the applet class.
The start() method is also executed automatically after the applet is initialised.
The start () method can be called several times.
SYNTAX :
DISPLAY STATE
An Applet moves to the display state whenever it has to perform some output operations on the
screen.
The paint()methodisusedtoaccomplishthistaskwhenitenterstherunningstate.
SYNTAX
When we leave the page containing the current applet, it enters the idle/stopped state
automatically.
We can also stop the applet explicitly by calling the stop() method.
While using a thread to run an applet , it is mandatory to use stop() method to terminate the
thread.
SYNTAX
SYNTAX
public void destroy()
{
……………..
……………..(Action)
}
COLOR CONTROL
Example :
FONT CONTROL
Example :
GRAPHICS CLASS
g.drawLine( x1 , y1 , x2 , y2);
g.drawOval( left , top , width , height);
g.fillOval( left , top , width , height);
g.drawRoundRect( left , top , width , height);
g.fillRoundRect( left , top , width , height);
g.drawArc( left , top , width , height , startAngle , arcAngle);
g.drawString( string , x , y);
ExampleProgram:
Swing widgets provide more sophisticated GUI components than the earlier Abstract Window
Toolkit. Since they are written in pure Java, they run the same on all platforms, unlike the AWT which
is tied to the underlying platform's windowing system.
Swing supports pluggable look and feel – not by using the native platform's facilities, but by
roughly emulating (imitate)them. This means you can get any supported look and feel on any platform.
Swing’s Features:
Swing is huge and has great depth. Compared with AWT, Swing provides a huge and
comprehensive collection of reusable GUI components, as shown in the Figure below
Main Features:
Swing is written in pure Java (except a few classes) and therefore is 100%portable.
Swing components are lightweight. TheAWT components are heavyweight (in terms of system
resource utilization).
Each AWT component has its own opaque native display, and always displays on top of the
lightweightcomponents.
AWT components rely heavily on the underlying windowing subsystem of the nativeoperating
system.
For example, an AWT button ties to an actual button in the underlying native windowing
subsystem, and relies on the native windowing subsystem for their rendering and processing.
Swing components (JComponents) are written in Java. They are generally not "weight-down"
by complex GUI considerations imposed by the underlying windowingsubsystem.
Swing components support pluggable look-and-feel. You can choose between Java look-and-
feel and the look-and-feel of the underlying OS (e.g., Windows, UNIX orMac).
If the later is chosen, a Swing button runs on the Windows looks like a Windows' button and
feels like a Window's button. Similarly, a Swing button runs on the UNIX looks like a UNIX's
button and feels like a UNIX'sbutton.
SWING COMPONENTS:
JPanel
Jpanel is Swing's version of the AWT class Panel and uses the same default layout, FlowLayout.
JPanel is descended directly from JComponent.
CONSTRUCTORS:
JPanel ()
Constructs a new blank JPanel
METHODS:
JFrame is Swing's version of Frame and is descended directly from that class. The components
added to the frame are referred to as its contents; these are managed by the contentPane. To add a
component to a JFrame, we must use its contentPane instead.
CONSTRUCTORS:
JFrame ()
Creates a blank Button instance.
JFrame (String Text)
Creates a Frame instance with the specified text in the title bar
METHODS:
JLabel
CONSTRUCTORS:
JLabel ()
Creates a blank JLabel instance.
JLabel (String Text)
Creates a JLabel instance with the specified text.
JLabel (String Text, int Alignment)
Creates a JLabel instance with the specified text and horizontal alignment
METHODS:
JButton
The abstract class AbstractButton extends class JComponent and provides a foundation for a family
of button classes, including JButton
CONSTRUCTORS:
JButton ()
Creates a blank JButton instance.
JButton (String Text)
Creates a JButton instance with the specified text.
METHODS:
JTextField
JTextField allows editing of a single line of text. New features include the ability to justify the text
left, right, or center, and to set the text's font.
CONSTRUCTORS:
JTextField()
Creates a blank JTextField instance.
JTextField (String Text)
Creates a JTextField instance with the specified text.
JTextField (int Columns)
Creates a blank JTextField instance with the specified number of columns.
JTextField (String Text, int Columns)
Creates a JTextField instance with the specified text and the specified number of
columns.
METHODS:
JInternalFrame
JWindow
JWindow is Swing's version of Window and is descended directly from that class. Like Window, it
uses BorderLayout by default.
JDialog
JDialog is Swing's version of Dialog and is descended directly from that class. Like Dialog, it uses
BorderLayout by default. Like JFrame and JWindow,
JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass
panes. All dialogs are model, which means the current thread is blocked until user interaction with it
has been completed.
JDialog class is intended as the basis for creating custom dialogs; however, some of the most
common dialogs are provided through static methods in the class JOptionPane.
JPasswordField
JPasswordField (a direct subclass of JTextField) you can suppress the display of input.
Each character entered can be replaced by an echo character.
This allows confidential input for passwords, for example. By default, the echo character is the
asterisk, *.
JTextArea
JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class
JScrollPane to achieve scrolling.
The underlying JScrollPane can be forced to always or never have either the vertical or horizontal
scrollbar;
JRadioButton
JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio
buttons can be associated as a group in which only one button at a time can be selected.
JCheckBox
JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and
it also displays its current state.
JComboBox
JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a
list.
For example,
When the component has focus, pressing a key that corresponds to the first character in some entry's
name selects that entry. A vertical scrollbar is used for longer lists.
JList
JList provides a scrollable set of items from which one or more may be selected. JList can be
populated from an Array or Vector.
JList does not support scrolling directly, instead, the list must be associated with a scrollpane.
The view port used by the scroll pane can also have a user-defined border. JList actions are handled
using ListSelectionListener.
JTabbedPane
JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text
and an image.
JToolbar
JToolbar contains a number of components whose type is usually some kind of button which can
also include separators to group related components within the toolbar.
JMenubar
JMenubar can contain several JMenu's. Each of the JMenu's can contain a series of JMenuItem 's
that you can select. Swing provides support for pull-down and popup menus.
Scrollable JPopupMenu
Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so many
items in a popup menu that exceeds the screen visible height.
EXAMPLE PROGRAM:
public classCalculator
{
public Calculator()
{
JFrame f=new JFrame("CALCULATOR"); f.setVisible(true);
f.setSize(300,300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Layouts are invoked using layout manager interface and set by the setlayoutmethod.
Java LayoutManagers are used to save you the effort of manually putting Components where
you want them on aContainer.
Even more useful is the fact that a LayoutManager object will handle repositioning your objects
whenever the Container isresized.
TYPES OF LAYOUT:
Flow Layout
BorderLayout
GridLayout
GridBagLayout
The Flow Layout manager arrange components in its container horizontally left to right and top
to bottom starting from center by default.
If you try to add more components in a single row then the row splits into secondrow.
Justification - FlowLayout.LEFT, FlowLayout.CENTER orFlowLayout.RIGHT.
Default is Flow Layout.CENTER.
The components added to a container using Flow Layout manager, even if you resize the
window, component does not change it's original size.
FlowLayout honors the preferred size of the component.
EXAMPLE:
}
}
Output:
If you resize the window to smaller size then the top row splits into second row but the the size of
the component does not change, which means Flow Layout manager honors the component preferred
size.
BORDERLAYOUT MANAGER
Example :
Output:
If you don't specify the location of the component, then the center is the default location ofthe
component in the BorderLayout, and component occupies all the leftover space.
While adding a component you can use "North", "South" , "East", "West", "Center" or the
following constants to specify the location of the component. You can also specify mixing of
both.
Output:
If you use Border Layout when you resize the window, the components in the container also
resized.
GRIDLAYOUT MANAGER
The Grid Layout manager divides the space in the container in to ROWS AND COLUMNS
specified in the constructor.
Basically it divides the region into number of rows and columns which you specified while
setting the layout manager for the container.
Example:
Output:
If you use GridLayout manager and when you resize the window all the components in the
container also resized.
GridBag Layout determines the number of rows and columns from the constraints placedupon
the components it laysout.
It does not require providing the rows and columns as in theGridLayout.
It allows spanning the components to more than one grid cell.
Output:
4. JAVA GRAPHICS CLASS INDETAIL
Graphics:
Java supports graphics along with the AWT. A graphics context is encapsulated by the graphics
class and obtained in 2 ways
It is passed to an applet when one of its various methods such as paint() and update() is called.
It is returned by the getGraphics() method of component.
Graphic class defines a number of drawing function. Each shape can be drawn edge-only or filled.
Methods are:
drawLine
Draws a line between the coordinates (x1,y1) and (x2,y2). The line is drawn below and to the
left of the logical coordinates
public abstract void drawLine(int x1,int y1, int x2, int y2)
Parameters:
x1 - the first point's x coordinate y1 - the first point's y coordinate x2 - the second point's x
coordinate y2 - the second point's ycoordinate
drawRect
Draws the outline of the specified rectangle using the current color. Use drawRect(x, y, width-
1, height-1) to draw the outline inside the specified rectangle.
Parameters:
fillRect
Fills the specified rectangle with the current color. public abstract void fillRect(int x, int y,
int width, int height) Parameters:
x - the x coordinate y - the y coordinate
width - the width of the rectangle height - the height of the rectangle
Color can be given to the shapes drawn using draw methods. Methods are
getColor
setColor
Sets the current color to the specified color. All subsequent graphics operations will use this
specified color.
Parameters:
setPaintMode
Sets the default paint mode to overwrite the destination with the current color. public abstract
void setPaintMode()
WORKING WITH FONTS:
getFont
setFont
Sets the font for all subsequent text-drawing operations. public abstract void setFont(Font font)
Parameters:
getFontMetrics
getFontMetrics
Gets the current font metrics for the specified font. public abstract FontMetrics
getFontMetrics(Font f) Parameters:
f - the specified font
Clears the specified rectangle by filling it with the current background color of the current
drawing surface.
Creates a new Graphics Object with the specified parameters, based on the original Graphics
Object.
dispose()
scale(float,float)
setColor(Color)
setXORMode(Color)
Sets the paint mode to alternate between the current color and the new specified color.
toString()
translate(int,int)
Translates the specified parameters into the origin of the graphics context.
Any action that user performs on a GUI component must be listened and necessary action should to
be taken.
For example, if a user clicks on a Exit button, then we need to write code to exit the program. we
need to know that the user has clicked the button. This process of knowing is called as
listening. The action done by the user is called an event.Writing the corresponding codefora
user action is called as Event handling
COMPONENTS OF EVENT HANDLING
• Listeners: A listener is an object that listens to the event. A listener gets notified when an event
occurs
Source object fires event event upon triggered. For example, clicking an Button fires an
ActionEvent, mouse-click fires MouseEvent, key-type fires KeyEvent,etc.
The source and listener understand each other via an agreed-upon interface.
For example, if a source is capable of firing an event called XxxEvent (e.g., MouseEvent)
involving various operational modes (e.g., mouse-clicked, mouse-entered, mouse-exited, mouse-
pressed, and mouse-released).
Firstly, we need to declare an interface called XxxListener (e.g., MouseListener) containing
the names of the handler methods. Recall that an interface contains only abstract methods
without implementation.
For example,
// A Mouse Listener interface, which declares the signature of the handlers
// for the various operational modes. public interface Mouse Listener {
public void mouse Pressed(MouseEvent evt); // Called back upon mouse-button pressed public void
mouse Released(MouseEvent evt); // Called back upon mouse-button released public
voidmouseClicked(MouseEvent evt); // Called back upon mouse-buttonclicked
(pressed and released)
public void mouse Entered(MouseEvent evt); // Called back when mouse pointer entered
thecomponent
public voidmouseExited(MouseEventevt); // Called back when mouse pointer exited the
component
}
Secondly, all the listeners interested in the XxxEvent must implement the
XxxListener interface. That is, the listeners must provide their own implementations (i.e., programmed
responses) to all the abstract methods declared in the XxxListener interface. In this way, the listenser(s)
can response to these eventsappropriately.
For example,
@Override
public void mouseReleased(MouseEvent e) { System.out.println("Mouse-button released!");
}
@Override
public void mouseClicked(MouseEvent e) { System.out.println("Mouse-button clicked (pressed
and released)!");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse-pointer entered the source component!");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited-pointer the source component!");
}
}
Thirdly, in the source, we need to maintain a list of listener object(s), and define two
methods: addXxxListener() and removeXxxListener() to add and remove a listener from this list.
In summary, we identify the source, the event-listener interface, and the listener object. The
listener must implement the event-listener interface. The source object then registers listener object
via theaddXxxListener()method:
3. The source create an XxxEvent object, which encapsulates the necessary information about the
activation. For example, the (x, y) position of the mouse pointer, the text entered,etc.
4. Finally, for each of the listeners in the listener list, the source invokes the appropriate handler on the
listener(s), which provides the programmedresponse.
In brief, triggering a source fires an event to all its registered listeners, and invoke an
appropriate handler of the listener.
EVENT HANDLING INTERFACES AND ITS METHODS
UNIT – IV
Generics – Collections - Utility Packages – Input Output Packages - Inner Classes - Java Database
Connectivity – Java Security
Collection Framework provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, deletion etc. can
be performed by Java Collection Framework.
Collection simply means a single unit of objects. Collection framework provides many interfaces
(Set, List, Queue, Deque etc.) and classes (Array List, Vector, LinkedList, Priority Queue, HashSet, Linked
HashSet, Tree Set etc).
Collection framework represents a unified architecture for storing and manipulating group of
object.
It has:
1. Interfaces and its implementations I. e. classes
2. Algorithm
The java. util package contains all the classes and interfaces for Collection framework.
METHODS OF COLLECTION INTERFACE
There are many methods declared in the Collection interface. They are as follows:
ITERATOR INTERFACE
Iterator interface provides the facility of iterating the elements in forward direction only
LinkedList
uses doubly linked list to store the elements. It extends the Abstract List class and implements
List and Deque interfaces.
can contain duplicate elements.
maintains insertion order.
not synchronized.
No random-access.
manipulation fast because no shifting needs to be occurred.
can be used as list, stack or queue
EXAMPLE
SET INTERFACE
The Set interface is used to represent a group of unique elements. It extends the Collection
interface. The class HashSet, Linked HashSet implements the Set interface.
contains unique elements only like Hash Set. It extends HashSet class and implements Set interface.
maintains insertion order.
SORTEDSET INTERFACE
The Sorted Set interface extends the Set interface. It provides extra functionality of keeping the
elements sorted. So Sorted Set interface is used to represent collections consisting of unique, sorted
elements. The class Tree Setis an implementation of interface Sorted Set.
Sorted set Implemented Class Tree set
containsuniqueelementsonlylikeHashSet.TheTreeSetclassimplementsNavigableSet interface that
extends the SortedSetinterface.
maintains ascending order
MAP INTERFACE
The Map Interface is a basic interface that is used to represent mapping of keys to values. A map
contains values based on the key i.e. key and value pair. Each pair is known as an entry. Map contains only
unique elements. Classes HashMap and Linked HashMap are implementations of Map interface
Linked HashMap
ALinkedHashMapcontainsvaluesbasedonthekey.ItimplementstheMapinterfaceand extends
HashMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order.
2. UTILITYPACKAGE
The java.util package defines a number of useful classes, primarily collections classes that
are useful for working with groups of objects. This package should not be considered merely a
utility package that is separate from the rest of the language; in fact, Java depends directly on
several of the classes in this package. Figure 1 shows the collection classes of this package, while
Figure 2 shows the other classes.
It contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).
LIST OF INTERFACES
INTERFACES DESCRIPTION
Collection<E> The root interface in the collection hierarchy.
Comparator<T> A comparison function, which imposes a total ordering on some collection
of objects.
Deque<E> A linear collection that supports element insertion and removal at both ends.
LIST OF CLASSES
CLASS DESCRIPTION
Abstract Collection< This class provides a skeletal implementation of the Collection interface, to
E> minimize the effort required to implement this interface.
Abstract List<E> This class provides a skeletal implementation of the List interface to minimize
the effort required to implement this interface backed bay "random access"
data store (such as an array).
Abstract Map<K, V> This class provides a skeletal implementation of the Map interface, to
minimize the effort required to implement this interface.
AbstractMap.Simpl An Entry maintaining a key and a value.
eEntry<K,V>
AbstractMap.Simpl An Entry maintaining an immutable key and value.
eImmutableEntry<
K,V>
AbstractQueue<E> This class provides skeletal implementations of some Queue operations.
AbstractSequential This class provides a skeletal implementation of the List interface to minimize
List<E> the effort required to implement this interface backed bya "sequential access"
data store (such as a linkedlist).
AbstractSet<E> This class provides a skeletal implementation of the Set interface to minimize
the effort required to implement this interface.
ArrayDeque<E> Resizable-array implementation of the Deque interface.
ArrayList<E> Resizable-array implementation of the List interface.
Arrays This class contains various methods for manipulating arrays (such as sorting
and searching).
BitSet This class implements a vector of bits that grows as needed.
Calendar The Calendar class is an abstract class that provides methods for converting
between a specific instant in time and a set of calendarfields such as YEAR,
MONTH, DAY_OF_MONTH,HOUR, and so on, and for
manipulating the calendar fields, such as getting the date of the next week.
Collections This class consists exclusively of static methods that operate on or return
collections.
Currency Represents a currency.
Date The class Date represents a specific instant in time, with millisecond precision.
Dictionary<K,V> The Dictionary class is the abstract parent of any class, such as Hashtable,
which maps keys to values.
EnumMap<K A specialized Map implementation for use with enum type keys.
extends Enum<K>,V
>
EnumSet<E extends A specialized Set implementation for use with enum types.
Enum<E>>
EventListenerProxy An abstract wrapper class for an EventListener class which associates a set of
<T additional parameters with the listener.
extends EventListen
er>
EventObject The root class from which all event state objects shall be derived.
FormattableFlags FomattableFlags are passed to the Formattable.formatTo() method and
modify the output format for Format tables.
Formatter An interpreter for printf-style format strings.
GregorianCalendar GregorianCalendar is a concrete subclass of Calendar and provides the
standard calendar system used by most of the world.
HashMap<K,V> Hash table based implementation of the Map interface.
HashSet<E> This class implements the Set interface, backed by a hash table (actually a
HashMap instance).
Hashtable<K,V> This class implements a hash table, which maps keys to values.
IdentityHashMap<K This class implements the Map interface with a hash table, using reference-
,V> equality in place of object-equality when comparing keys (and values).
LinkedHashMap<K, Hash table and linked list implementation of the Map interface, with
V> predictable iteration order.
LinkedHashSet<E> Hash table and linked list implementation of the Set interface, with predictable
iteration order.
LinkedList<E> Doubly-linked list implementation of the List and Deque interfaces.
ListResource Bundl e List ResourceBundle is an abstract subclass of ResourceBundle that manages
resources for a locale in a convenient and easy to use list.
Locale A Locale object represents a specific geographical, political, or cultural region.
Locale. Builder Builder is used to build instances of Locale from values configured by the
setters.
Objects This class consists of static utility methods for operating on objects.
Observable This class represents an observable object, or "data" in the model-view
paradigm.
PriorityQueue<E> An unbounded priority queue based on a priority heap.
Properties The Properties class represents a persistent set of properties.
Property Permissio This class is for property permissions.
n
Property Resource Property ResourceBundle is a concrete subclass of Resource Bundle that
Bundle manages resources for a locale using a set of static strings from a property file.
Timer A facility for threads to schedule tasks for future execution in a background
thread.
TimerTask A task that can be scheduled for one-time or repeated execution by a Timer.
TimeZone TimeZone represents a time zone offset, and also figures out daylight savings.
This class defines static methods for sorting, searching, and performing other useful operations on arrays. It
also defines the as List () method, which returns a List wrapper around a specified array of objects.
Any changes made to the List are also made to the underlying array. This is a powerful method that allows any
array of objects to be manipulated in any of the ways a List can be manipulated. It provides a link between
arrays and the Java collections framework.
The various sort() methods sort an array (or a specified portion of an array) in place. Variants of the method
are defined for arrays of each primitive type and for arrays of Object. For arrays of primitive types, the sorting
is done according to the natural ordering of the type.
For arrays of objects, the sorting is done according to the specified Comparator, or, if the array contains only
java.lang.Comparable objects, according to the ordering defined by that interface. When sorting an array of
objects, a stable sorting algorithm is used so that the relative ordering of equal objects is not disturbed. (This
allows repeated sorts to order objects by key and subkey, for example.)
The binary Search() methods perform an efficient search (in logarithmic time) of a sorted array for a specified
value. If a match is found in the array, binary Search() returns the index of the match. If no match is found, the
method returns a negative number.
For a negative return value r, the index -(r+1) specifies the array index at which the specified value can be
inserted to maintain the sorted order of the array. When the array to be searched is an array of objects, the
elements of the array must all implement java. lang.Comparable, or you must provide a Comparator object to
compare them.
The equals() methods test whether two arrays are equal. Two arrays of primitive type are equal if they
contain the same number of elements and if corresponding pairs of elements are equal according to the ==
operator.
Two arrays of objects are equal if they contain the same number of elements and if corresponding
pairs of elements are equal according to the equals() method defined by those objects. The fill() methods fill
an array or a specified range of an array with the specified value.
This abstract class defines methods that perform date and time arithmetic. It also includes
methods that convert dates and times to and from the machine-usable millisecond format used by the
Date class and units such as minutes, hours, days, weeks, months, and years that are more useful to
humans. As an abstract class,Calendar cannot be directlyinstantiated.
Instead, it provides static getInstance() methods that return instances of a Calendar subclass
suitable for use in a specified or default locale with a specified or default time zone. See also Date, Date
Format, and Time Zone.
Calendar defines a number of useful constants. Some of these are values that represent days of
the week and months of the year. Other constants, such as HOUR and DAY_OF_WEEK, represent
various fields of date and time information. These field constants are passed to a number of Calendar
methods, such as get() and set(), in order to indicate what particular date or time field is desired.
setTime() and the various set() methods set the date represented by a
Calendar object. The add() method adds (or subtracts) values to a calendar field, incrementing
the next larger field when the field being set rolls over. roll() does the same, without modifying anything
but the specified field. before() and after() compare two Calendar objects.
Many of the methods of the Calendar class are replacements for methods of Date that have been
deprecated as of Java 1.1. While the Calendar class converts a time value to its various hour, day, month,
and other fields, it is not intended to present those fields in a form suitable for display to the end user.
That function is performed by the java.text.DateFormat class, which handles internationalization issues.
//
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
Before generics, we can store any type of objects in collection i.e. non-generic.
Now generics, forces the java programmer to store specific type of objects.
1) Type-safety:Wecanholdonlytypeofobjectsingenerics.Itdoesn’tallowtostoreother objects.
2) Type casting is not required: There is no need to typecast the object. Before Generics, we need to
typecast.
List list = new ArrayList(); list.add("hello");
String s = (String) list.get(0);//typecasting After Generics, we don't need to typecast the
object.
List<String> list = new ArrayList<String>(); list.add("hello");
String s = list.get(0);
Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.
import java.util.*;
class TestGenerics1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>(); list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
Iterator<String> itr=list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output
: element is: jai rahul
jai
GENERIC CLASS
A class that can refer to any type is known as generic class. Here, we are using T type parameter to
create the generic class of specific type.
Let’s see the simple example to create and use the generic class.
The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type you
specify for the class, will be used to store and retrieve the data.
Using generic class:
class TestGenerics3{
public static void main(String args[]){ MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
//m.add("vivek");//Compile time error System.out.println(m.get());
}}
Output: 2
GENERIC METHOD
Like generic class, we can create generic method that can accept any type of argument.
Let’s see a simple example of java generic method to print array elements. We are using here E to denote the
element.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
2) Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
o b)Anonymous innerclass
o c)Local innerclass
2. Static nested class
Type Description
Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.
data is30
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used if you must
override method of class or interface. Java Anonymous inner class can be created by two ways:
Output:
nicefruits
Java anonymous inner class example using interface interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){ Eatable e=new Eatable(){
public void eat(){System.out.println("nice fruits");}
};
e.eat();
}
}
Output:
nicefruits
JAVA LOCAL INNER CLASS
A class i.e. created inside a method is called local inner class in java. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.
30
The standard defined by Sun Microsystems, allowing individual providers to implement and extend
the standard with their own JDBC drivers.
TASKS OF JDBC:
The JDBC API supports both two-tier and three-tier models for database access.
> Two-tier model -- a Java applet or application interacts directly with the database.
> Three-tier model -- introduces a middle-level server for execution of business logic:
JDBC ARCHITECTURE:
Class-I:
JDBC:ODBC ( mainly for Desktop Applications)
> Use bridging technology
> Requires installation/configuration on client machines
> Not good for Web
Class-II:
Native API Drivers (Vendor Specific drivers)
> Requires installation/configuration on client machines
> Used to leverage existing CLIlibraries
> Usually notthread-safe
> Mostly obsolete now
> e.g. Intersolv Oracle Driver, WebLogic drivers
Class-III:
Network API
> Calls middleware server, usually on database host
> Very flexible & allows access to multiple databases using one driver
> Only need to download one driver
> But it’s another server application to install and maintain
Class IV : > e.g. Symantec DB Anywhere
Network Protocol Driver (used for Network based Applications)
> Pure Java Drivers
> Use Java networking libraries to talk directly to database engines
> need to download a new driver for each database engine
> e.g. Oracle, MySQL
1) Connect
2) Query
3) Process Results
4) Close
1) CONNECT
DRIVER
DATABASE
Two Ways:
1) Using Class.forName()
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Using DriverManager.registerDriver()
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
i) Create a Statement
ii) Query The Database
i) Create a Statement
The Statement Object
A Statement object sends your SQL statement to the database.
You need an active connection to create a JDBC Statement.
Create the prepared statement, identifying variables with a question mark (?).
pstmt.setXXX(index, value);
pstmt.executeQuery(); pstmt.executeUpdate();
Eg:
3. PROCESS RESULTS
i) Step through
theresults
ii) Assign Values to the results
a) Using ColumnName
String val = rset.getString(colname);
b) Using ColumnIndex
String val = rset.getString(colIndex);
EG:
while (rset.next())
{
String title = rset.getString("TITLE"); String year =
rset.getString("YEAR");
… // Process or display the data
}
4. CLOSE
i) Close the ResultSetobject.
rset.close();
ii) Close the Statementobject.
stmt.close();
iii) Close the connection (not necessary for server-sidedriver).
conn.close();
EXAMPLE PROGRAM:
public void AddStudent()
{
tr
y
{ Class.forName("com.mysql.jdbc.Driver"); Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","admin");
int rollno = Integer.parseInt(txtRollno.getText());
String name = txtName.getText();
String department = txtDept.getText();
int mark1 =Integer.parseInt(txtMark1.getText());
int mark2 =Integer.parseInt(txtMark2.getText());
int mark3 =Integer.parseInt(txtMark3.getText());
int total = mark1 + mark2 +mark3;
String result;
if(mark1 >=50 && mark2 >=50 && mark3 >=50)
{
result = "Pass";
}
els
e
{ result = "Fail";
10. JAVASECURITY
The Java platform provides a number of features designed to improve the security of Java
applications. This includes enforcing runtime constraints through the use of the Java Virtual
Machine (JVM), a security manager that sandboxes un trusted code from the rest of the
operating system, and a suite of security APIs that Java developers canutilise.
Despite this, criticism has been directed at the programming language, and Oracle, due to an
increase in malicious programs that revealed security vulnerabilities in the JVM, which were
subsequently not properly addressed by Oracle in a timelymanner.
Java's security model is focused on protecting users from hostile programs downloaded from un
trusted sources across a network. To accomplish this goal, Java provides a customizable
"sandbox" in which Java programsrun.
A Java program must play only inside its sandbox. It can do anything within the boundaries of
its sandbox, but it can't take any action outside those boundaries. The sandbox for un trusted
Java applets, for example, prohibits many activities, including:
The sandbox security model is an intrinsic part of Java's architecture. The sandbox, a shell that
surrounds a running Java program, protects the host system from malicious code. This security
model helps give users confidence in downloading un trusted code across network.
The sandbox is designed into the Java virtual machine and Java API. It touches all corners of the
architecture, but can be divided into four main components:
Several built-in security mechanisms are operating as Java virtual machine bytecodes. You have
likely heard these mechanisms listed as features of the Java programming language that make Java
programs robust. They are, not surprisingly, also features of the Java virtual machine. The
mechanisms are:
Type-safe reference casting
Structured memory access (no pointer arithmetic)
Automatic garbage collection (can't explicitly free allocated memory)
Array bounds checking
Checking references for null
Whenever you use an object reference, the JVM watches over you. If you attempt to cast a reference
to a different type, the JVM makes sure the cast is valid. If you access an array, the JVM ensures
the element you are requesting actually exists within the bounds of the array. If you ever try and use
a null reference, the JVM throws an exception.
The following sections explain the basic concepts necessary to understand how this model works:
Permissions
Protection Domains and Security Policies
Security Managers and Access Controllers
PERMISSIONS
A permission is a set of permissible operations on some set of resources. Every Java class loaded
into a running environment is assigned a set of permissions according to some criteria, each
permission granting a specific access to a particular resource. For example, a permission can
constrain the access to a database or disallow the editing of agile.
In code-based security, permissions are granted based on code characteristics, such as where the
code is coming from and whether it is digitally signed (and by whom). A codebase is a URL
indicating code location, such as the following:
java.security.AllPermission
java.lang.RuntimePermission(includes only a resourcetarget)
java.io.FilePermission(includes a resource andactions)
Thefollowingsampleentryinapolicyfileillustrateshowcodelocatedinthedirectory
/home/sysadmin and signed by jJoe is granted read access to the file /tmp/abc:
grant signedby jJoe codeBase "file:/home/sysadmin/" { permission java.io.FilePermission
"/tmp/abc", "read";
};
The signedBy clause in the preceding example is optional. If omitted, the permission is granted
to all code in the specified location. Figure 1-1illustrates the relationship between classes,
protection domains, and permissionsets.
A security manager is the component of the Java security model that enforces the permissions
granted to applications by security policies. For any security-sensitive operation that an application
attempts, the security manager checks the application permissions and determines whether the operation
should be allowed. The Java class java.lang.SecurityManagerrepresents a security manager and includes
several check methods to determine whether an operation should be allowed or a given permission is in
effect.
An access controller is the object used by the security manager (or directly by an application, if the
security manager is not enabled) to control operations and decisions. More specifically, an access
controller:
Decides whether access to a system resource should be allowed or denied, based on the current
security policy ineffect.
Java Beans - Application Builder Tools - Using the Bean Developer Kit -Jar FilesIntrospection – BDK –
Using BeanInfo Interface – Persistence - Java Beans API Using Bean Builder - Networking Basics - Java and
the Net – InetAddress – TCP/IP Client Sockets – URL – URL Connection – TCP/IP Server - Sockets - A
Caching Proxy HTTP Server – Datagrams – RMI.
JAVABEANS
Software components are self-contained software units developed according to the motto
“Developed them once, run and reused them everywhere”. Or in other words, reusability is the main
concern behind the component model.
A software component is a reusable object that can be plugged into any target software
application. You can develop software components using various programming languages, such as C,
C++, Java, and Visual Basic
Bean that provides real-time price information from a stock or commodities exchange.
ELEMENTS OF A JAVABEAN:
Properties
Similar to instance variables.
A bean property is a named attribute of a bean that can affect its behavior or appearance.
Examples of bean properties include color, label, font, font size, anddisplay size.
Methods
Same as normal Java methods.
Every property should have accessor (get) and mutator (set)method.
All Public methods can be identified by the introspection mechanism.
There is no specific naming standard for these methods.
Events
Similar to Swing/AWT event handling.
Persistence: Is the ability of JavaBean to save its state to disk or storage device and restore the saved
state when the JavaBean is reloaded.
Communication: Is the ability of JavaBean to notify change in its properties to other JavaBeans or the
container.
Introspection: - Is the ability of a JavaBean to allow an external application to query the properties,
methods, and events supported by it.
SERVICES OF JAVABEAN COMPONENTS
Builder support: Enables you to create and group multiple JavaBeans in an application.
Layout- Allows multiple JavaBeans to be arranged in a development environment.
Interface publishing: Enables multiple JavaBeans in an application to communicate with each other.
Event handling: Refers to firing and handling of events associated with a JavaBean.
Persistence: Enables you to save the last state of JavaBean
FEATURES OF A JAVABEAN
Support for “introspection” so that a builder tool can analyze how a bean works. ®
Support for “customization” to allow the customization of the appearance and behavior of a bean.
Supportfor“events”asasimplecommunicationmetaphorthancanbe used to connect up beans.
Support for “properties”, both for customization and for programmatic use.®
Support for “persistence”, so that a bean can save and restore its customized state.
BeanInfo
Methods
Customizer JAR
BEAN DEVELOPMERKIT
Java Workshop2.0 Sun Microsystems., Inc., Complete IDE that supports applet,
application and bean development
Beans Development
Kit Sun Microsystems., Inc., Supports only Beans development
TOOLBOX WINDOW:
Lists the sample JavaBeans of BDK.
BEANBOX WINDOW:
Is a workspace for creating the layout of JavaBean application. The following figure shows the Bean
Box window:
PROPERTIES WINDOW:
Displays all the exposed properties of a JavaBean. You can modify JavaBean properties in the
properties window.
import java.awt.*;
public class MyBean extends Canvas
{
public MyBean()
{
setSize(70,50); setBackground(Color.green);
}
}
4. Create a manifestfile
Manifest File
· The manifest file for a JavaBean application contains a list of all the class files that make up a JavaBean.
· The entry in the manifest file enables the target application to recognize the JavaBean classes for an
application.
· For example, the entry for the MyBean JavaBean in the manifest file is as shown:
Manifest-Version: 1.0
Name: MyBean.class
Java-Bean: true
Note: write that 2 lines code in the notepad and save that file as MyBean.mf
· Press the Enter key after typing each line in the manifest file.
· Leave a space after the colon.
· Type a hyphen between Java and Bean.
· No blank line between the Name and the Java-Bean entry.
5. Generate a JAR file
JAR file:
JAR file allows you to efficiently deploy a set of classes and their associated resources. JAR file makes
it much easier to deliver, install, and download. It is compressed.
6. Start BDK
Go to-> C:\bdk1_1\beans\beanbox
Click on run.bat file. When we click on run.bat file the BDK software automatically started.
7. Load Jarfile
Go to
Bean box->File->Load jar. Here we have to select our created jar file when we click on ok, our bean(user
defined) My Bean appear in the Toolbox.
If you want to apply events for that bean, now we apply the events for that Bean.
INTROSPECTION, PROPERTIES AND PERSISTENCE IN JAVA BEANS
Introspection:
Introspection can be defined as the technique of obtaining information about bean properties,
events,and methods.
Basically, introspection means analysis of bean capabilities.
Introspection is the automatic process by which a builder tool finds out which properties, methods,
and events a bean supports.
Introspection describes how methods, properties, and events are discovered in the beans that you
write.
This process controls the publishing and discovery of bean operations and properties
Without introspection, the JavaBeans technology could not operate.
B
4. Introspection:
Allows automatic analysis of a java beans component
Enables a builder tool to analyze how a bean works.
(Or)
A mechanism that allows classes to publish the operations and properties they support and a
mechanism to support the discovery of such mechanism.
Introspection can be defined as the technique of obtaining information about bean properties,
events,and methods.
Basically, introspection means analysis of bean capabilities
2) In the second way, an additional class is provided that explicitly supplies this information.
A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples of
bean properties include color, label, font, font size, and display size.
Properties are used to accept input from an end user to customize a JavaBean
.
Properties can retrieve and specify the values of various attributes, which determine the behavior of
a JavaBean.
Types of JavaBeans Properties
· Simple properties
· Boolean properties
· Indexed properties
Simple Properties:
Simple properties refer to the private variables of a JavaBean that can have only a single value.
Simple properties are retrieved and specified using the get and set methods respectively.
A read/write property has both methods to access its values. The get method used to read the value of
the property. The set method that sets the value of the property.
The set XX () and get XX () methods are the heart of the java beans properties mechanism. This is also
called getters and setters. These accessor methods are used to set the property.
Ex:
proteinoid;
publicvoidsetId(intid)
{
this.id = id;
}
public StringgetName()
{
returnname;
}
Boolean Properties:
A Boolean property is a property which is used to represent the values True or False. Have either of the two
values, TRUE or FALSE.
It can identified by the following methods:
Syntax:
Let N be the name of the property and T be the type of the value then public boolean isN();
public void setN(Boolean parameter); public boolean getN();
public boolean is<PropertyName>()
public boolean get<PropertyName>()
Ex:
public Boolean dotted=false;
Indexed Properties:
Indexed Properties are consisting of multiple values. If a simple property can hold an array of value, they
are no longer called simple but instead indexed properties. The method’s signature must be adapted
accordingly.
An indexed property may expose set/get methods to read/write one element in the array (so-called
’index getter/setter’) and/or so-called ’array getter/setter’ which read/write the entire array.
Indexed Properties enable you to set or retrieve the values from an array of property values.
Syntax:
public int [] get<Property Name>()
Ex:
privatedoubledata[ ];
publicdoublegetData(intindex)
{
returndata[index];
}
publicvoidsetData(intindex, doublevalue)
{
data[index] = value;
}
public double[ ] getData()
{
returndata;
}
publicvoidsetData(double[ ] values)
{
data = new double[values.length]; System.arraycopy(values, 0, data, 0, values.length);
}
The properties window of BDK does not handle indexed properties. Hence the output cannot be displayed here.
Bound Properties:
A bean that has a bound property generates an event when the property is changed.
Bound Properties are the properties of a JavaBean that inform its listeners about changes in its
value
s. Bound Properties are implemented using the PropertyChangeSupport class and its methods. Bound
Properties are always registered with an external event listener.
The event is of type PropertyChangeEvent and is sent to objects that previously registered an interest in
receiving such notifications bean with bound property - Event source Bean implementing listener -- event target
To provide this notification service a Java Bean needs to have the following two methods:
Constrained Properties:
It generates an event when an attempt is made to change it value Constrained Properties are
implemented using the PropertyChangeEvent class
Beans generate events and these events can be sent to other objects.
Event means any activity that interrupts the current ongoing activity.
User-defined JavaBeans interact with the help of user-defined events, which are also called custom
events. You can use the Java event delegation model to handle these custom events.
• Event Source: Generates the event and informs all the event listeners that are registered
with it.
• Event Listener: Receives the notification, when an event source generates an event.
• Event Object: Represents the various types of events that can be generated by the event
sources.
The classes and interfaces that you need to define to create the custom JavaBean events are:
• An event class to define a custom JavaBean event.
• An event listener interface for the custom JavaBean event.
• An event handler to process the custom JavaBean event.
• A target Java application that implements the custom event.
The event class that defines the custom event extends the Event Object class of the java.util package.
For example,
public class NumberEvent extends EventObject
{
public int number1,number2;
public NumberEvent(Object o,int number1,int number2)
{
super(o); this.number1=number1; this.number2=number2;
}
}
Syntax:
public void addTListener(TListener eventListener);
public void addTListener(TListener eventListener)throws TooManyListeners; public void
removeTListener(TListener eventListener);
The target application that uses the custom event implements the custom listener.
For example,
PERSISTENCE
Persistence means an ability to save properties and events of our beans to non-volatile storage and
retrieve later. It has the ability to save a bean to storage and retrieve it later Configuration settings are saved
It is implemented by Java serialization.
If a bean inherits directly or indirectly from Component class it is automatically Serializable. Transient
keyword can be used to designate data members of a Bean that should not be serialized.
Enables developers to customize Beans in an application builder, and then retrieve those Beans, with
customized features intact, for future use, perhaps in another environment.
Automatic Persistence:
Automatic persistence are java’s built-in serialization mechanism to save and restore the state of a
bean.
External Persistence:
External persistence, on the other hand, gives you the option of supplying your own custom classes to
control precisely how a bean state is stored and retrieved.
4) BEANINFO INTERFACE IN JAVABEANS
Interface Description
Applet Initializer Methods in this interface are used to initialize Beans that are also applets.
Bean Info This interface allows the designer to specify information about the events,
methods, and properties of a Bean.
Customizer This interface allows the designer to provide a graphical user interface through
which a bean may be configured.
Design Mode Methods in this interface determine if a bean is executing in design mode.
Exception Listener A method in this interface is invoked when an exception has occurred.
Property Editor Objects that implement this interface allow the designer to change and display
property values.
Visibility Methods in this interface allow a bean to execute in environments where the GUI
is not available.
you can explicitly expose a Bean's features in a separate, associated class that implements the
BeanInfointerface.
By associating a Bean Info class with your Bean, you can:
BEANINFO INTERFACE
A bean implementor who wishes to provide explicit information about their bean may provide a Bean
Info class that implements this Bean Info interface and provides explicit information about the methods,
properties, events, etc., of their bean.
A bean implementor doesn't need to provide a complete set of explicit information. You can pick and choose
which information you want to provide and the rest will be obtained by automatic analysis using low-level
reflection of the bean classes' methods and applying standard design patterns.
You get the opportunity to provide lots and lots of different information as part of the various XyZDescriptor
classes. But don't panic, you only really need to provide the minimal core information required by the various
constructors.
Method Summary
int getDefaultEventIndex()
A bean may have a "default" event that is the event that will mostly
commonly be used by humans when using the bean.
int getDefaultPropertyIndex()
A bean may have a "default" property that is the property that will mostly
commonly be initially chosen for update by human's who are
customizing the bean.
EventSetDescriptor[] getEventSetDescriptors()
Gets the beans EventSetDescriptors.
PropertyDescriptor[] getPropertyDescriptors()
Gets the beans PropertyDescriptors.
Feature Descriptors
BeanInfo classes contain descriptors that precisely describe the target Bean's features. The BDK
implements the following descriptor classes:
FeatureDescriptor is the base class for the other descriptor classes. It declares the aspects common to all
descriptor types.
Bean Descriptor describes the target Bean's class type and name, and describes the target Bean's
customizer class if it exists.
Property Descriptor describes the target Bean’s properties.
Indexed Property Descriptor is a subclass of Property Descriptor, and describes the target Bean's
indexed properties.
EventSetDescriptor describes the events the target Bean fires.
Method Descriptor describes the target Bean’s methods.
Parameter Descriptor describes method parameters.
The Bean Info interface declares methods that return arrays of the above descriptors.
1. Name your Bean Info class. You must append the string "Bean Info" to the target class name. If the
target class name is Explicit Button, then its associated Bean information class must be named
ExplicitButtonBeanInfo
2. Subclass Simple Bean Info. This is a convenience class that implements Bean Info methods to return
null, or an equivalent no-opvalue.
public class ExplicitButtonBeanInfo extends SimpleBeanInfo {
Using SimpleBeanInfo saves you from implementing all the BeanInfo methods; you only have to
override those methods you need.
3. Override the appropriate methods to return the properties, methods, or events that you
wantexposed
o If you leave a descriptor out, that property, event or method will not be exposed. In other words,
you can selectively expose properties, events, or methods by leaving out those you don't want
exposed.
o If a feature's getter (for example, getMethodDescriptor()) method returns null, low- level
reflection is then used for that feature. This means, for example, that you can explicitly specify
properties, and let low-level reflection discover the methods. If you don't override the
SimpleBeanInfo default method, which returns null, low-level reflection will be used for that
feature.
4. Specify the target Bean class, and, if the Bean has a customizer, specify it also.
If noBean Infois found, then the Bean information package search path (maintained by the Introspector)
is searched.
If no Bean Info class is found, then low-level reflection is used to discover a Bean's features.
By using a Bean Info class, you can expose subsets of a particular Bean feature. For example, by not
returning a method descriptor for a particular method, that method will not be exposed in a builder tool.
When you use a Bean Info class:
Base class features willnot be exposed. You can retrieve base class features by using the
BeanInfo.getAdditionalBeanInfomethod.
Properties, events, or methods that have no descriptor will not be exposed. For a particular feature, only
those items returned in the descriptor array will be exposed. For example, if you return descriptors for
all your Bean methods except foo, then foo will not be exposed.
Low-level reflection will be used for features with getter methods returning null. For example if your
Bean Info class contains this method implementation:
Then low-level reflection will be used to discover your Bean's public methods.
Before examining a Bean, the Introspector will attempt to find a BeanInfo class associated with the
Bean.
By default, the Introspector takes the target Bean's fully qualified package name, and appends
"BeanInfo" to form a new class name.
For example, if the target Bean issunw.demo.buttons.ExplicitButton, then the Introspector will attempt
to locate sunw.demo.buttons.ExplicitButtonBeanInfo.
If that fails, then each package in the BeanInfo search path is searched.
Typically such tools are GUI applications, although they need not be. There is usually a palette of
components available from which a program designer can drag items and place them on a form or client
window.
In Windows environments the form is often called the client window area.
The form, or client window, represents the target application under construction and is presented, during
design, as it will appear when it runs independently of the builder program.
The most tell-tale window shared by many popular application builders is a property sheet, sometimes
called a property editor or simply a properties window.
A property sheet is used to modify properties and events associated with components. In keeping with
Java AWT terminology some property editors use the term action in place of event.
Applications built with powerful components can appear complex even when they take little effort to
build.
Linking Components in Builder Tools
The calculator program shown earlier is a good example of building a complex program with no
handwritten code.
The calculator was built without writing any Java code. Instead, components were linked by using a
mouse.
Generated events and event-handler methods were selected through pop-up menus.
Every time a button is pressed, an event is fired and side effects result. Example side effects include
appending digits to the invisible Entered String storage buffer, performing a math operation, or displaying text
in the display pane.
To program an event sequence, select a button as the event source, and indicate that you want to fire an
event through a keystroke or menu command.
You'll see a menu, or a property sheet, listing events that can be fired. Select an event, then drag a link
to the target object which should receive the event. You will be presented with a menu listing event handlers
available for the target object.
The following sequence of screens shows a more complex example in a different builder tool.
An animation component is added to a subpanel within a client window.
First an Animation Bean is selected from the builder's palette and dropped on a panel object in the client
form.
A Bean is customized by selecting action items from a property sheet, which in turn invokes a custom
Bean editor to select a specific event from a list of events that can be generated by an Animation Bean.
A list of events is acquired by introspection; the builder tool uses Java introspection APIs to query
beans dropped on the form.
Default behavior for event handlers is usually acceptable, but in some cases, you'll want to manually
override handler definitions with a text editor.
In this builder tool, much of the programming, including selection of events and event handlers, is done
using a class hierarchy browser. After selecting the event-handler method, a template for the event handler is
generated, while you flesh out details manually by writing code in the browser.
However not all programs require text editing. As mentioned, the calculator example was built without
resorting to text coding. The maze of links required to hookup components can be overwhelming, as you can
see in the following figure.
But most builder tools allow you to easily edit links and filter the display of links so that you see only
the level of detail that you want.
Nesting Components
Once you have assembled components into an application, often that application itself can be turned
into a component. An earlier example showed an Animation component dropped onto a panel to display an
animation.
Most of the code for the example was created through menu selections. The component was customized
primarily by specifying the names of animation files to be displayed from the disk.
The mouse Drag event handler was overridden through the browser for detailed customization. Once
custom properties and behavior are defined, they can be preserved by making a new
Bean out of the customized instance.
This is usually accomplished by serializing the customized Bean using Java's built-in support for object
serialization. Most builder tools provide a way to turn compound components into custom Beans.
In this example you select the Animation Bean, and issue a menu command to turn it into a Bean
component.
The builder generates code to turn the assembly (property and behavior definitions) into a Bean. The
bean is added to the component palette of the builder tool.
Alternately the bean can be packaged in a JAR archive file for sale, or distribution to clients.
You could take the new custom Bean and use it to compose a compound assembly, creating yet another
custom Bean.
For example, you could group three instance of a My Animation Bean on a panel and save the whole
assembly as a single new Bean.
The compound My Three Beans custom component is added to your builder's component palette as a
single Bean.
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low- level
communication details, allowing you to write programs that focus on solving the problem at hand.
The java.net package provides support for the two common network protocols:
TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of
data to be transmitted between applications.
SOCKET PROGRAMMING:
Sockets provide the communication mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on its end of the communication. The client and
server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.Server Socket class provides a mechanism for the
server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
The server instantiates a Server Socket object, denoting which port number communication is to occur on.
The server invokes the accept () method of the Server Socketclass. This method waits until a client
connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server’s name and port
number to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and port
number. If communication is established, the client now has a Socket object capable of communicating with
the server.
On the server side, the accept () method returns a reference to a new socket on the server that is
connected to the client’s socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an
Output Stream and an Input Stream. The client's Output Streamis connected to the server's Input Stream, and
the client's Input Streamis connected to the server'sOutputStream.
TCP is a two-way communication protocol, so data can be sent across both streams at the same time. There are
following useful classes providing complete set of methods to implement sockets.
The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests
The Server Socket class has four constructors:
1. ServerSocket(int port) - Attempts to create a server socket bound to the specified port. An
exception occurs if the port is already bound by another application
2. ServerSocket (int port, int backlog) - Like the previous constructor, the backlog parameter
specifies how many incoming clients to store in a wait queue.
3. ServerSocket(int port, int backlog, InetAddress address) - Similar to the previous constructor,
the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for
servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses
to accept client requests on
4. ServerSocket()- Creates an unbound server socket. When using this constructor, use the bind()
method when you are ready to bind the server socket
If the Server Socket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.
1. getLocalPort()- Returns the port that the server socket is listening on. This method is useful if you
passed in 0 as the port number in a constructor and let the server find a port foryou.
2. accept()- Waits for an incoming client. This method blocks until either a client connects to the server on
the specified port or the socket times out, assuming that the time-out value has been set using the
setSoTimeout() method. Otherwise, this method blocksindefinitely
3. setSoTimeout(int timeout)- Sets the time-out value for how long the server socket waits for a client
during theaccept().
4. bind(SocketAddress host, int backlog)- Binds the socket to the specified server and port in the
SocketAddress object. Use this method if you instantiated the ServerSocket using the no-argument
constructor.
When the ServerSocket invokes accept(), the method does not return until a client connects. After a client
does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new
Socket. A TCP connection now exists between the client and server, and communication can begin.
The java.net.Socket class represents the socket that both the client and server use to communicate with
each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object
from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server:
1. Socket(String host, int port)- This method attempts to connect to the specified server at the specified
port. If this constructor does not throw an exception, the connection is successful and the client is
connected to the server.
2. Socket(InetAddress host, int port) - This method is identical to the previous constructor, except that
the host is denoted by an InetAddressobject.
3. Socket(String host, int port, InetAddress localAddress, int localPort)- Connects to the specified host
and port, creating a socket on the local host at the specified address andport.
4. Socket(String host, int port, InetAddress localAddress, int localPort) - Connects to the specified
host and port, creating a socket on the local host at the specified address andport.
5. Socket()- Creates an unconnected socket. Use the connect() method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts
to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and server have a Socket
object, so these methods can be invoked by both the client and server.
1. connect(SocketAddress host, int timeout) - This method connects the socket to the specified host.
This method is needed only when you instantiated the Socket using the no-argument constructor.
2. getInetAddress()- This method returns the address of the other computer that this socket is connected
to.
3. getPort()- Returns the port the socket is bound to on the remote machine.
4. getLocalPort ()- Returns the port the socket is bound to on the local machine.
6. getInputStream() - Returns the input stream of the socket. The input stream is connected to the output
stream of the remote socket.
7. getOutputStream() - Returns the output stream of the socket. The output stream is connected to the
input stream of the remote socket
8. close() - Closes the socket, which makes this Socket object no longer capable of connecting again to
anyserver
2. getByAddress(String host, byte[] addr)- Create an InetAddress based on the provided host name
and IPaddress.
When a server invokes the accept() method of the Server Socket instance, the main server thread blocks
until a client connects to the server; it is then prevented from accepting further client connections until the
server has processed the client's request
The Remote Method Invocation (RMI) is an API that provides a mechanism to create distributed
application in java. an object to invoke methods on an object running in another JVM.
The RMI provides remote communication between the applications using two objects stub and skeleton.
RMI uses stub and skeleton object for communication with the remote object. A remote object is an object
whose method can be invoked from another JVM.
STUB AND SKELETON OBJECTS: STUB
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes method on the
stub object, it does the following tasks:
SKELETON
The skeleton is an object, acts as a gateway for the server-side object. All the incoming requests are
routed through it. When the skeleton receives the incoming request, it does the following tasks:
RMI LAYERS
3. Create object for implementation class and register the object with the rmiregistry
4. Create class in client side and get the remote reference by lookup the registry in the remote system
FactInterface serv = (FactInterface) Naming.lookup("rmi://"127.0.0.1"/server");