0% found this document useful (0 votes)
2 views294 pages

Java Materials

The document provides a comprehensive overview of the history, features, and programming principles of Java, originally developed by James Gosling and his team at Sun Microsystems in the early 1990s. It highlights Java's evolution from its initial design for interactive television to its current status as a widely-used programming language, emphasizing its object-oriented nature, portability, and security features. Additionally, it includes a simple Java program example and discusses the significance of naming conventions in Java programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views294 pages

Java Materials

The document provides a comprehensive overview of the history, features, and programming principles of Java, originally developed by James Gosling and his team at Sun Microsystems in the early 1990s. It highlights Java's evolution from its initial design for interactive television to its current status as a widely-used programming language, emphasizing its object-oriented nature, portability, and security features. Additionally, it includes a simple Java program example and discusses the significance of naming conventions in Java programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Oject Oriented Programming using

Java
2
3
History of Java

The history of Java is very interesting. Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time. The history of Java starts with the Green
Team. Java team members (also known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured,
High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java
was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team
members started the project in the early '90s.

4
1) James Gosling, Mike Sheridan, and Patrick
Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems
in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and
the file extension was .gt.
4) After that, it was called Oak and was developed as a part
of the Green project.
Why Java was named as "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as
a national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was
already a trademark by Oak Technologies.

5
Why Java Programming named "Java"?
7) Why had they chose the name Java for Java language? The team gathered to choose a
new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA",
etc. They wanted something that reflected the essence of the technology: revolutionary,
dynamic, lively, cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It
is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of
coffee nearby his office.

6
9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems


(which is now a subsidiary of Oracle Corporation) and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many
additional features added to the language. Now Java is being used in Windows applications, Web
applications, enterprise applications, mobile applications, cards, etc. Each new version adds new features in
Java.

Java Version History


Many java versions have been released till now. The current stable release of Java is Java SE 10

JDK Alpha and Beta (1995)


JDK 1.0 (23rd Jan 1996) Java SE 13 (September 2019)
JDK 1.1 (19th Feb 1997) Java SE 14 (Mar 2020)
J2SE 1.2 (8th Dec 1998)
Java SE 15 (September 2020)
J2SE 1.3 (8th May 2000)
Java SE 16 (Mar 2021)
J2SE 1.4 (6th Feb 2002)
J2SE 5.0 (30th Sep 2004) Java SE 17 (September 2021)
Java SE 6 (11th Dec 2006) Java SE 18 (to be released by March 2022)
Java SE 7 (28th July 2011)
Java SE 8 (18th Mar 2014)
Java SE 9 (21st Sep 2017)
Java SE 10 (20th Mar 2018)
Java SE 11 (September 2018)
Java SE 12 (March 2019)

7
Features of Java
The primary objective of Java programming
language creation was to make it portable, simple and secure programming language. Apart from
this, there are also some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

8
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a
simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.
Object-oriented

Java is an object-oriented
programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of
different types of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some
rules.

Basic concepts of OOPs are:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

9
Platform Independent
Java is platform independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into
platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or
software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on top
of other hardware-based platforms. It has two components:

• Runtime Environment
• API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).

10
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

• No explicit pointer
• Java Programs run inside a virtual machine sandbox

• Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java
classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
• Security Manager: It determines what resources a class can access such as reading and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.
11
Robust
The English mining of Robust is strong. Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
12
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is
an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.

Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

13
C++ vs Java
There are many differences and similarities between the C++ programming
language and Java

A list of top differences between C++ and Java are given below:

14
First Java Program | Hello World Example

The requirement for Java Hello World Example


For executing any Java program, the following software or application must be properly
installed.

download the JDK and install it.


Set path of the jdk/bin directory.
Create the Java program
Compile and run the Java program

class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
Save the above file as [Link].

To compile:
javac [Link]
To execute:
15
java Simple
16
17
Compilation Flow:

When we compile Java program using javac tool, the Java compiler converts the
source code into byte code.

Parameters used in First Java Program


• Let's see what is the meaning of class,
class, public, static, void, main, String[], [Link]().
• class keyword is used to declare a class in Java.
• public keyword is an access modifier that represents visibility. It means it is visible to all.
• static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method
is that there is no need to create an object to invoke the static method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it saves memory.
• void is the return type of the method. It means it doesn't return any value.
• main represents the starting point of the program.
• String[] args or String args[] is used for command line argument. We will discuss it in coming section.
• [Link]() is used to print statement. Here, System is a class, out is an object of the PrintStream class, println() is a
18
method of the PrintStream class. We will discuss the internal working of [Link]() statement in the coming section
19
To write the simple program, you need to open notepad by start menu -> All Programs -> Accessories ->
Notepad and write a simple program as we have shownbelow:

As displayed in the above diagram, write the simple program of Java in notepad and saved it as
[Link]. In order to compile and run the above program, you need to open the command
prompt by start menu -> All Programs -> Accessories -> command prompt. When we have
done with all the steps properly, it shows the following output:
20
To compile and run the above program, go to your current directory first; my current directory is
c:\new. Write here:

To compile:
javac [Link]
To execute:
java Simple

21
In how many ways we can write a Java program?
There are many ways to write a Java program. The modifications that can be done in a Java
program are given below:

1) By changing the sequence of the modifiers, method prototype is not changed in Java.

Let's see the simple code of the main method

2) The subscript notation in the Java array can be used after type, before the variable or
after the variable.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])

3) You can provide var-args support to the main() method by passing 3 ellipses (dots)

Let's see the simple code of using var-args in the main() method. We will learn about var-
args later in the Java New Features chapter.

4) Having a semicolon at the end of class is optional in Java.

Let's see the simple code.


22
4) Having a semicolon at the end of class is optional in Java.
class A
{
static public void main(String... args)
{
[Link]("hello java4");
}
};

Valid Java main() method signature

public static void main(String[] args)


public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void main(String[] args)

23
24
Java Platform

25
26
27
28
29
30
31
32
33
Unit - II
WHAT ARE Objects?
 An object has:
 –state - descriptive characteristics
 –behaviors - what it can do (or what can be done
to it)
 The state of a bank account includes its account
number and its current balance•
 The behaviors associated with a bank account
include the ability to make deposits and
withdrawals
 Note that the behavior of an object might change
its state. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.
•A class is the blueprint of an object
•The class uses methods to define the behaviors
of the object
•The class that contains the main method of a
Java program represents the entire program
•A class represents a concept, and an object
represents the embodiment of that concept
•Multiple objects can be created from the same
class
Syntax to declare a class:
class <class_name>
{
data member;
method;
}
class Student1{
int id; //data member (also instance variabl
e)
String name; //data member(also instance variable)

void getId(); //member function

public static void main(String args[])


{
Student1 s1=new Student1();
//creating an object of Student
[Link]([Link]);
[Link]([Link]);
[Link]();
}
Advantage of Method
•Code Reusability
•Code Optimization
 Javanaming convention is a rule to
follow as you decide what to name
your identifiers such as class,
package, variable, constant, method,
etc.
Identifiers Naming Rules Examples
Type
Class It should start with the public
uppercase letter. class Employee
It should be a noun {
such as Color, Button, //code
System, Thread, etc. }
Use appropriate words,
instead of acronyms.
Metho It should start with class Employee
d lowercase letter. {
It should be a verb such // method
as main(), print(), void draw()
println(). {
If the name contains //code snippet
multiple words, start it }
with a lowercase letter }
followed by an
uppercase letter such as
actionPerformed().
Variable It should start with a lowercase class Employee
letter such as id, name. {
It should not start with the special // variable
characters like & (ampersand), $ int id;
(dollar), _ (underscore). //code snippet
If the name contains multiple }
words, start it with the lowercase
letter followed by an uppercase
letter such as firstName,
lastName.
Avoid using one-character
variables such as x, y, z.
 Theaccess modifiers in Java specifies the
accessibility or scope of a field, method,
constructor, or class.
 We can change the access level of fields,
constructors, methods, and class by
applying the access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is
only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is
only within the package. It cannot be accessed
from outside the package. If you do not specify
any access level, it will be the default.
3. Protected: The access level of a protected
modifier is within the package and outside the
package through child class. If you do not make the
child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is
everywhere. It can be accessed from within the
class, outside the class, within the package and
outside the package.
 A constructor in Java is a special
method that is used to initialize objects.
 The constructor is called when an object
of a class is created.
 It can be used to set initial values for
object attributes:






 








 The java command-line argument is an
argument i.e. passed at the time of running the
java program.
 The arguments passed from the console can be
received in the java program and it can be used
as an input.
In this example, we are receiving only one
argument and printing it.
To run this java program, you must pass at least
one argument from the command prompt.
class CommandLineExample
{
public static void main(String args[])
{
[Link]("Your first argument is: "+args[0]);
}
}
 compile by > javac [Link]
 run by > java CommandLineExample sonoo

Output:
Your first argument is: sonoo
 The this keyword refers to the current object in a
method or constructor.
 The most common use of the this keyword is to
eliminate the confusion between class attributes and
parameters with the same name
 There can be a lot of usage of Java this keyword. In
Java, this is a reference variable that refers to the
current object.
 The final keyword is a non-access modifier used for
classes, attributes and methods, which makes them
non-changeable (impossible to inherit or override).
 The final keyword is useful when you want a variable
to always store the same value, like PI (3.14159...).
 The final keyword is called a "modifier".








 The static keyword in Java is used for memory
management mainly.
 We can apply static keyword with variables, methods,
blocks and nested classes.
 If you declare any variable as static, it is known as a
static variable.
 The static variable can be used to refer to the
common property of all objects (which is not unique
for each object), for example, the company name of
employees, college name of students, etc.
 The static variable gets memory only once in the
class area at the time of class loading.
 A class which contains the abstract keyword in its
declaration is known as an abstract class.
 An abstract class is a class that is declared abstract
means it may or may not include abstract methods.
 Abstract classes may not be marked as private or final.
abstract class syntax

public abstract class DemoClass


{
//declare other methods and fields
}
 The abstract keyword is a non-access modifier, used
for classes and methods. Class:
 An abstract class is a restricted class that cannot be
used to create objects (to access it, it must be inherited
from another class).
 Method: An abstract method can only be used in an
abstract class, and it does not have a body.
 The Finalize method is used to perform
cleanup operations on unmanaged
resources held by the current object before
the object is destroyed.
 The method is protected and therefore is
accessible only through this class or through a
derived class.
 Finalize() is the method of Object class.
 This method is called just before an object is garbage
collected.
 finalize() method overrides to dispose system
resources, perform clean-up activities and minimize
memory leaks.
 If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.

Advantage of method overloading


 Method overloading increases the readability of the
program.
Different ways to overload the method
There are two ways to overload the method in
java
 By changing number of arguments
 By changing the data type
1) Method Overloading: changing no. of arguments
 In this example, we have created two methods, first
add() method performs addition of two numbers and
second add method performs addition of three
numbers.
 In this example, we are creating static methods so
that we don't need to create instance for calling
methods.
class Adder
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
Output:
22
33
2) Method Overloading: changing data type of
arguments
 In this example, we have created two methods that
differs in data type.
 The first add method receives two integer arguments
and second add method receives two double
arguments.
class Adder
{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}
}
Output:
22
24.9
 Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs
(Object Oriented programming system).
 The idea behind inheritance in Java is that you can
create new classes that are built upon existing classes.
 For Method Overriding
 For Code Reusability.
 Class: A class is a group of objects which have
common properties. It is a template or blueprint from
which objects are created.
 Sub Class/Child Class: Subclass is a class which
inherits the other class. It is also called a derived class,
extended class, or child class.
 Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a
base class or a parent class.
 Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new
class. You can use the same fields and methods already
defined in the previous class.
class Subclass-name extends Superclass-name
{
//methods and fields
}

 The extends keyword indicates that you are making a


new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
 On the basis of class, there can be single, and
multilevel
When a class inherits another class, it is known as
a single inheritance.
In the example given below, Dog class inherits the
Animal class, so there is the single inheritance.
class Animal
{
void eat(){[Link]("eating...");}
}
class Dog extends Animal
{
void bark(){[Link]("barking...");}
}
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}
}
Output:

barking...
eating...
 When there is a chain of inheritance, it is
known as multilevel inheritance.
 As you can see in the example given below,
BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a
multilevel inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:
weeping...
barking...
eating...
 Dynamic method dispatch is a mechanism by which a
call to an overridden method is resolved at runtime.
 This is how java implements runtime polymorphism.
 When an overridden method is called by a reference,
java determines which version of that method to
execute based on the type of object it refer to.
Upcasting in Java
 When Parent class reference variable refers
to Child class object, it is known as Upcasting.
 In Java this can be done and is helpful in scenarios
where multiple child classes extends one parent class.
 In those cases we can create a parent class reference
and assign child class objects to it.
 The super keyword in Java is a reference variable
which is used to refer immediate parent class object.
 Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword
 super can be used to refer immediate parent class
instance variable.
 super can be used to invoke immediate parent class
method.
 super() can be used to invoke immediate parent class
constructor.

super is used to refer immediate parent class


instance variable.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}
Output:

black
white
 An interface is a reference type in Java. It is
similar to class. It is a collection of abstract
methods.
 A class implements an interface, thereby
inheriting the abstract methods of the
interface.
 The interface keyword is used to declare an
interface.
 Here is a simple example to declare an interface −
Example
/* File name : [Link] */
interface Animal
{
public void eat();
public void travel();
}
 A class uses the implements keyword to
implement an interface.
 The implements keyword appears in the class
declaration following the extends portion of
the declaration.
/* File name : [Link] */
public class MammalInt implements Animal
{
public void eat()
{ [Link]("Mammal eats"); }
public void travel()
{ [Link]("Mammal travels"); }
public int noOfLegs()
{ return 0; }
public static void main(String args[])
{
MammalInt m = new MammalInt();
[Link]();
[Link]();
}
}
Mammal eats
Mammal travels
When implementation interfaces, there are several rules −
 A class can implement more than one interface at a
time.
 A class can extend only one class, but implement many
interfaces.
 An interface can extend another interface, in a similar
way as a class can extend another class.
 In java, an interface can extend another interface. When
an interface wants to extend another interface, it uses
the keyword extends.
 The interface that extends another interface has its own
members and all the members defined in its parent
interface too.
 The class which implements a child interface needs to
provide code for the methods defined in both child and
parent interfaces
interface ParentInterface
{ void parentMethod(); }

interface ChildInterface extends ParentInterface


{ void childMethod(); }

class ImplementingClass implements ChildInterface


{ public void childMethod()
{ [Link]("Child Interface method!!"); }
public void parentMethod()
{
[Link]("Parent Interface method!"); }
}
public class ExtendingAnInterface
{
public static void main(String[] args)
{
ImplementingClass obj = new ImplementingClass();
[Link]();
[Link]();
}
}
Output
Child Interface method!!
Parent Interface method!
 A java package is a group of similar types of
classes, interfaces and sub-packages.
 Package in java can be categorized in two
form, built-in package and user-defined
package.
 There are many built-in packages such as java,
lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
 1) Java package is used to categorize the
classes and interfaces so that they can be
easily maintained.
 2) Java package provides access protection.
Simple example of java package
 The package keyword is used to create a package in
java.
//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}
How to access package from another
package?
There are three ways to access the
package from outside the package.
 import package.*;
 import [Link];
 fully qualified name.
 If you use package.* then all the classes and
interfaces of this package will be accessible
but not subpackages.
 The import keyword is used to make the
classes and interface of another package
accessible to the current package.
//save by [Link]
package pack;
public class A
{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;

class B
{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:
Hello
 If you import [Link] then only declared
class of this package will be accessible.

//save by [Link]
package pack;
public class A
{
public void msg()
{[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;

class B{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output:
Hello
 If you use fully qualified name then only
declared class of this package will be
accessible.
 Now there is no need to import.
 But you need to use fully qualified name every
time when you are accessing the class or
interface.
//save by [Link]
package pack;
public class A
{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B
{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Output:
Hello
 Note: If you import a package, subpackages will not
be imported.

 Note: The standard of defining package is


[Link] e.g. [Link] or
[Link].
package [Link];
class Simple
{
public static void main(String args[])
{
[Link]("Hello subpackage");
}
}
Let’s quickly compare these access modifiers.
 public – accessible everywhere
 protected – accessible in the same package and in sub-
classes
 default – accessible only in the same package
 private – accessible only in the same class
 [Link] package contains the classes that are
fundamental to the design of the Java
programming language
 The package [Link] contains classes and
interfaces that are essential to the java
language. These includes:
 The package [Link] contains classes and
interfaces that are essential to the Java
programming language.
 This [Link] package contains Object,
Thread, String etc. Object class is the ultimate
super class of all classes in Java.
 Thread class that controls each thread in a
multi threaded program.
 Object, the ultimate superclass of all classes in java
 Thread, the class that controls each thread in a
multithread program
 Throwable, the superclass of all error and exception
classes in java.
 Classes for accessing system resources and other low-
level entities.
 Math, a class that provides mathematical methods
 String, that class is used to represent strings.
 The wrapper class in Java provides the
mechanism to convert primitive into
object and object into primitive.
 autoboxing and unboxing feature convert
primitives into objects and objects into
primitives automatically.
 The eight classes of the [Link] package are
known as wrapper classes in Java. The list of
eight wrapper classes are given below:
Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
 The automatic conversion of primitive data
type into its corresponding wrapper class is
known as autoboxing,
 for example, byte to Byte, char to Character,
int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and
short to Short.
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=[Link](a);//converting int into Integer explicitl
Integer j=a;//autoboxing, now compiler will write [Link]
internally
[Link](a+" "+i+" "+j);
}
}
Output

20 20 20
 The automatic conversion of wrapper
type into its corresponding primitive type
is known as unboxing.
 It is the reverse process of autoboxing.
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=[Link]();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write [Link]()
internally
[Link](a+" "+i+" "+j);
}
}
Output
333
Unit - III
Fundamentals of Exception

The Exception Handling in Java is one of the


powerful mechanism to handle the runtime errors so
that the normal flow of the application can be
maintained.
 Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
 The core advantage of exception handling is to
maintain the normal flow of the application.
 An exception normally disrupts the normal flow of
the application; that is why we need to handle
exceptions.
 Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
 Suppose there are 10 statements in a Java program and
an exception occurs at statement 5; the rest of the code
will not be executed, i.e., statements 6 to 10 will not be
executed.
 However, when we perform exception handling, the
rest of the statements will be executed. That is why we
use exception handling in Java.
 Checked exceptions are called compile-
time exceptions because these exceptions are checked
at compile-time by the compiler.
 The compiler ensures whether the programmer handles
the exception or not. The programmer should have to
handle the exception; otherwise, the system has shown
a compilation error.
 The unchecked exceptions are just opposite to
the checked exceptions.
 The compiler will not check these exceptions at
compile time.
 In simple words, if a program throws an unchecked
exception, and even if we didn't handle or declare it,
the program would not give a compilation error.
 Usually, it occurs when the user provides bad data
during the interaction with the program.
Keyword Description
try The "try" keyword is used to specify a block where we should
place an exception code. It means we can't use try block alone.
The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It


specifies that there may occur an exception in the
method.
public class JavaExceptionExample
{
public static void main(String args[])
{
try
{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e) {[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}
 Output
Exception in thread main
[Link]:/ by zero
rest of the code...

In the above example, 100/0 raises an


ArithmeticException which is handled by a try-catch
block.
 When an array exceeds to it's size, the
ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur
ArrayIndexOutOfBoundsException.
 Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
public class TestFinallyBlock2{
public static void main(String args[]){

try {

[Link]("Inside try block");

//below code throws divide by zero exception


int data=25/0;
[Link](data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
[Link]("Exception handled");
[Link](e);
}

//executes regardless of exception occured or not


finally {
[Link]("finally block is always executed");
}

[Link]("rest of the code...");


}
}
public class TestFinallyBlock1{
public static void main(String args[]){
try {
[Link]("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
[Link](data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
[Link](e);
}
//executes regardless of exception occured or not
finally {
[Link]("finally block is always executed");
}

[Link]("rest of the code...");


}
}
 Multithreading in Java is a process of
executing multiple threads simultaneously.
 A thread is a lightweight sub-process, the
smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve
multitasking.
 However, we use multithreading than multiprocessing
because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and
context-switching between the threads takes less time
than process.
 Java Multithreading is mostly used in games,
animation, etc.
1) It doesn't block the user because threads are
independent and you can perform multiple operations at
the same time.
2) You can perform many operations together, so it
saves time.
3) Threads are independent, so it doesn't affect other
threads if an exception occurs in a single thread.
 A thread is a lightweight subprocess, the smallest unit
of processing. It is a separate path of execution.
 Threads are independent. If there occurs exception in
one thread, it doesn't affect other threads. It uses a
shared memory area.
 As shown in the above figure, a thread is
executed inside the process.
 There is context-switching between the
threads.
 There can be multiple processes inside the OS,
and one process can have multiple threads.
In Java, a thread always exists in any one of the
following states. These states are:
 New
 Active
 Blocked / Waiting
 Timed Waiting
 Terminated
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Output:
 thread is running...
class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
[Link]();
}
}
Output:
 thread is running...
public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(S
tring name)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
[Link]();
// getting the thread name by invoking the getName() method
String str = [Link]();
[Link](str);
}
}
Output:
My first thread
Unit - IV
An applet is a Java program that can be
embedded into a web page.
It runs inside the web browser and works at
client side.
An applet is embedded in an HTML page using
the APPLET tag
Applets are used to make the website more
dynamic and entertaining.
 All applets are sub-classes (either directly or
indirectly) of [Link] class.
 Applets are not stand-alone programs. Instead,
they run within either a web browser or an
applet viewer. JDK provides a standard applet
viewer tool called applet viewer.
 In general, execution of an applet does not
begin at main() method.
 Output of an applet window is not performed
by [Link](). Rather it is handled
with various AWT methods, such
as drawString().
 It is important to understand the order in which
the various methods shown in the above image
are called. When an applet begins, the
following methods are called, in this
sequence:
1. init( )
2. start( )
3. paint( )
 When an applet is terminated, the
following sequence of method calls takes
place:
1. stop( )
2. destroy( )
 1. init( ) : The init( ) method is the first method to be
called. This is where you should initialize variables.
This method is called only once during the run time of
your applet.
 2. start( ) : The start( ) method is called after init( ). It
is also called to restart an applet after it has been
stopped
 3. paint( ) : The paint( ) method is called each time an
AWT-based applet’s output must be redrawn.
 4. stop( ) : The stop( ) method is called when
a web browser leaves the HTML document
containing the applet—when it goes to another
page
 5. destroy( ) : The destroy( ) method is called
when the environment determines that your
applet needs to be removed completely from
memory
//[Link]
import [Link];
import [Link];
public class First extends Applet{
public void paint(Graphics g){
[Link]("welcome to applet",150,150);
}
}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool,
write in command prompt:
C:/> Javac [Link]
C:/> appletviewer [Link]
 The database server is connected to the JDBC driver,
which is connected to the applet.
 The applet is also connected to a browser, which is
connected to a web server that communicates with
the database.
 Applets are displayed in a window and they
use the AWT to perform input and output
functions.
 To output a string to an applet, use
drawString( ), which is a member of the
Graphics class.
 Typically, it is called from within either
update() or paint( ). It has the following
general form:
void drawString(String message, int x, int y)
The example below shows a simple applet
to change the color of the foreground and
background.
import [Link].*;
import [Link].*;
/* <applet code="Applet_Prog" width=500 height=550> </applet>*/
public class Applet_Prog extends Applet
{
public void paint (Graphics g)
{
setBackground([Link]);
setForeground([Link]);
[Link]("Using Colors in An Applet" , 100,250);
}
}
 The repaint () method causes the AWT runtime
system to execute the update () method of the
Component class which clears the window with the
background color of the applet and then calls the
paint () method.
 For example: Suppose you want to display the current
x and y coordinates of the location where the mouse
button is clicked in the applet window. As the applet
needs to update information displayed in its window
(i.e. redraw the window)
each time the mouse is being clicked so this is
possible with the use of repaint () method. To
sum up, the repaint() method is invoked to
refresh the viewing area i.e. you call it when
you have new things to display.
import [Link].*;
import [Link];
import [Link].*;
/*<applet code="[Link]" width="350" height="150"> </applet>*/
public class RepaintJavaExample extends Applet implements MouseListener
{
private int mouseX, mouseY;
private boolean mouseclicked = false;
public void init()
{
setBackground([Link]);
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
mouseX = [Link]();
mouseY=[Link]();
mouseclicked = true;
repaint();
}
public void mouseEntered(MouseEvent e){};
public void mousePressed(MouseEvent e){};
public void mouseReleased(MouseEvent e){};
public void mouseExited(MouseEvent e){};
public void paint( Graphics g )
{
String str;
[Link]([Link]);
if (mouseclicked)
{
str = "X="+ mouseX + "," + "Y="+ mouseY ;
[Link](str,mouseX,mouseY);
mouseclicked = false;
}
}
}
 The status window is a good place to give the
user feedback about what is occurring in the
applet, suggest options, or possibly report
some types of errors.
 The status window also makes an excellent
debugging aid, because it gives you an easy
way to output information about your applet.
// Using the Status Window.
import [Link].*;
import [Link].*; /*
<applet code="StatusWindow" width=300 height=50> </applet> */
public class StatusWindow extends Applet { public void init() {
setBackground([Link]);
}
// Display msg in applet window.
public void paint(Graphics g) {
[Link]("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}
 Any program that uses GUI (graphical user
interface) such as Java application written for
windows, is event driven.
 Event describes the change in state of any
object. For Example : Pressing a button,
Entering a character in Textbox, Clicking or
Dragging a mouse, etc.
 The [Link] package can be used to
provide various event classes.
Classification of Events
• Foreground Events
• Background Events
1. Foreground Events
 Foreground events are the events that require user
interaction to generate, i.e., foreground events are
generated due to interaction by the user on
components in Graphic User Interface (GUI).
 Interactions are nothing but clicking on a button,
scrolling the scroll bar, cursor moments, etc.
2. Background Events
 Events that don’t require interactions of users
to generate are known as background events.
Examples of these events are operating system
failures/interrupts, operation completion, etc.
 It is a mechanism to control the events and to decide what
should happen after an event occur.
 To handle the events, Java follows the Delegation Event
model.

Delegation Event model


• It has Sources and Listeners.
• Source: Events are generated from the source. There
are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components,
windows, etc., to generate events.
• Listeners: Listeners are used for handling the events
generated from the source. Each of these listeners
represents interfaces that are responsible for handling
events.
 To perform Event Handling, we need to register the
source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to r
.
Event Class Listener Interface Description

An event that indicates that a


component-defined action
ActionEvent ActionListener occurred like a button click or
selecting an item from the
menu-item list.

The adjustment event is


AdjustmentEvent AdjustmentListener emitted by an Adjustable object
like Scrollbar.

An event that indicates that a


component moved, the size
ComponentEvent ComponentListener
changed or changed its
visibility.

When a component is added to


a container (or) removed from
ContainerEvent ContainerListener
it, then this event is generated
by a container object.
These are focus-related events,
FocusEvent FocusListener which include focus, focusin,
focusout, and blur.

An event that indicates whether


ItemEvent ItemListener
an item was selected or not.

An event that occurs due to a


KeyEvent KeyListener sequence of keypresses on the
keyboard.

The events that occur due to the


MouseListener &
MouseEvent user interaction with the mouse
MouseMotionListener
(Pointing Device).
An event that
specifies that the
MouseWheelEvent MouseWheelListener mouse wheel was
rotated in a
component.

An event that occurs


TextEvent TextListener when an object’s
text changes.

An event which
indicates whether a
WindowEvent WindowListener window has
changed its status
or not.
Listener Interface Methods
ActionListener •actionPerformed()

AdjustmentListener •adjustmentValueChanged()

•componentResized()
•componentShown()
ComponentListener
•componentMoved()
•componentHidden()

•componentAdded()
ContainerListener
•componentRemoved()
•focusGained()
FocusListener
•focusLost()

ItemListener •itemStateChanged()

•keyTyped()
KeyListener •keyPressed()
•keyReleased()

•mousePressed()
•mouseClicked()
MouseListener •mouseEntered()
•mouseExited()
•mouseReleased()

•mouseMoved()
MouseMotionListener
•mouseDragged()
MouseWheelListener •mouseWheelMoved()

TextListener •textChanged()

•windowActivated()
•windowDeactivated()
•windowOpened()
WindowListener •windowClosed()
•windowClosing()
•windowIconified()
•windowDeiconified()
 The Java MouseListener is notified whenever you
change the state of mouse. It is notified against
MouseEvent.
 The MouseListener interface is found in [Link]
package. It has five methods.
 Methods of MouseListener interface
1. public abstract void mouseClicked(MouseEvent e)
;
2. public abstract void mouseEntered(MouseEvent e
);
3. public abstract void mouseExited(MouseEvent e);

4. public abstract void mousePressed(MouseEvent e


);
5. public abstract void mouseReleased(MouseEvent
e);
import [Link].*;
import [Link].*;
public class MouseListenerExample extends Frame implements
MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
[Link](20,50,100,20);
add(l);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
 The Java KeyListener is notified whenever
you change the state of key.
 It is notified against KeyEvent.
 The KeyListener interface is found in
[Link] package, and it has three
methods.
Sr. no. Method name Description
1. public abstract void It is invoked when a
keyPressed (KeyEvent key has been pressed.
e);
2. public abstract void It is invoked when a
keyReleased (KeyEvent key has been
e); released.
3. public abstract void It is invoked when a
keyTyped (KeyEvent e); key has been typed.
 In the Java programming language, the adapter
class in Java is the default implementation of
listener interfaces in Java provided via adapter
classes.
 If you inherit the adapter class, you will not
be required to implement all of the listener
interface functions.
 As a result, it saves code.
 Provides a way to use classes in multiple ways.
 Increases the transparency of classes.
 Its provides a way to include related patterns in a class.
 It makes a class highly reusable.
 ContainerAdapter class.
 KeyAdapter class.
 FocusAdapter class.
 WindowAdapter class.
 MouseAdapter class.
 ComponentAdapter class.
 MouseMotionAdapter class.
public class WindowAdapter implements WindowListner
{
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowClosing(WindowEvent e){}
}
 Java inner class or nested class is a class that is
declared inside the class or interface.
 We use inner classes to logically group classes and
interfaces in one place to be more readable and
maintainable.
 Additionally, it can access all the members of the
outer class, including private data members and
methods.
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
 A non-static class that is created inside a class
but outside a method is called member inner
class.
 It is also known as a regular inner class.
 It can be declared with access modifiers like
public, default, private, and protected.
class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
[Link]("data is "+data);
}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
[Link] in=[Link] Inner();
[Link]();
}
}
 data is 30
Unit - V
 Java AWT (Abstract Window Toolkit) is an API to
develop Graphical User Interface (GUI) or windows-
based applications in Java.
 Java AWT components are platform-dependent i.e.
components are displayed according to the view of
operating system
 The [Link] package provides classes for AWT API
such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
 Components
All the elements like the button, text fields, scroll bars,
etc. are called components. In Java AWT, there are
classes for each component as shown in above diagram.
In order to place every component in a particular position
on a screen, we need to add them to a container.
 Container
The Container is a component in AWT that can contain
another components like buttons, textfields, labels etc.
The classes that extends Container class are known as
container such as Frame, Dialog and Panel.
 The AWT defines windows according to a class
hierarchy that adds functionality and specificity with
each level.
 The two most common windows are those derived from
Panel, which is used by applets, and those derived from
Frame, which creates a standard window.
 Much of the functionality of these windows is derived
from their parent classes.
There are four types of containers in Java AWT:
 Window
 Panel
 Frame
 Dialog
Window
 The window is the container that have no borders and
menu bars. You must use frame, dialog or another
window for creating a window.
Panel
 The Panel is the container that doesn't contain title bar,
border or menu bar. It is generic container for holding
the components. It can have other components like
button, text field etc. An instance of Panel class creates
a container, in which we can add components.
Frame
 The Frame is the container that contain title bar and
border and can have menu bars. It can have other
components like button, text field, scrollbar etc. Frame
is most widely used container while developing an
AWT application.
Dialog
 The Dialog control represents a top level window with
a border and a title used to take some form of input
from the user.
// importing Java AWT class
import [Link].*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


[Link](30,100,80,30);
// adding button into frame
add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample1 f = new AWTExample1();

}
//[Link]
import [Link];
import [Link];
public class First extends Applet{

public void paint(Graphics g){


[Link]("welcome to applet",150,150);
}

}
/*
<applet code="[Link]" width="300" height="300">
</applet>
*/
After the applet, the type of window you will most often
create is derived from Frame.

Here are two of Frame’s constructors:

Frame( )
Frame(String title)

 The first form creates a standard window that does not


contain a title. The second form creates a window with the
title specified by title.
 Setting the Window’s Dimensions

void setSize(int newWidth, int newHeight)


The new size of the window is specified by newWidth
and newHeight
 Hiding and Showing a Window

After a frame window has been created, it will not be


visible until you call setVisible( ).
Its signature is shown here:
void setVisible(boolean visibleFlag)
 Setting a Window’s Title

You can change the title in a frame window using


setTitle( ), which has this general form:

void setTitle(String newTitle)

Here, newTitle is the new title for the window.


 Closing a Frame Window
When using a frame window, your program must remove
that window from the screen when it is closed, by calling
setVisible(false).
BorderLayout
The borderlayout arranges the components to fit in the five
regions: east, west, north, south and center.
2 CardLayout
The CardLayout object treats each component
in the container as a card. Only one card is
visible at a time.
3 FlowLayout
The FlowLayout is the default [Link] layouts
the components in a directional flow.

4 GridLayout
The GridLayout manages the components in
form of a rectangular grid.
5 GridBagLayout
This is the most flexible layout manager
[Link] object of GridBagLayout aligns the
component vertically,horizontally or along their
baseline without requiring the components of
same size.
public class BorderDemo1
{
JFrame frame;
BorderDemo1()
{
frame=new JFrame();
JButton box1=new JButton("**NORTH**"); JButton
box2=new JButton("**SOUTH**"); JButton box3=new
JButton("**EAST**");
JButton box4=new JButton("**WEST**");
JButton box5=new JButton("**CENTER**");
[Link](box1,[Link]);
[Link](box2,[Link]);
[Link](box3,[Link]);
[Link](box4,[Link]);
[Link](box5,[Link]);
[Link](400,400); [Link](true);
}
public static void main(String[] args)
{
new BorderDemo1(); }
}
 A label is a user for placing text inside the container.
 A label is used only for outputting text.

Label n=new Label("Name:",[Link]);


 This command generates a button in the User Interface.
 Clicking on the button would move the command to
another page .

Syntax
Button a1=new Button("submit");
Button a2=new Button("cancel");
 There can be a certain question and the checkbox is
used to determine the true or false nature of the
question being asked.
 If the checkbox is ticked then it means that the said
question is true which if it is unchecked it means that
the said question is false.
Checkbox checkbox1 = new Checkbox("Hello World");
 As the name implies the checkbox group is a set of
checkboxes that are being used in the programming
language.
 There are many checkboxes that are being used and
hence the group of checkboxes is known as the
checkbox
CheckboxGroup cb = new CheckboxGroup(); Checkbox
checkBox1 = new Checkbox("Hello", cb, true);
[Link] (100,100, 50,50);
 The List component presents the user with a scrolling
list of text items.

List list=new List(4);


[Link]("Mango");
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
 Choice control is used to show pop up menu of choices.
Selected choice is shown on the top of the menu.

Choice c=new Choice();


[Link](100,100, 75,75);
[Link]("Subject 1");
[Link]("Subject 2");
[Link]("Subject 3");
[Link]("Subject 4");
[Link]("Subject 5");
 The scroll bar like a normal one is used to scroll or
move from a varied range of values. The user selects
one value from those range of values.

Scrollbar s=new Scrollbar();


[Link](100,100, 50,100);
A text field is used for the editing of a particular line of
text which can be used within the programming concept.

TextField na=new TextField(20);


 A text area is used for the editing of multiple lines of
text.
 The only difference between the Text field and Text
area is that Text Field is used for editing a single line of
text within the user interface while a Text Area is used
for editing multiple lines of text.

TextArea area=new TextArea("Welcome to the universe");


[Link](10,30, 300,300);
 The object of MenuItem class adds a simple
labeled menu item on menu.
 The items used in a menu must belong to the
MenuItem or any of its subclass.
 The object of Menu class is a pull down menu
component which is displayed on the menu bar.
import [Link].*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
[Link](i1);
[Link](i2);
[Link](i3);
[Link](i4);
[Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Output:
 Dialog boxes are graphical components that are usually
used to display errors or give some other information to
the user.
 Dialogs are created as part of a frame.
import [Link].*;
import [Link].*;
public class DialogExample
{
private static Dialog d;
DialogExample()
{
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
Button b = new Button ("OK");
[Link] ( new ActionListener() )
{
public void actionPerformed( ActionEvent e )
{
[Link](false);
}
}
[Link]( new Label ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
new DialogExample();
}
}
 FileDialog control represents a dialog window from
which the user can select a file.
 The FileDialog class displays a dialog window from
which the user can select a file.
 Since it is a modal dialog, when the application calls
its show method to display the dialog, it blocks the rest
of the application until the user has chosen a file.
private void showFileDialogDemo()
{
private Label statusLabel;
FileDialog fileDialog = new FileDialog(mainFrame,"Select file");
Button showFileDialogButton = new Button("Open File");
showFileDialogButton. addActionListener(new ActionListener())
{
public void actionPerformed(ActionEvent e)
{
[Link](true);
[Link]("File Selected :" +
[Link]() + [Link]());
}
}
}
 Swing is a Java Foundation Classes JFC]
library and an extension of the Abstract
Window Toolkit [AWT].
 Swing offers much-improved functionality
over AWT, new components, expanded
components features, excellent event handling
with drag and drop support.
No. Java AWT Java Swing
1) AWT components are platform- Java swing components are platform-
dependent. independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable Swing supports pluggable look and feel.
look and feel.
4) AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser etc.
5) AWT doesn't follows MVC(Model Swing follows MVC.
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.

You might also like