Java Programming Lecture Notes for B.Tech
Java Programming Lecture Notes for B.Tech
Lecture Notes
[Link]
(III YEAR – I
SEM) (2022-23)
Prepared by:
Mrs. [Link], Assistant Professor
COURSE OBJECTIVES:
1) To create Java programs that leverage the object-oriented features of the Java language, such
as encapsulation, inheritance and polymorphism;
2) Use data types, arrays and strings;
3) Implement error-handling techniques using exception handling,
4) To know about Applets and Event Handling
5) Create and event-driven GUI using AWT components.
UNIT I:
Java Programming-OOP Concepts, History of Java, Java buzzwords, Data types, Variables,
Constants, Scope and Life time of variables, Operators, Type conversion and casting, Control
Flow Statements, simple java programs, concepts of classes, objects, arrays, strings,
constructors, methods, access control, this keyword, overloading methods and constructors,
garbage collection, recursion.
UNIT II:
Inheritance – Types of Inheritance, super keyword, and preventing inheritance: final classes
and methods.
Polymorphism – Dynamic binding, method overriding, abstract classes and methods.
Interfaces-Interfaces Vs Abstract classes, defining an interface, implement interfaces,
extending interface.
Packages- Defining, creating and accessing a package, importing packages.
UNIT III:
Exception handling - Benefits of exception handling, exception hierarchy, Classification of
exceptions - checked exceptions and unchecked exceptions, usage of try, catch, throw, throws
and finally, built in exceptions.
Multi-threading- Differences between multi-threading and multitasking, thread life cycle,
creating threads, synchronizing threads.
UNIT IV
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets.
Event Handling: Events, Handling mouse and keyboard events.
Files- Streams, Byte streams, Character streams, Text
input/output UNIT V
GUI Programming with Java – AWT class hierarchy, AWT controls - Labels, button, text
field, check box, and graphics. Layout Manager – Layout manager types: border, grid and flow.
Swing – Introduction, limitations of AWT, Swing vs AWT.
TEXT BOOKS:
1) Java- The Complete Reference, 7th edition, Herbert schildt,TMH.
2) Understanding OOP with Java, updated edition, T. Budd, Pearsoneducation.
3) Core Java an integrated approach, dreamtech publication, Dr. [Link].
REFERENCE BOOKS:
1) Java for Programmers, [Link] and [Link], PEA (or) Java: How to
Program,[Link] and [Link], PHI
2) Object Oriented Programming through Java, P. Radha Krishna, Universities Press.
COURSE OUTCOMES:
1) An understanding of the principles and practice of object-oriented programming anddesign
in the construction of robust, maintainable programs which satisfy theirrequirements;
2) A competence to design, write, compile, test and execute straightforward programsusinga
high-level language;
3) An awareness of the need for a professional approach to design and the importance of good
documentation to the finished programs.
4) Be able to make use of members of classes found in the Java API.
5) Demonstrate the ability to employ various types of constructs and a hierarchy of Javaclasses
to provide solution to a given set of requirements.
MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY
DEPARTMENT OF ECE
INDEX
2 Benefits of Inheritance 2
I
Simula is considered as the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as truly object-oriented programming language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing someconcepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because allthe data
members are private here.
Benefits of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilationunits.
Inheritance can also make application code more flexible to change because
classesthat inherit from a common superclass can be used interchangeably. If the
return type of a method issuperclass
Reusability - facility to use public methods of base class without rewriting thesame.
Extensibility - extending the base class logic as per business logic of the derivedclass.
For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
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) Originally designed for small, embedded systems in electronic appliances like set-
topboxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension [Link].
4) After that, it was called Oak and was developed as a part of the Green
project.
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for specific time.
1. Single LineComment
2. Multi LineComment
3. DocumentationComment
Syntax:
Output:
10
Java Multi Line Comment
The multi line comment is used to comment multiple lines of code.
Syntax:
/* Thisis
multi linecomment
*/
Example:
Output:
10
Syntax:
/**
This
is
documentation
comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}
Now, there
javadoc will be HTML files created for your Calculator class in the current directory. Open the HTML
[Link]
files and see the explanation of Calculator class provided through documentation comment.
o Primitive datatypes
o Non-primitive datatypes
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Output:20
There are two types of data types in java: primitive and non-primitive.
Types of Variable
There are three types of variables in java:
o localvariable
o instancevariable
o staticvariable
1) LocalVariable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance variable. Itis not
declared as static.
3) Staticvariable
A variable that is declared as static is called static variable. It cannot be [Link] will have detailed
learning of these variables in next chapters.
Example to understand the types of variables in java
class A{
int data=50;//instance variable
static int m=100;//static
variable void method(){
int n=90;//local variable
}
}//end of class
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.
Syntax
modifierfinal dataType variableName = value; //global constant
Instance variables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have already seen about it earlier.
The lifetime of these variables is the same as the lifetime of the object to which it belongs.
Object once created do not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.
Argument variables
These are the variables that are defined in the header oaf constructor or a method. The scope
of these variables is the method or constructor in which they are defined. The lifetime is
limited to the time for which the method keeps executing. Once the method finishes
execution, these variables aredestroyed.
Local variables
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the methoditself.
One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the block
itself.
o ArithmeticOperator,
o shiftOperator,
o RelationalOperator,
o BitwiseOperator,
o LogicalOperator,
o Ternary Operatorand
o AssignmentOperator.
Operators Hierarchy
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types ofexpressions in
Java:
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are
not compatible with each other.
if(condition) {
// execute this code
}
Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and selectproperties.
Click on the Advanced tab, and then click on the Environment variables button. Look at the variables
listed for all users, and click on the Path variable. Do not delete the contents of this variable! Instead, edit
the contents by moving the cursor to the right end, entering a semicolon (;), and pressing Ctrl-V to paste
the path you copied earlier. Then go ahead and save your changes. (If you have any Cmd windows open,
you will need to close them.)
10. If you're using Windows, go to the Start menu and type "cmd" to run a program
that brings up a command prompt window. If you're using a Mac or Linux machine,
run the Terminal program to bring up a commandprompt.
11. In Windows, type dir at the command prompt to list the contents of the current
directory. On a Mac or Linux machine, type ls to dothis.
cd Desktop
cd ..
Every time you change to a new directory, list the contents of that directory to see where to gonext.
Continue listing and changing directories until you reach the directory that contains your .class files.
13. If you compiled your program using Java 1.6, but plan to run it on a Mac, you'll needto
recompile your code from the command line, bytyping:
14. Now we'll create a single JAR file containing all of the files needed to run yourprogram.
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed
variables.
Creating
Arrays:
You can create an array by using the new operator with the following syntax:
Declaring an array variable, creating an array, and assigning the reference of the array to thevariable can be
combined in one statement, as shown below:
The array elements are accessed through the index. Array indices are 0-based; that is, they startfrom 0 to
dataType[] arrayRefVar = {value0, value1, ..., valuek};
[Link]-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements ofdouble type
and assigns its reference tomyList:
Following picture represents array myList. Here, myList holds ten double values and the indicesare from
double[] myList = new double[10];
0 to 9.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
public class TestArray {
public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements for(double element: myList) {
[Link](element);
}}}
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked atthe time of object
creation.
classBike1{
Bike1(){[Link]("Bike is created");}
public static void main(String args[])
{ Bike1 b=new Bike1();
}}
Output:Bike is created
Output:
111Karan222Aryan
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter [Link] compiler differentiates these constructors bytaking into account the number of
parameters in the list and their type.
Output:
Java
111 CopyConstructor
Karan 0
222 Aryan 25
There is no copy constructor in java. But, we can copy the values of one object to another likecopy
constructor inC++.
There are many ways to copy the values of one object into another in java. They are:
oBy constructor
oBy assigning the values of one object into another
oBy clone() method of Object class
In this example, we are going to copy the values of one object into another using javaconstructor.
classStudent6{intid; Stringname;
Student6(int i,String n){id = i;
name = n;
}
Output:
111Karan 111Karan
Syntax
Here,
public static int methodName(int a, int b) {
// body
public static −modifier
}
int − returntype
a, b − formalparameters
Method definition consists of a method header and a method body. The same is shown in thefollowing syntax −
Syntax
The syntax shown above includes −
modifier returnType nameOfMethod (Parameter List) {
// method body
modifier− It defines the access type of the method and it is optional touse.
}
returnType− Method may return avalue.
method body − The method body defines what the method does with thestatements.
o The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees,college name of studentsetc.
o The static variable gets memory only once in class area at the time of classloading.
[Link]();
[Link]();
}}
Output:111 KaranITS
222 AryanITS
classStudent9{ i
nt rollno;
String name;
staticString college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){rollno =r;
name =n;
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructoror class.
There are 4 types of java access modifiers:
2) default accessmodifier
If you don't use any modifier, it is treated as default bydefault. The default modifier isaccessible only
withinpackage.
Example of default accessmodifier
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside thepackage.
//save by [Link]
package pack;
class A{
voidmsg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
In the above example, the scope of class A and its method msg() is default so it cannot beaccessed from
outside thepackage.
3) protected accessmodifier
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can'tbe
applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only throughinheritance.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");} }
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}}
Output:Hello
4) public accessmodifier
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=newStudent(112,"sumit",6000f);
[Link]();
[Link]();
}}
Output:
111 ankit 5000
112 sumit 6000
Constructor must not have return type. Method must have return type.
The java compiler provides a default Method is not provided by compiler inany case.
constructor if youdon't have any
constructor.
Constructor name must be same as the Method name may or may not be
class name.
JAVA PROGRAMMING Page 30
same as class name.
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter [Link] compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:
JAVAPROGRAMMING Page31
111 Karan 0
222 Aryan 25
If we have to perform only one operation, having same name of the methods increases thereadability of the
program.
In this example, we are creating static methods so that we don't need to create instance for callingmethods.
classAdder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
classTestOverloading1{
public static void main(String[] args){ [Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
Output:
22
Method Overloading: changing data type of arguments
33
In this example, we have created two methods that differs in data type. The first add methodreceives two
integer arguments and second add method receives two double arguments.
JAVA Page
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java thatcalls itself is called
recursive method.
Output:
Java Garbage
Factorial Collection
of 5 is: 120
Garbage Collection is process of reclaiming the runtime unused memory automatically. In otherwords, it
is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it
isperformed automatically. So, java provides better memory management.
gc() method
JAVA Page
The gc() method is used to invoke the garbage collector to perform cleanup processing. Thegc() is found in
System and Runtime classes.
s1=null;
s2=null; [Link]();
}}
Java String
object is garbage collectedobject is garbage collected
string is basically an object that represents sequence of char values. An array of characters workssame as
java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);ssame as:
1. Strings="javatpoint";
2. Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()etc.
3. The [Link] class implements Serializable, Comparable and
CharSequenceinterfaces.
CharSequence Interface
JAVA Page
The CharSequence interface is used to represent sequence of characters. It is implemented by String,
StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3 classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is
created. For mutable string, you can use StringBuffer and StringBuilderclasses.
There are two ways to create String object:
1. By stringliteral
2. By newkeyword
String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1. Strings1="Welcome";
2. String s2="Welcome";//will not create newinstance
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap (non
pool).
JAVA Page
java strings example
Immutable String in Java
JAVA Page
MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY
DEPARTMENT OF ECE
Unit-2
Inheritance in
Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Inheritance represents the IS-A relationship, also known as parent-
childrelationship.
The extends keyword indicates that you are making a new class that derives from an existingclass.
The meaning of "extends" is to increase the functionality.
classEmployee{ flo
at salary=40000;
}
classProgrammer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}}
Programmer salary is:40000.0
JAVA Page
Bonus of programmeris:10000
classAnimal{ voideat(){[Link]("eating...");}
}
classDog extends Animal{
voidbark(){[Link]("barking...");}
}
classTestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output: barking...eating...
File: [Link]
classAnimal{
voideat(){
[Link]("eating...");
}
}
classDog extends Animal{
voidbark(){
[Link]("barking...");
}
}
classBabyDog extends Dog{
voidweep(){
[Link]("weeping...");
}
}
classTestInheritance2{
Output:
weeping...barking... eating...
Hierarchical Inheritance Example
File: [Link]
classAnimal{
voideat(){
[Link]("eating...");
}
}
classDog extends Animal{
voidbark(){
[Link]("barking...");
}
}
classCat extends Animal{
voidmeow(){
[Link]("meowing...");
}
}
classTestInheritance3{
public static void main(String args[])
{ Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
meowing...eating...
JAVA Page
Member access and Inheritance
A subclass includes all of the members of its super class but it cannot access those members ofthe
super class that have been declared as private. Attempt to access a private variable would cause
compilation error as it causes access violation. The variables declared as private, is onlyaccessible by
other members of its own class. Subclass have no access to it.
Whenever you create the instance of subclass, an instance of parent class is created implicitlywhich
is referred by super reference variable.
classAnimal{ Stringcolor="white";
}
classDog extends Animal{Stringcolor="black";
voidprintColor(){ [Link](color);//printscolor of Dogclass
[Link]([Link]);//prints color of Animal class
}
}
classTestSuper1{
public static void main(String args[]){Dog d=new Dog();
JAVA Page
[Link]();
}}
Output:
Final Keyword
bla
in Java
The finalckkeyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only.
The Object class is beneficial if you want to refer any object whose type you don't know. Noticethat parent
class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any typelike
Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't know what object will be returned from thismethod
The Object class provides some common behaviors to all the objects such as object can becompared, object
can be cloned, object can be notified etc.
If subclass (child class) has the same method as declared in the parent class, it is knownas method
overriding in java.
JAVA Page
Usage of Java Method Overriding
o Method overriding is used to provide specific implementation of a method that is
already provided by its superclass.
o Method overriding is used for runtimepolymorphism
Example of method
overriding Class Vehicle{
voidrun(){[Link]("Vehicle is running");}
}
classBike2 extends Vehicle{ voidrun()
{[Link]("Bike is running safely");} public
static void main(String args[]){
Bike2 obj = new Bike2();[Link]();
}
1. classBank{
intgetRateOfInterest(){return 0;}
}
classSBI extends Bank{
intgetRateOfInterest(){return 8;}
}
classICICI extends Bank{
intgetRateOfInterest(){return 7;}
}
classAXIS extends Bank{
intgetRateOfInterest(){return 9;}
}
classTest2{
public static void main(String args[])
{ SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new
AXIS();
[Link]("SBI Rate of Interest: "+[Link]());
[Link]("ICICI Rate of Interest: "+[Link]());
[Link]("AXIS Rate of Interest:
"+[Link]());
}}
Output:
SBI Rate of Interest: 8
JAVA Page
ICICI Rate of Interest: 7AXIS Rate of Interest: 9
abstractmethod
1. abstract void printStatus();//no bodyand abstract
runningsafely..
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methodsin the
java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.
Java Interface also represents IS-A [Link] cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.
o It is used to achieveabstraction.
o By interface, we can support the functionality of multipleinheritance.
o It can be used to achieve loosecoupling.
JAVA Page
Internal addition by compiler
interfacePrintable{
JAVA Page
voidprint();
}
interfaceShowable{ voi
dshow();
}
classA7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
public static void main(String args[]){
A7 obj = new A7();[Link]();
[Link]();
}}
Output:Hello
Welcome
Abstract class Interface
1) Abstract class can have abstract Interface can have only abstract methods. Since
and non-abstractmethods. Java 8, it can have default and static
methodsalso.
2) Abstract class doesn't support Interface supports multiple inheritance.
multipleinheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation ofinterface. abstract class.
5) The abstract keyword is used to Theinterface keyword is used to declare
declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
We use inner classes to logically group classes and interfaces in one place so that it can be morereadable and
maintainable.
JAVA Page
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class includingprivate.
2) Nested classes are used to develop more readable and maintainable code because
it logically group classes and interfaces in one placeonly.
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
There are two types of nested classes non-static and static nested [Link] non-static nestedclasses are also
known as inner classes.
Java Package
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 [Link] are many built-in packages
such as java, lang, awt, javax, swing, net, io, util, sql [Link] of JavaPackage
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
packagemypack;
public class
Simple{
public static void main(String args[]){
[Link]("Welcome to
package");
}}
JAVA Page
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:javac -d directory
javafilename
How to run java package program
JAVA Page
MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY
DEPARTMENT OF ECE
UNIT-3
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can bemaintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which isthrown at
runtime.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered asunchecked
exception. The sun microsystem says there are three types of exceptions:
1. CheckedException
2. UncheckedException
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions [Link], SQLException etc. Checked exceptions are
checked atcompile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checkedatruntime.
JAVA Page
Hierarchy of Java Exception classes
JAVA Page
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
1. try{
2. //code that may throwexception
3. }catch(Exception_class_Nameref){}Syntax of try-finallyblock
1. try{
2. //code that may throwexception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only. You can use
multiple catch block with a single try.
Problem without exception handling
As displayed in the above example, rest of the code is not executed (in such case, rest of the code...
statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not beexecuted.
JAVA Page
public static void main(String args[]){
try{ intdata=
50/0;
}catch(ArithmeticException e){[Link](e);}[Link]("rest of the code...");
}}
1. Output:
Now, as displayed
Exception in the
in thread above
main example, rest of the code is by
[Link]:/ executed
zeroresti.e.
of rest of the code... statement is
the code...
printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java multicatch block.
public classTestMultipleCatchBlock{
public static void main(Stringargs[])
{ try{
inta[]=new
int[5]; a[5]=30/0;
}
catch(ArithmeticException e){[Link]("task1 iscompleted");}
catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed"); }
catch(Exception e){[Link]("common taskcompleted");
}
[Link]("rest of the code...");13. } }
class Excep6{
public static void main(String args[]){
try{try{
[Link]("going to divide");
intb =39/0;
}catch(ArithmeticException e){[Link](e);}
JAVA Page
try{
int a[]=new
int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{ [Link](e);
}
[Link]("other statement);
}catch(Exception e){
[Link]("handeled");
}
[Link]("normal flow..");
} }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or [Link] finally block follows try or
catch block.
Case 1
Let's see the java finally example where exception doesn't [Link] TestFinallyBlock{
public static void main(String args[])
{ try{ intdata=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);} finally{[Link]("finally block is always
executed");}[Link]("rest of the code...");
}
}
Output:5
Javafinally
throwblock
keyword
is always executedrest of the code...
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception. We will see custom exceptions later.
1. throwexception;
JAVA Page
Java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. Ifthe age is
less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
Output:
The Java throws keyword is used to declare an exception. It gives an information to the programmer that
there may occur an exception so it is better for the programmer to provide the exception handling code so
that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up before
the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be propagated by
throws keyword.
import [Link];
class Testthrows1{
void m() throwsIOException{
throw new IOException("device error");//checked exception
JAVA Page
}
Void n() throws
IOException{m();
}
voidp(){
try{ n()
;
}catch(Exception e){[Link]("exception handled");}
}
public static void main(String args[])
{ Testthrows1 obj=new
Testthrows1(); obj.p();
[Link]("normal flow..."); } }Output:
Java Custom
exception Exception flow...
handlednormal
If you are creating your own Exception that is known as custom exception or user-defined exception. Java
custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and [Link]'s see a simple example
of java custom exception.
class InvalidAgeException extends Exception{InvalidAgeException(String s){super(s);
}}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
try{ validate(13);
}catch(Exception m){[Link]("Exception occured: "+m);}
JAVA Page
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
But we use multithreading than multiprocessing because threads share a common memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less time
than process.
3) Threads are independent so it doesn't affect other threads if exception occur in a singlethread.
states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
JAVA Page
How to create thread
There are two ways to create a thread:
1. By extending Threadclass
2. By implementing Runnableinterface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
JAVA Page
Commonly used methods of Thread class:
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to beexecuted by a
thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for athread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs followingtasks:
oA new thread starts(with new callstack).
oThe thread moves from New state to the Runnable state.
oWhen the thread gets a chance to execute, its target run() method will run.
JAVA Page
Java Thread Example by extending Thread class
Example of priority of a
Thread: class TestMultiPriority1
extends Thread{public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority());
}
public static void main(String args[]){
JAVA Page
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}}
Output:running thread name is:Thread-0running thread priority is:10
running thread name is:Thread-1running thread iority is:1
pr
chronized method
Java syn
If you declare any method as synchronized, it is known as synchronized [Link] method is used
to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that objectand releases it
when the thread completes its task.
MALLA REDDY COLLEGE OF ENGINEERING &TECHNOLOGY
DEPARTMENT OF ECE
UNIT 4
APPLETS:
An applet is a program that comes from server into a client and gets executed at client side anddisplaysthe
result.
An applet represents byte code embedded in a html page. (Applet = bytecode + html) and runwith thehelp
of Java enabled browsers such as Internet Explorer.
An applet is a Java program that runs in a browser. Unlike Java applications applets do not havea main()
method.
To create applet we can use [Link] or [Link] class. All applets inherit the super
class ‘Applet’. An Applet class contains several methods that help to control the execution of an applet.
Advantages:
1. Applets provide dynamic nature for a webpage.
2. Applets are used in developing games and animations.
3. Writing and displaying (browser) graphics and animations is easier thanapplications.
4. In GUI development, constructor, size of frame, window closing code etc. are notrequired
JAVA Page
client as well as server. problems.
Working Applications are created by Applets are created by
writing public static void extending the
main(String[] s) method [Link]
class
Client side / The applications don't Applets are designed for the
Server side have such type of client site programming purpose
criteria
Methods Application has a single Applet application has 5
start point which is main methods which will be
method automatically invoked.
Example public class MyClass import [Link].*;
{ public static void import [Link].*;
main(String args[]){} public class Myclass
} extends Applet{
public void init(){}
public void start(){}
public void stop(){}
public void destroy()
{}
public void paint(Graphics g) {}
}
Initialization:
public void init(): This method is used for initializing variables, parameters to create components. This
method is executed only once at the time of applet loaded into memory.
public void init(){
//initialization
}
Runnning:
public void start (): After init() method is executed, the start method is executed automatically. Start
method is executed as long as applet gains focus. In this method code related to opening files and
JAVA Page
connecting to database and retrieving the data and processingthe data is written.
JAVA Page
Idle / Runnable:
public void stop (): This method is executed when the applet loses focus. Code related to closing the files
and database, stopping threads and performing clean up operations are written in this stop method.
Dead/Destroyed:
public void destroy (): This method is executed only once when the applet is terminatedfrom the memory.
Executing above methods in that sequence is c alled applet life cycle. We can also use public void paint
(Graphics g) in applets.
//An Applet skeleton.
import [Link].*;
import [Link].*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
public voidinit() {
//initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
//start or resume execution
}
/* Called when the applet is stopped. */
public void stop() {
//suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() {
//perform shutdown activities
}
//Called when an applet's window must berestored.
public void paint(Graphics g) {
//redisplay contents of window
}
}
After writing an applet, an applet is compiled in the same way as Java application but running ofan applet is
different.
There are two ways to run an applet.
Executing an applet within a Java compatible web browser.
Executing an applet using ‘appletviewer’. This executes the applet in a window.
To execute an applet using web browser, we must write a small HTML file which contains the appropriate
„APPLET‟ tag. <APPLET> tag is useful to embed an applet into an HTML page. It has the following form:
TYPES OF APPLETS
Applets are of two types:
// Local Applets
// Remote Applets
JAVA PROGRAMMING Page 64
Local Applets: An applet developed locally and stored in a local system is called local applets.
So, local system does not require internet. We can write our own applets and embed them into
the web pages.
Remote Applets: The applet that is downloaded from a remote computer system and embed
applet into a web page. The internet should be present in the system to download the applet and
run it. To download the applet we must know the applet address on web known as Uniform
Resource Locator(URL) and must be specified in the applets HTML document as the value of
CODEBASE.
Page 65
String str;
int a,b,result;
public void init()
{
str=getParameter("a");
a=[Link](str);
str=getParameter("b");
b=[Link](str);
result=a+b;
str=[Link](result);
}
public void paint(Graphics g)
{
[Link](" Result of Addition is : "+str,0,15);
}
}
Ex3: [Link]
import [Link].*;
import [Link].*;
/*<Applet code="hai" height="250" 0">
width="25
<PARAM name="Message" value="Hai friend how are you ..?"></APPLET>
*/
class hai extends Applet
{
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
The advantage of this design is that the application logic that processes events is cleanly separated from the user
interface logic that generates those events. A user interface element is able to "delegate" the processing of an
event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an event notification. This
provides an important benefit: notifications are sent only to listeners that want to receive them.
EVENTS
In the delegation model, an event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a graphical user interface. Some of the activities that
cause events to be generated are pressing a button, enteringa character via the keyboard, selecting an item in a
list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value, software or hardware
failure occurs, or an operation is completed.
EVENT SOURCES
A source is an object that generates an event. This occurs when the internal state of that object changes in some
way. Sources may generate more than one type of event. A source must register listeners in order for the
listeners to receive notifications about a specific type of event. Each type of event has its own registration
method.
Here is the general form:
public void add Type Listener( Type Listener el )
EVENT LISTENERS
A listener is an object that is notified when an event occurs. It has two major requirements. First,it must have
been registered with one or more sources to receive notifications about specific types of events. Second, it must
implement methods to receive and process these notifications. The methods that receive and process events are
defined in a set of interfaces found in [Link].
For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse
is dragged or moved.
EVENT CLASSES
The classes that represent events are at the core of Java's event handling mechanism. At the root of the Java
event class hierarchy is EventObject, which is in [Link]. It is the superclass for all events.
It’s one constructor is shown here:
EventObject(Object src )
EventObject contains two methods: getSource( ) and toString( ) .
The getSource( ) method returns the source of the event. Ex: Object getSource( )
toString( ) returns the string equivalent of the event.
The package [Link] defines several types of events that are generated by various userinterface elements.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized or becomes visible.
ContainerEvent Generated when a component is added to or removed from a container.
FocusEvent Generated when a component gains or loses keyboard focus.
InputEvent Abstract super class for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; so occurs when a choice
selection is made or a checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved. (Added by Java 2, version 1.4)
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
ActionEvent has these three constructors: ActionEvent(Object src , int type , String cmd )
ActionEvent(Object src , int type , String cmd , int modifiers )
ActionEvent(Object src , int type, String cmd, long when , int modifiers )
The ComponentEvent Class
// ComponentEvent is generated when the size, position, or visibility of a component is changed. There are four
types of component events. The constants and their meanings areshown here:
COMPONENT_HIDDEN The component was hidden. COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized. COMPONENT_SHOWN The component became
visible.
The ContainerEvent Class
//ContainerEvent is generated when a component is added to or removed from a container.
There are two types of container events.
COMPONENT_ADDED and
COMPONENT_REMOVED The KeyEvent Class
//KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified
by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED .
The first two events are generated when any key is pressed or released. The last event occurs only when a
character is generated.
The MouseEvent Class
There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a
component. MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved (Java 2,
v1.4).
The WindowEvent Class
There are ten types of window events. The WindowEvent class defines integer constants thatcan be used to
identify them. The constants and their meanings are shown here:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be
closed. WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input focus.
WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input
focus. WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.
EVENT LISTENER INTERFACES
When an event occurs, the event source invokes the appropriate method defined by the listenerand provides an
event object as its argument
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden,
moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener Defines two methods to recognize when a component gains or losses
keyboard focus.
ItemListener Defines one method to recognize when the state of an item changes.
KeyListener Defines three methods to recognize when a key is pressed, released,
or typed.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
TextListener Defines one method to recognize when a text value changes.
WindowListener Defines seven methods to recognize when a window is
activated, closed, deactivated, deiconified, iconified, opened, or
quit.
The delegation event model has two parts: sources and listeners. Listeners are created by
implementing one or more of the interfaces defined by the [Link] package.
The ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action eventoccurs.
Its general form is shown here: void actionPerformed(ActionEvent ae )
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an itemchanges.
Its general form is shown here: void itemStateChanged(ItemEvent ie )
The KeyListener Interface
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invokedwhen a key
is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered. For
example, if a user presses and releases the key, three events are generated in A sequence: key pressed, typed, and released.
The general forms of these methods are shown here:
void keyPressed(KeyEvent ke )
void keyReleased(KeyEvent ke )
void keyTyped(KeyEvent ke )
The MouseListener Interface
This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is
invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves,
mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is
pressed and released, respectively.
The general forms of these methods are shown here:
void mouseClicked(MouseEvent me )
void mouseEntered(MouseEvent me )
void mouseExited(MouseEvent me )
void mousePressed(MouseEvent me )
void mouseReleased(MouseEvent me
)
Java provides strong but flexible support for I/O related to files and networks.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream.
Example
import [Link].*;
public class CopyFile {
public static void main(String args[]) throws IOException
{ FileInputStream in = null;
FileOutputStream out =
null; try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null)
{ [Link]();
}
}
}}
Now let's have a file [Link] with the following content:
This is test for copy file.
$javac [Link]
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major
difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
Example
import [Link].*;
public class CopyFile {
public static void main(String args[]) throws IOException
{ FileReader in = null;
FileWriter out =
null; try {
in = new FileReader("[Link]");
out = new
FileWriter("[Link]"); int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null)
{ [Link]();
}
}
}
}
First we should read data from the keyword. It uses DataInputStream class for reading data from the
keyboard is as:
DataInputStream dis=new DataInputStream([Link]);
FileOutputStream used to send data to the file and attaching the file to FileOutputStream. i.e.,
FileOutputStream fout=new FileOutputStream(“File_name”);
The next step is to read data from DataInputStream and write it into FileOutputStream. It means read data
from dis object and write it into fout object. i.e.,
ch=(char)[Link](); //read one character into
ch [Link](ch); //write ch into file.
Finally closing the file using: [Link]();
Creating a Text file:
Example: Write a program to read data from the keyboard and write it to [Link] file.
import [Link].*;
class Test{
public static void main(String args[])
{
DataInputStream dis=new DataInputStream([Link]);
FileOutputstream fout=new
FileOutputStream("[Link]");
[Link]("Entertext @ at the end:”);
char ch; while((ch=(char)[Link]())!
=‟@‟) [Link](ch);[Link]();
}
}
Output: javac [Link]
Java Test
Java FileInputStream class
It is useful to read data from a file in the form of sequence of bytes. It is possible to read datafrom a
text file using FileInputStream. i.e.,
FileInputStream fin= new FileInputStream(“[Link]”);
To read data fromthe file is,
ch=[Link]();
When there is no more data available to read then it returns -1.
The Output Stream is used to send data to the monitor. i.e., PrintStream, for displaying the data we can
use [Link].
[Link](ch);
Example: Write a program to read data from [Link] using FileInputStream and
display it on monitor.
import [Link].*;
class ReadFile
{
public static void main(String args[])
{
FileInputStream fin=new FileInputStream("[Link]");
[Link](“File Contents:”);
int ch;
while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
[Link]();
}
}
Output: javac [Link]
java ReadFile
UNIT V:
GUI Programming with Java – AWT class hierarchy, component, container,panel,window, frame,
graphics.
AWT controls: Labels, button, text field, check box, check box groups, choices, lists,scrollbars, and graphics.
Layout Manager – Layout manager types: border, grid and flow.
Swing – Introduction, limitations of AWT, Swing vs AWT.
Container
The Container is a component in AWT that can contain other components like buttons, textfields,labels etc.
The classes that extend Container class are known as container such as Frame, Dialogand Panel.
Window
The window is the container that has 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 and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size(width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.
A layout manager arranges the child components of a container. It positions and sets the size of components
within the container's display area according to a particular layout scheme.
The layout manager's job is to fit the components into the available area, while maintaining the proper spatial
relationships between the components. AWT comes with a few standard layout managers that will collectively
handle most situations; you can make your own layout managers if you have special requirements.
LayoutManager at work
Every container has a default layout manager; therefore, when you make a new container, it comes with
a LayoutManager object of the appropriate type. You can install a new layout manager at any time with
the setLayout() method. Below, we set the layout manager of a container to a BorderLayout:
setLayout ( new BorderLayout( ) );
Every component determines three important pieces of information used by the layout manager in placing
and sizing it: a minimum size, a maximum size, and a preferred size.
These are reported by the getMinimumSize(), getMaximumSize(), and getPreferredSize(), methods of
Component, respectively.
When a layout manager is called to arrange its components, it is working within a fixed area. It usually
begins by looking at its container's dimensions, and the preferred or minimum sizes of the child
components.
Layout manager
types Flow Layout
FlowLayout is a simple layout manager that tries to arrange components with their preferred sizes,
from left to right and top to bottom in the display. A FlowLayout can have a specified justification of
LEFT, CENTER, or RIGHT, and a fixed horizontal and vertical padding.
By default, a flow layout uses CENTER justification, meaning that all components are centered within the
area allotted to them. FlowLayout is the default for Panel components like Applet.
The following applet adds five buttons to the default FlowLayout.
import [Link].*;
/*
<applet code="Flow" width="500" height="500">
</applet>
*/
public class Flow extends [Link]
{
public void init()
{
//Default for Applet is
FlowLayout add( new
Button("One") );
add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}
If the applet is small enough, some of the buttons spill over to a second or third row.
Grid Layout
GridLayout arranges components into regularly spaced rows and columns. The components are
arbitrarily resized to fit in the resulting areas; their minimum and preferred sizes are consequently ignored.
GridLayout is most useful for arranging very regular, identically sized objects and for allocating space
for Panels to hold other layouts in each region of the container.
GridLayout takes the number of rows and columns in its constructor. If you subsequently give it too
many objects to manage, it adds extra columns to make the objects fit. You can also set the number of
rows or columns to zero, which means that you don't care how many elements the layout manager packs
in that dimension.
For example, GridLayout(2,0) requests a layout with two rows and an unlimited number of
columns; if you put ten components into this layout, you'll get two rows of five columns each. The
following applet sets a GridLayout with three rows and two columns as its layout manager;
import [Link].*;
/*
<applet code="Grid" width="500"height="500"> </applet>
*/
public class Grid extends [Link]
{
public void init()
{
setLayout( new GridLayout( 3, 2 ));
add( new Button("One") );
add( new Button("Two") ); add( new Button("Three") );add( new Button("Four") );
add( new Button("Five") );
}
}
The five buttons are laid out, in order, from left to right, top to bottom, with one empty spot.
Border Layout
BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical locations:
"North," "South," "East," "West," and "Center," possibly with some padding between.
BorderLayout is the default layout for Window and Frame objects. Because each component is
associated with a direction, BorderLayout can manage at most five components; it squashes or stretches
those components to fit its constraints.
When we add a component to a border layout, we need to specify both the component and the position at
which to add it. To do so, we use an overloaded version of the add() method that takes an additional
argument as a constraint.
The following applet sets a BorderLayout layout and adds our five buttons again, named for their locations;
import [Link].*;
/*
<applet code="Border" width="500" height="500">
</applet>
*/
public class Border extends [Link]
{
public void init()
{
setLayout( new [Link]()
); add( new Button("North"), "North" );
add(
new Button("East"), "East" );
add( new Button("South"), "South" );
add( new Button("West"), "West" ); add( new Button("Center"), "Center" );
}
}
Demonstrate Buttons
import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="ButtonDemo" width=250 height=150>
</applet> */
Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small box that can either
contain a check mark or not. There is a label associated with each check box that describes what option the
box represents. You change the state of a check box by clicking on it. Check boxes can be used individually or
as part of a group.
}
}
TextArea:
Sometimes a single line of text input is not enough for a given task. To handle thesesituations,
the AWT includes a simple multiline editor called TextArea .
DemonstrateT extArea
import [Link].*;
[Link].*;
/*
<applet code="TextAreaDemo" width=300height=250> </applet>
*/
public class TextAreaDemo extends Applet
{
public void init()
{
String val = "There are two ways of constructing " + "a software design.\n" + "One way is to make it so simple\
n" + "that there are obviously no deficiencies.\n" + "And the other way is to make it so complicated\n"
+ "that there are no obvious deficiencies.\n\n" + " -C.A.R. Hoare\n\n"
+ "There's an old story about the person who wished\n" + "his computer were as easy to use as his
telephone.\n" + "That wish has come true,\n" + "since I no longer know how to use my telephone.\n\n" + " -
Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10,
30); add(text);
}
}
CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one and only one check box in the
group can be checked at any one time. These check boxes are often called radio buttons. A Radio button
represents a round shaped button such that only one can be selected from a panel. Radio button can be created
using CheckboxGroup class and Checkbox classes.
· To create a radio button:
Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choiceobject, which
shows only the single selected item in the menu, a List object can be constructed to show any number of
choices in the visible window. It can also be created to allow multiple selections.
List provides these constructors:
List( )
List(int numRows )
List(int numRows , boolean multipleSelect )
A List box is similar to a choice box, it allows the user to select multiple items.
· To create a list
box: List lst = new List();
(or)
List lst = new List (3, true);
This list box initially displays 3 items. The next parameter true represents that the user can select more than
one item from the available items. If it is false, then the user can select onlyone item.
= To add items to the list box: [Link]("text");
= To get the selected items: String x[] = [Link]();
= To get the selected indexes: int x[] = [Link] ();
//Demonstrate Lists.
import [Link].*;
[Link].*;
import [Link].*; /*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener
{
List os, browser; String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);
//add items to os list
[Link]("Windows 98/XP");
[Link]("Windows
NT/2000");
[Link]("Solaris");
[Link]("MacOS");
// add items to browser list
[Link]("Netscape 3.x");
[Link]("Netscape 4.x");
[Link]("Netscape 5.x");
[Link]("Netscape 6.x");
[Link]("Internet Explorer4.0");
[Link]("InternetExplorer 5.0");
[Link]("Internet Explorer6.0");
[Link]("Lynx 2.4");
[Link](1);
// add lists to
window add(os);
add(browser);
//register to receive action events
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
//Display current selections
public void paint(Graphics g)
{
int idx[];
msg = "Current OS: ";
idx = [Link]();
for(int i=0; i<[Link]; i++)
msg += [Link](idx[i]) + "
"; [Link](msg, 6, 120);
msg = "Current Browser: ";
msg += [Link]();
[Link](msg, 6, 140);
}
}
Scroll Bars
Scroll bars are used to select continuous values between a specified minimum and [Link] bars may
be oriented horizontally or vertically. Scrollbar class is useful to create scrollbars that can be attached to a frame
or text area. Scrollbars can be arranged vertically or horizontally.
To create a scrollbar :
Scrollbar sb = new Scrollbar (alignment, start, step, min, max);
alignment: [Link], [Link]
start: starting value (e.g. 0)
step: step value (e.g. 30) // represents scrollbar lengthmin: minimum value (e.g. 0)
max: maximum value (e.g. 300)
· To know the location of a scrollbar: int n = [Link] ();
· To update scrollbar position to a new position: [Link] (int position);
· To get the maximum value of the scrollbar: int x = [Link] ();
· To get the minimum value of the scrollbar: int x = [Link] ();
· To get the alignment ofthe scrollbar: int x = getOrientation ();
This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL.
// Demonstrate scroll bars.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="SBDemo" width=300 height=200>
</applet>
*/
public class SBDemo extends Applet implements AdjustmentListener, MouseMotionListener
{
String msg = ""; Scrollbar vertSB, horzSB;
public void init() {
int width = [Link](getParameter("width"));
intheight = [Link](getParameter("height"));
vertSB = new Scrollbar([Link], 0, 1, 0, height);
horzSB = new Scrollbar([Link], 0, 1, 0,
width); add(vertSB);
add(horzSB);
// register to receive adjustment events
[Link](this);
[Link](this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{ repaint();
}
// Update scroll bars to reflect mouse
dragging. public void
mouseDragged(MouseEvent me) {
int x = [Link]();
int y = [Link]();
[Link](y);
[Link](x);
repaint();
}
//Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me)
{
}
//Display current value of scroll
bars. public void paint(Graphics g)
{
msg = "Vertical: " + [Link]();
msg += ", Horizontal: " + [Link]();
[Link](msg, 6, 160);
// show current mouse drag position
[Link]("*", [Link](),[Link]());
}
}
Graphics
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative toa window.
Graphics class and is obtained in two ways:
It is passed to an applet when one of its various methods, such as paint( ) or update( ),is called.
It is returned by the getGraphics( ) method of Component.
Drawing Lines
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX,startY and endsat endX,endY.
The following applet draws several lines:
//Draw lines
[Link].*;
import [Link].*;
/*
<applet code="Lines" width=300height=200> </applet>
*/
public class Lines extends Applet
{ public void paint(Graphics g) {[Link](0, 0, 100, 100);
[Link](0, 100, 100, 0);
[Link](40, 25, 250, 180);
[Link](75, 90, 400, 400);
[Link](20, 150, 400, 40);
[Link](5, 290, 80, 19);
}
}
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, [Link] are shown
here:
void drawRect(int top, int left, int width, int
height) void fillRect(int top, int left, int width, int
height)
The upper-left corner of the rectangle is at top, left. The dimensions of the rectangleare specified by width and
height.
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown here:
void drawRoundRect(int top, int left, int width, int height,int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
// Draw rectangles
import [Link].*;
import [Link].*;
/*
<applet code="Rectangles" width=300height=200> </applet>
*/
public class Rectangles extends Applet
{ public void paint(Graphics g) {
[Link](10, 10, 60, 50);
[Link](100,10, 60, 50);
[Link](190, 10,60, 50, 15, 15);
[Link](70, 90,140, 100, 30, 40);
}}
Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon(), shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygons endpoints are specified by the coordinate pairs contained within the x and y arrays.
The number of points defined by x and y is specified by numPoints.
There are alternative forms of these methods in which the polygon is specified by a Polygon object.
The following applet draws an hour glass shape:
// Draw Polygon
import [Link].*;
import [Link].*;
/*
<applet code="HourGlass"width=230 height=210>
</applet>
*/
public class HourGlass extends Applet
{ public void paint(Graphics g) {
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
[Link](xpoints, ypoints, num);
}}
SWINGS
Swing is a set of classes that provides more powerful and flexible components than are possible with the
AWT. Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) that is
used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit)
API and entirely written in java.
In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies several
exciting additions, including tabbed panes, scroll panes, trees, and tables. Even familiar components such
as buttons have more capabilities in Swing. For example, a button may have both an image and a text
string associated with it. Also, the image can be changed as the state of the button changes.
Unlike AWT components, Swing components are not implemented by platform specific code. Instead,
they are written entirely in Java and, therefore, are platform-independent. The term lightweight is used to
describe such elements.
The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
AWT Swing
AWT components are called Swings are called light weight component
Heavyweight component. because swing components sits on the top
of AWT components and do the work.
AWT components are platform dependent. Swing components are made in purely java
and they are platform independent.
AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has
very much richer functionality.
AWT stands for Abstract windows toolkit. Swing is also called as JFC’s (Java
Foundation classes).
This feature is not supported in AWT. We can have different look and feel in Swing.
Using AWT, you have to implement a lot of Swing has them built in.
things yourself.
This feature is not available in AWT. Swing has many advanced features like JTabel, Jtabbed pane
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet implements ActionListener {
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Add buttons to content pane
Limitations of AWT:
The AWT defines a basic set of controls, windows, and dialog boxes that support a usable,
but limited graphical interface.
One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or peers. This means
that the look and feel of a component is defined by the platform, not by java.
Because the AWT components use native code resources, they are referred to as heavy
weight.
The use of native peers led to several problems.
First, because of variations between operating systems, a component might look, or even
act, differently on different platforms. This variability threatened java’s philosophy: write
once, run anywhere.
Second, the look and feel of each component was fixed and could not be changed.
Third, the use of heavyweight components caused some frustrating restrictions.
Due to these limitations Swing came and was integrated to java. Swing is built on the AWT. Two key
Swing features are: Swing components are light weight, Swing supports a pluggable look and feel.
JAVA PROGRAMMING Page