1. 1)
A
Ans
Object-oriented programming (OOP) is a programming paradigm that represents concepts as
"objects" that have data fields (attributes that describe the object) and associated procedures
known as methods. Objects, which are usually instances of classes, are used to interact with
one another to design applications and computer programs
An object-oriented program may be viewed as a collection of interacting objects, as
opposed to the conventional model, in which a program is seen as a list of tasks
(subroutines) to perform. In OOP, each object is capable of receiving messages,
processing data, and sending messages to other objects. Each object can be viewed as
an independent "machine" with a distinct role or responsibility. Actions (or "methods") on
these objects are closely associated with the object. For example, OOP data
structures tend to "carry their own operators around with them" (or at least "inherit" them
from a similar object or class)—except when they must be serialized.
Simple, non-OOP programs may be one "long" list(or commands). More complex
programs often group smaller sections of these statements
intofunctions or subroutines—each of which might perform a particular task. With
designs of this sort, it is common for some of the program's data to be 'global', i.e.,
accessible from any part of the program. As programs grow in size, allowing any
function to modify any piece of data means that bugs can have wide-reaching effects.
In contrast, the object-oriented approach encourages the programmer to place data
where it is not directly accessible by the rest of the program. Instead, the data is
accessed by calling specially written functions, commonly called methods, which are
bundled in with the data. These act as the intermediaries for retrieving or modifying the
data they control. The programming construct that combines data with a set of methods
for accessing and managing those data is called an object. The practice of using
subroutines to examine or modify certain kinds of data was also used in non-
OOPmodular programming, well before the widespread use of object-oriented
programming.
An object-oriented program usually contains different types of objects, each
corresponding to a particular kind of complex data to manage, or perhaps to a real-
world object or concept such as a bank account, a hockey player, or a bulldozer. A
program might contain multiple copies of each type of object, one for each of the real-
2. world objects the program deals with. For instance, there could be one bank account
object for each real-world account at a particular bank. Each copy of the bank account
object would be alike in the methods it offers for manipulating or reading its data, but the
data inside each object would differ reflecting the different history of each account.
Objects can be thought of as wrapping their data within a set of functions designed to
ensure that the data are used appropriately, and to assist in that use. The object's
methods typically include checks and safeguards specific to the data types the object
contains. An object can also offer simple-to-use, standardized methods for performing
particular operations on its data, while concealing the specifics of how those tasks are
accomplished. In this way alterations can be made to the internal structure or methods
of an object without requiring that the rest of the program be modified. This approach
can also be used to offer standardized methods across different types of objects. As an
example, several different types of objects might offer print methods. Each type of
object might implement that print method in a different way, reflecting the different kinds
of data each contains, but all the different print methods might be called in the same
standardized manner from elsewhere in the program. These features become especially
useful when more than one programmer is contributing code to a project or when the
goal is to reuse code between projects.
Object-oriented programming has roots that can be traced to the 1960s. As hardware
and software became increasingly complex, manageability often became a concern.
Researchers studied ways to maintain software quality and developed object-oriented
programming in part to address common problems by strongly emphasizing discrete,
reusable units of programming logic[citation needed]. The technology focuses on data rather
than processes, with programs composed of self-sufficient modules ("classes"), each
instance of which ("objects") contains all the information needed to manipulate its own
data structure ("members"). This is in contrast to the existing modular programming that
had been dominant for many years that focused on the function of a module, rather than
specifically the data, but equally provided for code reuse, and self-sufficient reusable
units of programming logic, enabling collaboration through the use of linked modules
(subroutines).
As to the advantages of object-orientation over non-object-oriented software:
3. component-specific behavior - making details on how to handle a particular
component the responsibility of the smaller component-specific machine
ensures any time that component is handled, its machine will do so
appropriately;
polymorphic expressions - because component-specific machines performs
operations tailored to its particular component, the same message sent to
different machines can act differently;
type abstraction - it often makes sense for several different types of
components to use the same vocabulary for the operations their machines
do;
separation of concerns - leaving component-specific details to their
machines means the process machine only needs to handle the more
general, larger concerns of its process and the data required to manage it;
plus, it's less likely to be affected by changes in other components;
adaptability - components that focus on their area of speciality can be
adapted to unforeseen use simply by changing the components it uses, or
making it available to another process machine;
code reuse - components with a narrow focus and greater adaptability can
leverage their development cost by being put to use more often.
b)
"Poly" means "many" and "morph" means "form". Polymorphism is the
ability of an object (or reference) to assume (be replaced by) or become
many different forms of object.
Example: function overloading, function overriding, virtual functions.
Another example can be a plus ‗+‘ sign, used for adding two integers or for
using it to concatenate two strings.
Subtype polymorphism, often referred to as simply polymorphism in the context of object-oriented
programming, is the ability to create a variable, a function, or an object that has more than one form. In
4. principle, polymorphism can arise in other computing contexts and shares important similarities with the
concept of degeneracy in biology.
The purpose of polymorphism is to implement a style of programming called message-passing in the
[citation needed]
literature , in which objects of various types define a common interface of operations for users.
In strongly typed languages, polymorphism usually means that type A somehow derives from type B, or
type C implements an interface that represents type B. In weakly typed languages types are implicitly
polymorphic.
Operator overloading of the numeric operators (+, -, *, and /) allows polymorphic treatment of the various
numerical types: integer, unsigned integer, float, decimal, etc.; each of which have different ranges, bit
patterns, and representations. Another common example is the use of the "+" operator which allows
similar or polymorphic treatment of numbers (addition), strings (concatenation), and lists (attachment).
This is a lesser used feature of polymorphism.
The primary usage of polymorphism in industry (object-oriented programming theory) is the ability
of objects belonging to different types to respond tomethod, field, or property calls of the same name,
each one according to an appropriate type-specific behavior. The caller (calling code) likewise its
programmer, does not have to know the exact type of the callee (called object), thus the exact behavior is
determined at run-time (this is called late binding or dynamic binding).
The different objects involved only need to present a compatible interface to the clients' (calling routines).
That is, there must be public or internal methods, fields, events, and properties with the same name and
the same parameter sets in all the superclasses, subclasses and interfaces. In principle, the object types
may be unrelated, but since they share a common interface, they are often implemented as subclasses of
the same superclass. Though it is not required, it is understood that the different methods will also
produce similar results (for example, returning values of the same type).
Polymorphism (which is strictly referring to subtype polymorphism in the context of this article) is not the
[1]
same as method overloading or method overriding, (which is known instead as ad-hoc
[2]
polymorphism ). Polymorphism is only concerned with the application of specific implementations to
an interface or a more generic base class. Method overloading refers to methods that have the same
name but different signatures inside the same class. Method overriding is where a subclass replaces the
implementation of one or more of its parent's methods. Neither method overloading nor method overriding
[3]
is by itself an implementation of polymorphism.
2)
A
A Platform-Independent Model (PIM) in software engineering is a model of a software
system or business system, that is independent of the specific technological platform
used to implement it.
5. The term platform-independent model is most frequently used in the context of
the model-driven architecture approach.Platform independent is program running on
different processors like intel, AMD, Sun Micro Systems etc.; This model-driven
architecture approach corresponds the Object Management Group vision of Model
Driven Engineering.
The main idea is that it should be possible to use a Model Transformation Language to
transform a Platform-independent model into a Platform-specific model. In order to
achieve this transformation, one can use a language compliant to the newly
defined QVT standard. Examples of such languages are VIATRA or ATLAS
Transformation Language. It means execution of the program is not restricted by the
type of o/s used.
Java solves the problem of platform-independence by using
byte code. The Java compiler does not produce native
executable code for a particular machine like a C compiler
would. Instead it produces a special format called byte
code. Java byte code written in hexadecimal, byte by byte,
looks like this:
CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08
This looks a lot like machine language, but unlike machine
language Java byte code is exactly the same on every
platform. This byte code fragment means the same thing on a
Solaris workstation as it does on a Macintosh PowerBook.
Java programs that have been compiled into byte code still
need an interpreter to execute them on any given platform.
The interpreter reads the byte code and translates it into
the native language of the host machine on the fly. The most
common such interpreter is Sun's program java (with a little
j). Since the byte code is completely platform independent,
only the interpreter and a few native libraries need to be
ported to get Java to run on a new computer or operating
system. The rest of the runtime environment including the
6. compiler and most of the class libraries are written in Java.
All these pieces, the javac compiler, the java interpreter,
the Java programming language, and more are collectively
referred to as Java.
b)
*Write a program to find Fibonacci series of a given no.
Example :
Input - 8
Output - 1 1 2 3 5 8 13 21
*/
class Fibonacci{
public static void main(String args[]){
int num = Integer.parseInt(args[0]); //taking no. as command
line
argument.
System.out.println("*****Fibonacci Series*****");
int f1, f2=0, f3=1;
for(int i=1;i<=num;i++){
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
}
c)
see .htm file
d)
Classpath is a parameter—set either on the command-line, or through an environment
variable—that tells the Java Virtual Machine or the Java compiler where to look for user-
defined classes andpackages.
Suppose we have a package called org.mypackage containing the classes:
HelloWorld (main class)
SupportClass
UtilClass
and the files defining this package are stored physically under the directory D:myprogram (on Windows)
or /home/user/myprogram (on Linux).
The file structure will look like this:
7. Microsoft Windows Linux
D:myprogram /home/user/myprogram/
| |
---> org ---> org/
| |
---> mypackage ---> mypackage/
| |
---> --->
HelloWorld.class HelloWorld.class
---> --->
SupportClass.class SupportClass.class
---> --->
UtilClass.class UtilClass.class
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld.
However we must also tell Java where to look for the files and directories defining our package. So to
launch the program, we use the following command:
Microsoft Windows Linux
java -classpath D:myprogram java -classpath /home/user/myprogram
org.mypackage.HelloWorld org.mypackage.HelloWorld
where:
-classpath D:myprogram sets the path to the packages used in the program (on Linux, -classpath
/home/user/myprogram)
org.mypackage.HelloWorld is the name of the main class
Note that if we ran Java in D:myprogram (on Linux, /home/user/myprogram/) then we would not need to
specify the classpath since Java implicitly looks in the current working directory for files containing
classes.
[edit]Adding all JAR files in a directory
In Java 6 and higher, one can add all jar-files in a specific directory to the classpath using wildcard
notation.
Windows example:
8. java -classpath ".;c:mylib*" MyApp
Linux example:
java -classpath '.:/mylib/*' MyApp
[edit]Setting the path through an environment variable
The environment variable named CLASSPATH may be alternatively used to set the classpath. For the
above example, we could also use on Windows:
Sometimes you have to check the JAVA_HOME also, if it is pointing towards the right JDK version
set CLASSPATH=D:myprogram
java org.mypackage.HelloWorld
[edit]Setting the path of a Jar file
Now, suppose the program uses a supporting library enclosed in a Jar file called supportLib.jar, physically
in the directory D:myprogramlib.
The corresponding physical file structure is :
D:myprogram
|
---> lib
|
---> supportLib.jar
|
---> org
|
--> mypackage
|
---> HelloWorld.class
---> SupportClass.class
---> UtilClass.class
We should use the following command-line option:
java -classpath D:myprogram;D:myprogramlibsupportLib.jar
org.mypackage.HelloWorld
or alternatively:
9. set CLASSPATH=D:myprogram;D:myprogramlibsupportLib.jar
java org.mypackage.HelloWorld
[edit]Setting the path in a Manifest file
Suppose that our program has been enclosed in a Jar file called helloWorld.jar, put directly in
the D:myprogram directory. We have the following file structure:
D:myprogram
|
---> helloWorld.jar
|
---> lib
|
---> supportLib.jar
The manifest file defined in this Jar file has this definition:
Main-Class: org.mypackage.HelloWorld
Class-Path: lib/supportLib.jar
Note: It's important that the manifest file ends with either a new line or carriage return.
Also, note that the classpath string in this case describes the location of the supportLib.jar file relative to
the location of the helloWorld.jar file, and not as an absolute file path (as it might be when setting the -
classpath parameter on the command line, for example). Thus, the actual locations of the jar file and its
support library are irrelevant so long as the relative directory structure between the two is preserved.
To launch the program, we can use the following command:
java -jar D:myprogramhelloWorld.jar
It is not necessary to define the Classpath to the program classes, or the support library classes, because
it is already defined in the manifest file.
Caution, it is useless to define the Main class at launch, the manifest of the JAR file must contain a line of
the form
Main-Class: classname
in order for the -jar option to work JavaDoc.
10. The syntax for specifying multiple library JAR files in the manifest file is to separate the entries with a
space:
Class-Path: lib/supportLib.jar lib/supportLib2.jar
3
A
xceptions are the customary way in Java to indicate to a calling method that an abnormal
condition has occurred. This article is a companion piece to this month's Design
Techniques installment, which discusses how to use exceptions appropriately in your
programs and designs. Look to this companion article for a tutorial on the nuts and bolts of what
exceptions are and how they work in the Java language and virtual machine.
When a method encounters an abnormal condition (an exception condition) that
it can't handle itself, it may throw an exception. Throwing an exception is like
throwing a beeping, flashing red ball to indicate there is a problem that can't be
handled where it occurred. Somewhere, you hope, this ball will be caught and the
problem will be dealt with. Exceptions are caught by handlers positioned along
the thread's method invocation stack. If the calling method isn't prepared to catch
the exception, it throws the exception up to itscalling method, and so on. If one of
the threads of your program throws an exception that isn't caught by any method
along the method invocation stack, that thread will expire. When you program in
Java, you must position catchers (the exception handlers) strategically, so your
program will catch and handle all exceptions from which you want your program
to recover.
Exception classes
In Java, exceptions are objects. When you throw an exception, you throw an
object. You can't throw just any object as an exception, however -- only those
objects whose classes descend fromThrowable. Throwable serves as the base
11. class for an entire family of classes, declared in java.lang, that your program can
instantiate and throw. A small part of this family is shown in Figure 1.
As you can see in Figure 1, Throwable has two direct
subclasses,Exception and Error. Exceptions (members of the Exception family)
are thrown to signal abnormal conditions that can often be handled by some
catcher, though it's possible they may not be caught and therefore could result in
a dead thread. Errors (members of theError family) are usually thrown for more
serious problems, such asOutOfMemoryError, that may not be so easy to handle. In
general, code you write should throw only exceptions, not errors. Errors are
usually thrown by the methods of the Java API, or by the Java virtual machine
itself.
The Exception class does not define any methods of its own. It inherits
methods provided by Throwable.
All exceptions have the methods defined by Throwable available to them.
They are shown in the following list.
Throwable fillInStackTrace( )
Returns a Throwable object that contains a completed stack trace.
Throwable getCause( )
Returns the exception that underlies the current exception.
String getLocalizedMessage( )
Returns a localized description.
String getMessage( )
Returns a description of the exception.
StackTraceElement[ ] getStackTrace( )
Returns an array that contains the stack trace.
Throwable initCause(Throwable causeExc)
Associates causeExc with the invoking exception as a cause of the
invoking exception.
void printStackTrace( )
Displays the stack trace.
void printStackTrace(PrintStream stream)
Sends the stack trace to the stream.
void printStackTrace(PrintWriter stream)
Sends the stack trace to the stream.
void setStackTrace(StackTraceElement elements[ ])
Sets the stack trace to the elements passed in elements.
String toString( )
Returns a String object containing a description of the exception.
12. The following program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
public class Main {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if (a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
B
Abstract classes in Java are classes which cannot be instantiated, meaning
you cannot create new instances of an abstract class. The purpose of an
abstract class is to function as a base for subclasses. This text gets into the
purpose of abstract classes in more detail towards the end of this text.
Here is a list of the topics covered in this text:
13. Declaring an Abstract Class
You declare that a class is abstract by adding the abstract keyword to the
class declaration. Here is an example:
public abstract class MyAbstractClass {
}
That is all there is to it. Now you cannot create instances
of MyAbstractClass. Thus, the following Java code is no longer valid:
MyAbstractClass myClassInstance = new MyAbstractClass(); //not valid
If you try to compile the code above, the Java compiler will generate an error.
Abstract Methods
An abstract class can have abstract methods. You declare a method abstract
by adding the abstract keyword in front of the method declaration. Here is
how that looks:
public abstract class MyAbstractClass {
14. public abstract void abstractMethod();
}
An abstract method has no implementation. It just has a method signature.
If a class has an abstract method, the whole class must be declared abstract.
Not all methods have to be abstract, even if the class is abstract. An abstract
class can have a mixture of abstract and non-abstract classes.
Subclasses of an abstract class must implement (override) all abstract
methods of its abstract superclass. The non-abstract methods of the
superclass are just inherited as they are. They can also be overridden, if
needed.
Here is an example subclass of MyAbstractClass:
public class MySubClass extends MyAbstractClass {
public void abstractMethod() {
System.out.println("My method implementation");
}
}
Notice how MySubClass has to implement the abstract
method abstractMethod() from its superclass MyAbstractClass.
15. The only time a subclass of an abstract class is not forced to implement all
abstract methods of its superclass, is if the subclass is also an abstract class.
The Purpose of Abstract Classes
The purpose of abstract classes is to function as base classes which can be
extended by subclasses to create a full implementation. For instance, imagine
that a certain process requires 3 steps:
1. The step before the action.
2. The action.
3. The step after the action.
If the steps before and after the action are always the same, the 3-step
process could be implemented in an abstract superclass like this:
public abstract MyAbstractProcess {
public void process() {
stepBefore();
action();
stepAfter();
}
16. public void stepBefore() {
//implementation directly in abstract superclass
}
public abstract void action(); // implemented by subclasses
public void stepAfter() {
//implementation directly in abstract superclass
}
}
Notice how the action() method is abstract. Subclasses
of MyAbstractProcess can now extend MyAbstractProcess and just
override the action() method.
When the process() method of the subclass is called, the full process is
executed, including the action() method of the subclass.
Of course, the MyAbstractProcess did not have to be an abstract class to
function as a base class. Nor did the action() method have to be abstract
either. You could have just used an ordinary class. However, by making the
method to implement abstract, and thus the class too, you signal clearly to the
programmer, that this class should not be used as it is, but be used as a base
class for a subclass, and that the abstract method should be implemented in
the subclass.
17. The above example did not have a default implementation for
the action() method. In some cases your superclass might actually have a
default implementation for the method that subclasses are supposed to
override. In that case, you cannot make the method abstract. You can still
make the superclass abstract though, even if it contains no abstract methods.
Here is a more concrete example that opens a URL, processes it and closes
the connection to the URL afterwards.
public abstract class URLProcessorBase {
public void process(URL url) throws IOException {
URLConnection urlConnection = url.openConnection();
InputStream input = urlConnection.getInputStream();
try{
processURLData(input);
} finally {
input.close();
}
}
18. protected abstract void processURLData(InputStream input)
throws IOException;
}
Notice how the processURLData() method is abstract. Subclasses
of URLProcessorBasehas to implement this method.
Subclasses of URLProcessorBase can process data downloaded from
URL's without worrying about opening and closing the network connection to
the URL. This is done by the URLProcessorBase. Subclasses only need to
worry about processing the data from the InputStream passed to
the processURLData() metod. This makes it easier to implement classes
that processes data from URL's.
Here is an example subclass:
public class URLProcessorImpl extends URLProcessorBase {
@Override
protected void processURLData(InputStream input) throws
IOException {
int data = input.read();
19. while(data != -1){
System.out.println((char) data);
data = input.read();
}
}
}
Notice how the subclass only implements the processURLData() method,
and nothing more. The rest of the code is inherited from
the URLProcessorBase superclass.
Here is an example of how to use the URLProcessorImpl class:
URLProcessorImpl urlProcessor = new URLProcessorImpl();
urlProcessor.process(new URL("http://jenkov.com"));
The process() method is called, which is implemented in
the URLProcessorBasesuperclass. This method in turn calls
the processURLData() in the URLProcessorImplclass.
Abstract classes improve the situation by preventing a developer from
instantiating the base class, because a developer has marked it as having
missing functionality. It also provides compile-time safety so that you can
ensure that any classes that extend your abstract class provide the bare
20. minimum functionality to work, and you don't need to worry about putting stub
methods (like the one above) that inheritors somehow have to magically know
that they have to override a method in order to make it work.
Interfaces are a totally separate topic. An interface lets you describe what
operations can be performed on an object. You would typically use interfaces
when writing methods, components, etc. that use the services of other
components, objects, but you don't care what the actual type of object you are
getting the services from is.
Consider the following method:
public void saveToDatabase(IProductDatabase database) {
database.addProduct(this.getName(), this.getPrice());
}
You don't care about whether the database object inherits from any particular
object, you just care that it has an addProduct method. So in this case, an
interface is better suited than making all of your classes happen to inherit from
the same base class.
Sometimes the combination of the two works very nicely. For example:
abstract class RemoteDatabase implements IProductDatabase {
public abstract String[] connect();
public abstract void writeRow(string col1, string col2);
public void addProduct(String name, Double price) {
connect();
writeRow(name, price.toString());
}
}
class SqlDatabase extends RemoteDatabase {
//TODO override connect and writeRow
}
class OracleDatabase extends RemoteDatabase {
//TODO override connect and writeRow
}
class FileDatabase implements IProductDatabase {
public void addProduct(String name, Double price) {
21. //TODO: just write to file
}
}
Multilevel inheritance is a java feature where the properties of a class are
inherited by a class which extends one or more classes which extend its
features...
Example:
public class A {
public String getName(){
return "Vijay";
}
}
public class B extends A {
public int getAge() {
return 24;
}
}
public class C extends B {
public String getAddress(){
return "Utter Pradesh,INDIA";
}
}
public class D extends C {
public void print {
System.out.println(getName());
System.out.println(getAge());
System.out.println(getAddress());
}
}
This method would print the following in the console:
22. Vijay
24
Pradesh,INDIA
Here in class D you are calling methods that are available inside classes A, B &
C. Though D extends only class C, it would in turn inherit the properties of the
classes extended by C and its parents.
This is multi level inheritance.
4
a
The final keyword is used to create constants, i.e. data which is always for reading and never
needs to change, once initialized. A simple example would be MaxAge, in a software to manage
details of employees in a company. Lets say the maximum age of retirement is 60, so we know
that no employee can have age greater than 60. So I will write –
final int MaxAge = 60;
Now anywhere in other part of software I can use the value simply for validation as follows:
If (age > MaxAge) // age is already declared somewhere as int
System.out.println(―There is an error. Invalid Age.‖); // Oops error in age!
The static keyword is used to create variables which are shared by all instances (objects) of the
class. The scope of usage of such a variable is class, i.e. it can be accessed only with the class
unless it is declared public. Their lifetime is same as that of the program, which means they
always exist and you don't need to create object to access them. A good example can be a
variable to count the total number of errors in a class and its objects. The following is one
example:
static int TotalErrors = 0;
Then we can write anywhere code like the following –
If (age > MaxAge)
23. {
System.out.println(―There is an error. Invalid Age!‖);
TotalErrors++; // There was an error so increment it
}
Did that make any sense?
Actually I am a C++ guy, so if it did not make any sense, just forgive me. I tried my best. =)
@To XTremeHell [In response to his assertion that const and final are different]
Sorry sir, you need to go back to read the textbooks again. Java's "final" and C++ "const" are
indeed ABSOLUTELY same. The value of const need not be known at compile time. See the
C++ code below:-
int var = 0;
DoSomethingWithVar(&var); // The function modifies var.
const int myReadOnlyValue = var;
The point is "myReadOnlyValue" is a constant. Now can you tell me XTremeHell, how the
compiler is supposed to know the value of myReadOnlyValue, even though it is a constant?
B
In the 'normal' cases a simple question is enough to find out if we need
inheritance or aggregation.
If The new class is more or less as the original class. Use inheritance. The
new class is now a subclass of the original class.
If the new class must have the original class. Use aggregation. The new
class has now the original class as a member.
However, there is a big gray area. So we need several other tricks.
If we have used inheritance (or we plan to use it) but we only use part of the
interface, or we are forced to override a lot of functionality to keep the
correlation logical. Then we have a big nasty smell that indicates that we
had to use aggregation.
If we have used aggregation (or we plan to use it) but we find out we need
to copy almost all of the functionality. Then we have a smell that points in
the direction of inheritance.
24. To cut it short. We should use aggregation if part of the interface is not used or
has to be changed to avoid an illogical situation. We only need to use
inheritance, if we need almost all of the functionality without major changes. And
when in doubt, use Aggregation.
An other possibility for, the case that we have an class that needs part of the
functionality of the original class, is to split the original class in a root class and a
sub class. And let the new class inherit from the root class. But you should take
care with this, not to create an illogical separation.
Lets add an example. We have a class 'Dog' with methods: 'Eat', 'Walk', 'Bark',
'Play'.
class Dog
Eat;
Walk;
Bark;
Play;
end;
We now need a class 'Cat', that needs 'Eat', 'Walk', 'Purr', and 'Play'. So first try
to extend it from a Dog.
class Cat is Dog
Purr;
end;
Looks, alright, but wait. This cat can Bark (Cat lovers will kill me for that). And a
barking cat violates the principles of the universe. So we need to override the
Bark method so that it does nothing.
class Cat is Dog
Purr;
Bark = null;
end;
Ok, this works, but it smells bad. So lets try an aggregation:
class Cat
has Dog;
Eat = Dog.Eat;
Walk = Dog.Walk;
Play = Dog.Play;
25. Purr;
end;
Ok, this is nice. This cat does not bark anymore, not even silent. But still it has an
internal dog that wants out. So lets try solution number three:
class Pet
Eat;
Walk;
Play;
end;
class Dog is Pet
Bark;
end;
class Cat is Pet
Purr;
end;
This is much cleaner. No internal dogs. And cats and dogs are at the same level.
We can even introduce other pets to extend the model. Unless it is a fish, or
something that does not walk. In that case we again need to refactor. But that is
something for an other time.
C
Difference Between Interface and Abstract Class
23/04/2008
1. Main difference is methods of a Java interface are implicitly abstract and
cannot have implementations. A Java abstract class can have instance
methods that implements a default behavior.
2. Variables declared in a Java interface is by default final. An abstract class
may contain non-final variables.
3. Members of a Java interface are public by default. A Java abstract class can
have the usual flavors of class members like private, protected, etc..
26. 4. Java interface should be implemented using keyword “implements”; A Java
abstract class should be extended using keyword “extends”.
5. An interface can extend another Java interface only, an abstract class can
extend another Java class and implement multiple Java interfaces.
6. A Java class can implement multiple interfaces but it can extend only one
abstract class.
7. Interface is absolutely abstract and cannot be instantiated; A Java abstract
class also cannot be instantiated, but can be invoked if a main() exists.
8. In comparison with java abstract classes, java interfaces are slow as it
requires extra indirection.
D
Java provides the StringBuffer and String classes, and the String class is used to
manipulate character strings that cannot be changed. Simply stated, objects of type String are
read only and immutable. The StringBuffer class is used to represent characters that can be
modified.
The significant performance difference between these two classes is
that StringBuffer is faster than String when performing simple
concatenations. In String manipulation code, character strings are routinely
concatenated. Using the String class, concatenations are typically performed as
follows:
String str = new String ("Stanford ");
str += "Lost!!";
If you were to use StringBuffer to perform the same concatenation, you would
need code that looks like this:
StringBuffer str = new StringBuffer ("Stanford ");
str.append("Lost!!");
27. Developers usually assume that the first example above is more efficient
because they think that the second example, which uses theappend method for
concatenation, is more costly than the first example, which uses the + operator to
concatenate two Stringobjects.
The + operator appears innocent, but the code generated produces some
surprises. Using a StringBuffer for concatenation can in fact produce code that
is significantly faster than using a String. To discover why this is the case, we
must examine the generated bytecode from our two examples. The bytecode for
the example using String looks like this:
0 new #7 <Class java.lang.String>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #12 <Method java.lang.String(java.lang.String)>
9 astore_1
10 new #8 <Class java.lang.StringBuffer>
13 dup
14 aload_1
15 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)>
18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
21 ldc #1 <String "Lost!!">
23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
26 invokevirtual #22 <Method java.lang.String toString()>
29 astore_1
The bytecode at locations 0 through 9 is executed for the first line of code,
namely:
String str = new String("Stanford ");
Then, the bytecode at location 10 through 29 is executed for the concatenation:
28. str += "Lost!!";
Things get interesting here. The bytecode generated for the concatenation
creates a StringBuffer object, then invokes itsappend method: the
temporary StringBuffer object is created at location 10, and its append method
is called at location 23. Because the String class is immutable,
a StringBuffer must be used for concatenation.
After the concatenation is performed on the StringBuffer object, it must be
converted back into a String. This is done with the call to the toString method
at location 26. This method creates a new String object from the
temporary StringBufferobject. The creation of this
temporary StringBuffer object and its subsequent conversion back into
a String object are very expensive.
In summary, the two lines of code above result in the creation of three objects:
1. A String object at location 0
2. A StringBuffer object at location 10
3. A String object at location 26
Now, let's look at the bytecode generated for the example using StringBuffer:
0 new #8 <Class java.lang.StringBuffer>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
9 astore_1
10 aload_1
11 ldc #1 <String "Lost!!">
13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
16 pop
29. The bytecode at locations 0 to 9 is executed for the first line of code:
StringBuffer str = new StringBuffer("Stanford ");
The bytecode at location 10 to 16 is then executed for the concatenation:
str.append("Lost!!");
Notice that, as is the case in the first example, this code invokes
the append method of a StringBuffer object. Unlike the first example, however,
there is no need to create a temporary StringBuffer and then convert it into
a String object. This code creates only one object, the StringBuffer, at
location 0.
In conclusion, StringBuffer concatenation is significantly faster
than String concatenation. Obviously, StringBuffers should be used in this
type of operation when possible. If the functionality of the String class is
desired, consider using aStringBuffer for concatenation and then performing
one conversion to String.
5
A
File Handling in Java
For file handling in java, the package known as java.io is available. This package
contains all the required classes needed to perform input and output (I/O) in Java.
Streams
30. The sequence of data can be defined as a stream. Java defines two types of streams
which are given below :
1. Byte
2. Characters
Byte Stream
For dealing input and output of bytes, byte stream is employed. For reading and writing
binary data it is incorporated. Binary Stream uses two abstract classes for input and
output. These are InputStream class and OutputStream class respectively. To read data
from the source InputStream is used and to write data to a destination OutputStream is
used.
The class hierarchy of the Byte Stream is given below :
The byte stream classes are given below :
31. Byte Stream Classes Detail
The InputStream is an abstract super class .All the
InputStream classes representing an input
stream of bytes is the subclass of this super class.
The OutputStream is an abstract super class .All the
OutputStream classes representing an output
stream of bytes is the subclass of this super class.
FileInputStream In a file system, it gets input bytes from a file.
FileOutputStream Using it you can write data to a File or to a FileDescriptor.
A ByteArrayInputStream has an internal buffer. This buffer
ByteArrayInputStream
can retain bytes read from the stream
Data can be written into a byte array using the output
ByteArrayOutputStream
stream of ByteArrayOutputStream.
The input streams can be logically concatenated using
SequenceInputStream
SequenceInputStream.
The string's content supplies bytes read to an input
stream which is created by an application.
StringBufferInputStream
The StringBufferInputStream class allows an application
to do this.
It has some additional input stream used as basic data
FilterInputStream source, These input streams can provide
transformation of data and extra functionality.
32. All the classes that filter output streams is the subclasses
FilterOutputStream
of the FilterOutputStream superclass.
It allows an application to read java's data type using an
DataInputStream
input stream which is independent of machine.
It allows an application to write java's data type(primitive)
DataOutputStream
to an output stream.
It provides additional functionality to the input stream such
BufferedInputStream as capability to buffer. It also supports reset and mark
methods.
BufferedOutputStream The buffered output stream is applied by this class.
It provide ability to the other output stream to print several
PrintStream
data values' representation.
The data byte written on piped output stream is provided
PipedInputStream by PipedInputStream. But before that it must connect to
the piped output stream.
For creating communication pipe, piped output stream
PipedOutputStream
should be connected to piped output stream.
To sum up the ability to "push back" or "unread" one byte
PushbackInputStream
to other input stream, a PushbackInputStream is used.
For accessing a file randomly (for reading or writing) this
RandomAccessFile
class is incorporated.
33. Methods defined by InputStream
After creating InputStream object, you can perform additional operations on the stream
using given below methods :
Methods Description
public void
The output stream of a file is closed using this function. Before that
close() throws
it releases any resource. This function throws IOException.
IOException{}
protected void
This function clears the connection to the file. It throws an
finalize()throws
IOException.
IOException {}
public int
This function reads the data from the InputStream and return int
read(int
which is next byte of data. It also returns
r)throws
-1 if end of file is reached.
IOException{}
public int
This method reads data equal to length of r from the input stream
read(byte[] r)
using array. The total number of bytes read is returned after
throws
finishing reading. When end of file reached it returns -1.
IOException{}
public int
available() This function returns the number of bytes available for reading from
throws file input stream. The return type is int.
IOException{}
34. Method defined by OutputStream
Once you have OutputStream object in hand then there is a list of helper methods which
can be used to write to stream or to do other operations on the stream.
Methods Description
public void close() throws This function closes the output stream of the file
IOException{} and throws IOException.
protected void finalize()throws This function closes the connection to the file
IOException{} and throws IOException.
public void write(int w)throws Using this function, you can write specified
IOException{} bytes to the output stream.
This function is used to write bytes of length
public void write(byte[] w) equal to w to the output stream from the the
mentioned byte array.
Character Stream
For handling the input and output of characters Character Stream is incorporated,
which streamlines internationalization.
The hierarchical distribution of Character stream is different from Byte Stream. The
hierarchical tree of Character Stream is topped by the Reader and Writer abstract
classes. Reader abstract class is used for input while Writer abstract class is used for
output.
The method defined by Reader abstract class is given below :
35. Function / Method Description
abstract void close( ) throws
The input source is closed using this function.
IOException
This function set a mark in the input stream at the
void mark(int numChars) throws
current point. This Point will remain valid till
IOException
numChars characters are read.
If the stream support mark( )/reset( ) , this
boolean markSupported( )
function returns true.
The input streams' next available character is
int read( ) throws IOException return by this function as an integer
representation.
This function reads the characters from buffer
int read(char buffer[ ]) throws
equal to the length of buffer.length and it returns
IOException
the number of successful characters read.
abstract int read(char buffer[ This function returns the count of the characters
],int offset, int numChars) successfully read from buffer starting from
throws IOException buffer[offset] up to numChars.
boolean ready( ) throws If the input is pending, it returns true otherwise
IOException false.
This function resets the input pointer to the
void reset( ) throws IOException
previously set mark.
long skip(long numChars) This function skips the number of input characters
36. throws IOException equal to numChars. It returns the count of actually
skipped characters.
The method defined by Writer abstract class is given below :
Function / Method Description
This function adds ch at the end of the
Writer append(char ch) throws
output stream which invoked it. It also
IOException
returns reference to the stream.
This function adds the chars to the end of
Writer append(CharSequence chars)
the output stream which invoked it. It also
throws IOException
returns a reference to the stream.
This function adds a sub range of chars to
Writer append(CharSequence chars,
the end of the output stream. It returns a
int begin, int end) throws IOException
reference to the stream.
abstract void close( ) throws
The output stream is closed by this function.
IOException
abstract void flush( ) throws
This function flushes the buffer of output.
IOException
This function writes the character to the
void write(int ch) throws IOException output stream. The characters are in the
low-order 16 bits of ch .
Using this function you can write to the
void write(char buffer[ ]) throws
output stream -a complete array of
37. IOException characters .
This function is used to writes a sub range
abstract void write(char buffer[ ],int
of numChars characters from the array
offset, int numChars) throws
buffer to the output stream beginning at
IOException
buffer[offset].
void write(String str) throws Using this function you can writes str to the
IOException output stream.
Using this function, from the string str ,you
void write(String str, int offset, int
can write a sub range of numChars
numChars)
characters.
The File Class
In spite of classes available to support file I/O, Java has a class named as File, which
contains information about a file. For manipulating a file or the computer's file system,
this class is very effective and efficient. This class is used for creation of files and
directories, file searching, file deletion etc.
Once you have File object in hand then there is a list of helper methods which can be
used manipulate the files, which are given below :
Methods Description
public String This function returns the file or directory's name specified by
getName() the pathname.
This function returns the parent directory pathname string.
public String
The pathname of the directory is passed to know it's parent
38. getParent() pathname string. If the pathname doesn't have parent
directory, it returns null.
public File getParent This function returns the parent directory abstract pathname
File() and it returns null if it doesn't have parent directory.
public String To convert the abstract pathname into a pathname string, we
getPath() use this function.
public boolean This function return true if this abstract pathname is absolute
isAbsolute() otherwise returns false.
public String To find the absolute pathname string of the provided abstract
getAbsolutePath() pathname, we incorporate this method.
This function is used to check if the application can read the
public boolean file provided by this abstract
canRead() pathname. This function returns true if the file name provided
by the abstract pathname exists otherwise return false.
This function is used to check if the application can modify to
the file provided through this abstract
public boolean
pathname. This function returns true if the file name provided
canWrite()
by the abstract pathname exists and allowed to write,
otherwise return false.
public boolean This function returns true if the file name provided by the
exists() abstract pathname exists otherwise return false.
public boolean This function returns true if the file represented by the
39. isDirectory() abstract pathname is a directory otherwise returns false.
This function is used to test whether the file represented by
public boolean
the abstract pathname exist and also checks whether it is a
isFile()
normal file. If it is , it will return true otherwise return false.
public long This function is used to return the last modification time of the
lastModified() file represented by the abstract pathname.
This function finds the length of the file of the file represented
public long length() by the abstract pathname and return it. It returns unspecified
if the pathname represented is a directory.
public boolean This function is used to create a new file which has the name
createNewFile() provided by its abstract pathname. It will return true if the file
throws IOException created successfully otherwise returns false.
public boolean This function is used to delete the file/directory represented
delete() by the abstract pathname.
public void This function is used to delete the file represented by the
deleteOnExit() abstract pathname when the virtual machine terminates.
This function returns an array of strings naming the files and
public String[] list() directories in the directory specified by its abstract
pathname.
public String[] This function returns an array of strings naming the files and
list(FilenameFilter directories in the directory specified by its abstract pathname
filter) that satisfy the specified filter.
40. public File[] This functions returns an array of abstract pathnames
listFiles() represented by the files in the directory.
This function returns an array of abstract pathnames
public File[] represented by the files and directories
listFiles(FileFilter in the directory represented by this abstract pathname that
filter) satisfy the
specified filter.
This function creates the directory named by this abstract
public boolean
pathname. this function returns true if the file created
mkdir()
successfully otherwise false.
This method creates the directory named by this abstract
pathname, including any
public boolean necessary but nonexistent parent directories. Returns true if
mkdirs() and only ifbr> the directory was created, along with all
necessary parent directories;
false otherwise
public boolean
This function renames the file represented by this abstract
renameTo(File
pathname.
dest)
public boolean This function is used to set the last modification time of the
setLastModified(long file/ directory specified by the abstract
time) pathname.
public boolean This function sets the file provided through abstract
setReadOnly() pathname to read-only mode. If it succeeded, it returns true
41. otherwise returns false.
public String This function is used to return the pathname string of the
toString() abstract pathname provided.
FileReader Class
FileReader class inherits from the InputStreamReader class. For reading streams of
characters, this class is used.
Once you have FileReader object in hand then there is a list of helper methods which
can be used manipulate the files :
Method /
Description
Function
public int
read() This function reads a single character at a time and returns the count
throws of number of character read.
IOException
public int
read(char [] This function is used to read characters. An array is used to read
c, int offset, characters.
int len)
package com.mkyong.file;
import java.io.File;
42. import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class AppendToFileExample
{
public static void main( String[] args )
{
try{
String data = " This content will append to the end
of the file";
File file =new File("javaio-appendfile.txt");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
43. FileWriter fileWritter = new
FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new
BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
}
}
b)
A checked exception is any subclass of Exception (or Exception itself),
excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the
possibility that the exception will be thrown. eg, IOException thrown by
java.io.FileInputStream's read() method
Unchecked exceptions are RuntimeException and any of its subclasses. Class
Error and its subclasses also are unchecked.
With an unchecked exception, however, the compiler doesn't force client
programmers either to catch the exception or declare it in a throws clause.
44. In fact, client programmers may not even know that the exception could be
thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt()
method.
Checked exceptions must be caught at compile time. Runtime exceptions do
not need to be. Errors often cannot be, as they tend to be unrecoverable.
public void storeDataFromUrl(String url){
try {
String data = readDataFromUrl(url);
} catch (BadUrlException e) {
e.printStackTrace();
}
}
public String readDataFromUrl(String url)
throws BadUrlException{
if(isUrlBad(url)){
throw new BadUrlException("Bad URL: " + url);
}
45. String data = null;
//read lots of data over HTTP and return
//it as a String instance.
return data;
}
As you can see the readDataFromUrl() method throws a BadUrlException. I
have created BadUrlException myself. BadUrlException is a checked
exception because it extends java.lang.Exception:
public class BadUrlException extends Exception {
public BadUrlException(String s) {
super(s);
}
}
If storeDataFromUrl() wants to call readDataFromUrl() it has only two choices.
Either it catches the BadUrlException or propagates it up the call stack. The
46. storeDataFromUrl() listed above catches the exception. This
storeDataFromUrl() implementation propagates the BadUrlException instead:
public void storeDataFromUrl(String url)
throws BadUrlException{
String data = readDataFromUrl(url);
}
Notice how the try catch block is gone and a "throws BadUrlException"
declaration is added instead. Now, let's see how it looks with unchecked
exceptions. First I change the BadUrlException to extend
java.lang.RuntimeException instead:
public class BadUrlException extends RuntimeException {
public BadUrlException(String s) {
super(s);
}
}
Then I change the methods to use the now unchecked BadUrlException:
public void storeDataFromUrl(String url){
47. String data = readDataFromUrl(url);
}
public String readDataFromUrl(String url) {
if(isUrlBad(url)){
throw new BadUrlException("Bad URL: " + url);
}
String data = null;
//read lots of data over HTTP and
//return it as a String instance.
return data;
}
Notice how the readDataFromUrl() method no longer declares that it throws
BadUrlException. The storeDataFromUrl() method doesn't have to catch the
BadUrlException either. The storeDataFromUrl() method can still choose to
48. catch the exception but it no longer has to, and it no longer has to declare that
it propagates the exception.
6
A
ava provides built-in support for multithreaded programming. A multithreaded program contains two or more parts
that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of
execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking
processes.
I need to define another term related to threads: process: A process consists of the memory space allocated by the
operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a
process. A process remains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time
can be kept to a minimum.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies.
Following diagram shows complete life cycle of a thread.
Above mentioned stages are explained here:
New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It
is also referred to as a born thread.
49. Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to
be executing its task.
Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a
task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue
executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this
state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By
default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-
priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much
platform dependentant.
Creating a Thread:
Java defines two ways in which this can be accomplished:
You can implement the Runnable interface.
You can extend the Thread class, itself.
Create Thread by Implementing Runnable:
The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class need only implement a single method called run( ), which is declared like this:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important to understand that run()
can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class.
Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is
specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within
Thread. The start( ) method is shown here:
void start( );
here are two ways of creating a thread.
1. Extending the Thread class
50. Ex: public class ThreadExample extends Thread {
.....
}
2. Implementing the Runnable Interface
Ex: public class ThreadExample implements Runnable {
...........
}
notify() is used to unblock one waiting thread; notifyAll() is used to unblock
all of them. Using notify() is preferable (for efficiency) when only one
blocked thread can benefit from the change (for example, when freeing a
buffer back into a pool). notifyAll() is necessary (for correctness) if multiple
threads should resume (for example, when releasing a "writer" lock on a file
might permit all "readers" to resume).
b)
Layout managers are software components used in widget toolkits which have the
ability to lay out widgets by their relative positions without using distance units. It is often
more natural to define component layouts in this manner than to define their position
in pixels or common distance units, so a number of popular widget toolkits include this
ability by default. Widget toolkits that provide this function can generally be classified
into two groups:
Those where the layout behavior is coded in special graphic containers. This is the
case in XUL and the .NET Framework widget toolkit (both in Windows Forms and
in XAML).
Those where the layout behavior is coded in layout managers, that can be applied to
any graphic container. This is the case in the Swing widget toolkit that is part of
the Java API.
51. Explain different layout manager in Java.
A layout manager organizes the objects in a container
Different layouts are used to organize or to arrange objects
1. Border Layout:
- It has five areas for holding components: north, east, west, south and center
- When there are only 5 elements to be placed, border layout is the right choice
2. Flow Layout:
- Default layout manager.
- It lays out the components from left to right
3. Card Layout:
- Different components at different times are laid out
- Controlled by a combo box, determining which panel the Card layout displays
4. Grid Layout:
- A group of components are laid out I equal size and displays them in certain rows and columns
5. Grid Bag Layout:
- Flexible layout for placing components within a grid of cells
- Allows certain components to span more than one cell
- The rows of the grid are not of the same height and height
7
A
A Java applet is an applet delivered to users in the form of Java bytecode. Java applets
can be part of a web page and executed by the Java Virtual Machine (JVM) in
a process separate from the web browser, or run in Sun's AppletViewer, a stand-alone
tool for testing applets. Java applets were introduced in the first version of the Java
language in 1995, and are written in programming languages that compile to Java
52. bytecode, usually in Java, but also in other languages such
as Jython,[8] JRuby,[9] or Eiffel (via SmartEiffel).[10]
Java applets run at very fast speeds comparable to, but generally slower than, other
compiled languages such as C++, but until approximately 2011 many times faster
than JavaScript.[11] In addition they can use 3D hardware acceleration that is available
from Java. This makes applets well suited for non-trivial, computation intensive
visualizations. As browsers have gained support for hardware accelerated graphics
thanks to the canvas technology (or specifically WebGL in the case of 3D graphics), as
well as just in time compiled JavaScript, the speed difference has become less
noticeable.
Since Java's bytecode is cross-platform or platform independent, Java applets can be
executed by browsers for many platforms, including Microsoft Windows, Unix, OS
X and Linux. It is also trivial to run a Java applet as an application software with very
little extra code so that it can be run directly from the integrated development
environment (IDE).
import java.applet.Applet;
import java.awt.*;
// Applet code for the "Hello, world!" example.
// This should be saved in a file named as "HelloWorld.java".
public class HelloWorld extends Applet {
// This method is mandatory, but can be empty (i.e., have no
actual code).
public void init() { }
// This method is mandatory, but can be empty.(i.e.,have no
actual code).
public void stop() { }
// Print a message on the screen (x=20, y=10).
public void paint(Graphics g) {
g.drawString("Hello, world!", 20,10);
// Draws a circle on the screen (x=40, y=30).
g.drawArc(40,30,20,20,0,360);
}
}
53. mport java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Mouse1 extends Applet
implements MouseListener, MouseMotionListener {
int width, height;
int mx, my; // the mouse coordinates
boolean isButtonPressed = false;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
mx = width/2;
my = height/2;
addMouseListener( this );
addMouseMotionListener( this );
}
public void mouseEntered( MouseEvent e ) {
// called when the pointer enters the applet's rectangular area
}
public void mouseExited( MouseEvent e ) {
// called when the pointer leaves the applet's rectangular area
}
public void mouseClicked( MouseEvent e ) {
// called after a press and release of a mouse button
// with no motion in between
// (If the user presses, drags, and then releases, there will be
// no click event generated.)
}
public void mousePressed( MouseEvent e ) { // called after a button is
pressed down
isButtonPressed = true;
setBackground( Color.gray );
repaint();
// "Consume" the event so it won't be processed in the
// default manner by the source which generated it.
e.consume();
}
public void mouseReleased( MouseEvent e ) { // called after a button is
released
isButtonPressed = false;
setBackground( Color.black );
repaint();
e.consume();
}
public void mouseMoved( MouseEvent e ) { // called during motion when no
buttons are down
mx = e.getX();
my = e.getY();
showStatus( "Mouse at (" + mx + "," + my + ")" );
repaint();
54. e.consume();
}
public void mouseDragged( MouseEvent e ) { // called during motion with
buttons down
mx = e.getX();
my = e.getY();
showStatus( "Mouse at (" + mx + "," + my + ")" );
repaint();
e.consume();
}
public void paint( Graphics g ) {
if ( isButtonPressed ) {
g.setColor( Color.black );
}
else {
g.setColor( Color.gray );
}
g.fillRect( mx-20, my-20, 40, 40 );
}
}
b)
8
JavaBeans are reusable software components for Java. Practically, they are classes written in
the Java programming language conforming to a particular convention. They are used to
encapsulate many objects into a single object (the bean), so that they can be passed around as
55. a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that
isserializable, has a 0-argument constructor, and allows access to properties using getter and
setter methods.
A Java Bean is a software component that has been designed to be reusable in a variety of different
environments. There is no restriction on the capability of a Bean. It may perform a simple function, such
as checking the spelling of a document, or a complex function, such as forecasting the performance of a
stock portfolio. A Bean may be visible to an end user. One example of this is a button on a graphical user
interface. A Bean may also be invisible to a user. Software to decode a stream of multimedia information
in real time is an example of this type of building block. Finally, a Bean may be designed to work
autonomously on a user's workstation or to work in cooperation with a set of other distributed
components. Software to generate a pie chart from a set of data points is an example of a Bean that can
execute locally. However, a Bean that provides real-time price information from a stock or commodities
exchange would need to work in cooperation with other distributed software to obtain its data.
We will see shortly what specific changes a software developer must make to a class so that it is
usable as a Java Bean. However, one of the goals of the Java designers was to make it easy to use
this technology. Therefore, the code changes are minimal.
Advantages of Java Beans
A software component architecture provides standard mechanisms to deal with software building
blocks. The following list enumerates some of the specific benefits that Java technology provides for
a component developer:
A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm.
The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled.
A Bean may be designed to operate correctly in different locales, which makes it
useful in global markets.
Auxiliary software can be provided to help a person configure a Bean. This software is
only needed when the design-time parameters for that component are being set. It
does not need to be included in the run-time environment.
The configuration settings of a Bean can be saved in persistent storage and restored
at a later time.
A Bean may register to receive events from other objects and can generate events that
are sent to other objects.