Java Programming-18
Java Programming-18
I SEM (R15)
UNIT I : Object oriented thinking :- Need for OOP paradigm, A way of viewing world –
Agents, responsibility, messages, methods, classes and instances, class hierarchies (Inheritance),
method binding, overriding and exceptions, summary of OOP concepts.
Java Basics :- History of Java, Java buzzwords, data types, variables, constants, scope and life
time of variables, operators, expressions, control statements, type conversion and casting, simple
java programs, concepts of classes, objects, arrays, strings, constructors, methods, access control,
this keyword, garbage collection, overloading methods and constructors, parameter passing,
BufferedReader class, Scanner class, StringTokenizer class, inner class.
• A file in an object-oriented paradigm can be packed with all the procedures called methods in
the object-oriented paradigm—to be performed by the file: printing, copying, deleting and so on.
The program in this paradigm just sends the corresponding request to the object.
• Java provides automatic garbage collection, relieving the programmer of the need to ensure that
unreferenced memory is regularly deallocated.
Responsibility
• In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a
source of command objects and a series of processing objects.
• Each processing object contains logic that defines the types of command objects that it can handle;
the rest are passed to the next processing object in the chain. A mechanism also exists for adding
new processing objects to the end of this chain.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
• Primary motivation is the need for a platform-independent (that is, architecture- neutral)
language that could be used to create software to be embedded in various consumer electronic
devices, such as microwave ovens and remote controls.
• Objects with clear responsibilities.
• Each class should have a clear responsibility.
• If you can't state the purpose of a class in a single, clear sentence, then perhaps your class
structure needs some thought.
• In object-oriented programming, the single responsibility principle states that every class
should have a single responsibility, and that responsibility should be entirely encapsulated by the
class. All its services should be narrowly aligned with that responsibility.
Messages
• Message implements the Part interface. Message contains a set of attributes and a "content".
• Message objects are obtained either from a Folder or by constructing a new Message object of
the appropriate subclass. Messages that have been received are normally retrieved from a folder
named "INBOX".
• A Message object obtained from a folder is just a lightweight reference to the actual message.
The Message is 'lazily' filled up (on demand) when each item is requested from the message.
• Note that certain folder implementations may return Message objects that are pre-filled with
certain user-specified items. To send a message, an appropriate subclass of Message (e.g., Mime
Message) is instantiated, the attributes and content are filled in, and the message is sent using the
Transport. Send method.
• We all like to use programs that let us know what's going on. Programs that keep us informed
often do so by displaying status and error messages.
• These messages need to be translated so they can be understood by end users around the world.
• The Section discusses translatable text messages. Usually, you're done after you move a
message String into a Resource Bundle.
• If you've embedded variable data in a message, you'll have to take some extra steps to prepare
it for translation.
Methods
• The only required elements of a method declaration are the method's return type, name, a
pair of parentheses, (), and a body between braces, {}.
• Two of the components of a method declaration comprise the method signature - the method's
name and the parameter types.
• More generally, method declarations have six components, in order:
• Modifiers - such as public, private, and others you will learn about later.
The return type - the data type of the value returned by the method, but void method does not
return a value to calling method.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
• The method name - the rules for field names apply to method names as well, but the
convention is a little different.
• The parameter list in parenthesis - a comma-delimited list of input parameters, preceded by
their data types, enclosed by parentheses, (). If there are no parameters, you must use empty
parentheses(). Ex: int add(int a,int b) { } or int add() { }
• The method body, enclosed between braces - the method's code, including the declaration of
local variables, goes here. { //body of amethod }
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names.
By convention, method names should be a verb in lowercase or a multi-word name that begins
with a verb in lowercase, followed by adjectives, nouns, etc. In multiword names, the first letter
of each of the second and following words should be capitalized. Here are some examples:
run
runFast
getBackground
getFinalData
Typically, a method has a unique name within its class. However, a method might have the same
name as other methods due to method overloading.
Overloading Methods
• The Java programming language supports overloading methods, and Java can distinguish
between methods with different method signatures. This means that methods within a class can
have the same name if they have different parameter lists (there are some qualifications to this
that will be discussed in the lesson titled "Interfaces and Inheritance").
• In the Java programming language, you can use the same name for all the drawing methods but
pass a different argument list to each method. Thus, the data drawing class might declare four
methods named draw, each of which has a different parameter list.
• Overloaded methods are differentiated by the number and the type of the arguments passed into
the method.
• You cannot declare more than one method with the same name and the same number and type
of arguments, because the compiler cannot tell them apart.
• The compiler does not consider return type when differentiating methods, so you cannot
declare two methods with the same signature even if they have a different return type.
• Overloaded methods should be used sparingly, as they can make code much less readable.
Classes
• In object-oriented terms, we say that your bicycle is an instance of the class of objects known
as bicycles. A class is the blueprint from which individual objects are created.
• Java classes contain fields and methods. A field is like a C++ data member, and a method is
like a C++ member function. In Java, each class will be in its own .java file. Each field and
method has an access level:
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
For example, methods in the java.lang.Math package are class methods. You cannot call
nonstatic methods from inside a static method. Bundling code into individual software objects
provides a number of benefits, including:
• Modularity: The source code for an object can be written and maintained independently of the
source code for other objects. Once created, an object can be easily passed around inside the
system.
• Information-hiding: By interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world.
• Code re-use: If an object already exists (perhaps written by another software developer), you
can use that object in your program. This allows specialists to implement/test/debug complex,
task-specific objects, which you can then trust to run in your own code.
• Pluggability and debugging ease: If a particular object turns out to be problematic, you can
simply remove it from your application and plug in a different object as its replacement. This is
analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not
the entire machine.
An instance or an object for a class is created in the following way
<class name> <object name>=new <constructor>();
Encapsulation:
• Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse.
• One way to think about encapsulation is as a protective wrapper that prevents the code and data
from being arbitrarily accessed by other code defined outside the wrapper.
• Access to the code and data inside the wrapper is tightly controlled through a well-defined
interface.
• To relate this to the real world, consider the automatic transmission on an automobile.
• It encapsulates hundreds of bits of information about your engine, such as how much we are
accelerating, the pitch of the surface we are on, and the position of the shift.
• The power of encapsulated code is that everyone knows how to access it and thus can use it
regardless of the implementation details—and without fear of unexpected side effects.
Polymorphism:
Polymorphism (from the Greek, meaning ―many forms‖) is a feature that allows one interface to
be used for a general class of actions (One in many forms).
• The specific action is determined by the exact nature of the situation. Consider a stack (which
is a last-in, first-out list). We might have a program that requires three types of stacks. One stack
is used for integer values, one for floating-point values, and one for characters. The algorithm
that implements each stack is the same, even though the data being stored differs.
• In Java we can specify a general set of stack routines that all share the same names.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
More generally, the concept of polymorphism is often expressed by the phrase - one interface,
multiple methods. This means that it is possible to design a generic interface to a group of related
activities.
• This helps reduce complexity by allowing the same interface to be used to specify a general
class of action.
• Polymorphism allows us to create clean, sensible, readable, and resilient code.
Inheritance or class Hierarchies:
• Object-oriented programming allows classes to inherit commonly used state and behavior from
other classes. Different kinds of objects often have a certain amount in common with each other.
• In the Java programming language, each class is allowed to have one direct superclass, and
each superclass has the potential for an unlimited number of subclasses.
• Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of
bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional
features that make them different: tandem bicycles have two seats and two sets of handlebars;
road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving
them a lower gear ratio. In this example, Bicycle now becomes the super class of Mountain
Bike, Road Bike, and Tandem Bike.
• The syntax for creating a subclass is simple. At the beginning of your class declaration, use the
extends keyword, followed by the name of the class to inherit from:
class <sub class> extends <super class>
{
// new fields and methods defining a sub class would go here
}
The different types of inheritance are:
1. Single level Inheritance.
2. Multilevel Inheritance.
3. Hierarchical inheritance.
4. Multiple inheritance.
5. Hybrid inheritance.
Multiple, hybrid inheritance is not used in the way as other inheritances but it needs a special
concept called interfaces.
Method Binding:
• Binding denotes association of a name with a class.
• Static binding is a binding in which the class association is made during compile time.
This is also called as early binding.
• Dynamic binding is a binding in which the class association is not made until the object is
created at execution time. It is also called as late binding.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Abstraction:
Abstraction in Java or Object oriented programming is a way to segregate/hiding
implementation from interface and one of the five fundamentals along with Encapsulation,
Inheritance, Polymorphism, Class and Object.
• An essential component of object oriented programming is Abstraction.
• Humans manage complexity through abstraction.
• For example people do not think a car as a set of tens and thousands of individual parts. They
think of it as a well defined object with its own unique behavior.
• This abstraction allows people to use a car ignoring all details of how the engine, transmission
and braking systems work.
• In computer programs the data from a traditional process oriented program can be transformed
by abstraction into its component objects.
• A sequence of process steps can become a collection of messages between these objects. Thus
each object describes its own behavior.
Overriding:
• In a class hierarchy when a sub class has the same name and type signature as a method in the
super class, then the method in the subclass is said to override the method in the super class.
• When an overridden method is called from within a sub class, it will always refer to the version
of that method defined by the sub class.
• The version of the method defined by the super class will be hidden.
Exceptions:
• An exception is an abnormal condition that arises in a code sequence at run time. In other
words an exception is a run time error.
• A java exception is an object that describes an exceptional condition that has occurred in a
piece of code. When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error.
Summary of OOP concepts
OOP) is a programming paradigm that represents concepts as "objects" that have data fields
(attributes that describe the object) and associated procedures known as methods.
• Objects, which are usually instances of classes, are used to interact with one another to design
applications and computer programs.
• Object-oriented programming is an approach to designing modular, reusable software systems.
• The goals of object-oriented programming are:
Increased understanding
Ease of maintenance
Ease of evolution.
Object orientation eases maintenance by the use of encapsulation and information hiding.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Java Basics:
History of JAVA
Java is a high level programming Language. It was introduced by ―SUN Microsystems‖ in June
1995. It was developed by a team under James Gosling. Its original name was ―OAK‖ and later
renamed to Java. Java has become the standard for Internet applications.
Since the Internet consists of different types of computers and operating systems. A common
language needed to enable computers. To run programs that run on multiple plot forms.
Java is Object-Oriented language built on C and C++. It derives its syntax from C and its
Object-Oriented features are influenced by C++.
Java can be used to create two types of programs
Applications
Applets.
An application is a prg.that runs on the user‘s computers under the operating system.
An Applet is a small window based prg.that runs on HTML page using a java enabled web
browser like internet Explorer, Netscape Navigator or an Applet Viewer.
JDK provides tools in the bin directory of JDK and they are as follows:
Javac: Javac is the java compiler that translates the source code to byte codes. That is, it
converts the source file. Namely the .java file to .class file.
Java: The java interpreter which runs applets and Applications by reading and interpreting the
byte code files. That is, it executes the .class file.
Javadoc: Javadoc is the utility used to produce documentation for the classes from the java files.
JDB: JDB is a debugging tool.
The way these tools are applied to build and run application programs is as follows:
The source code file is created using a text editor and saved with a .java (with Extension). The
source code is compiled using the java compiler javac. This translates source code to byte
codes. The compiled code is executed using the java interpreter java.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
7. Multithreaded: Java was designed to meet the real-world requirement. To achieve this, java
supports multithreaded programming. It is the ability to run any things simultaneously.
8. Dynamic: That is run time. This makes it possible to dynamically link code in a safe and
secure manner.
9. Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the main
problems facing programmers is that no guarantee exists that if you write a program today, it will
run tomorrow—even on the same machine.
Operating system upgrades, processor upgrades, and changes in core system resources can all
combine to make a program malfunction. The Java Virtual Machine (JVM) in an attempt to alter
this situation. Their goal was ―write once; run anywhere, anytime, forever.
Comments: There are 3 types of comments defined by java. Those are Single line comment,
multilane comment and the third type is called documentation comment. This type of comment is
used to produce an HTML file that documents your prg.
// this is single line comment.
/* this multiple
line comment*/
/** this documentation comment */
Key words:
Keywords are the words. Those have specifics meaning in the compiler. Those are called
keywords. There are 49 reserved keywords currently defined in the java language. These
keywords cannot be used as names for a variable, class or method. Those are,
First, every variable has a type, every expression has a type, & every type is strictly defined.
Second, all assignments, whether explicit or via parameter passing in method calls, are checked
for type compatibility. There are no automatic coercions or conversions of conflicting types as in
some languages.
The Java compiler checks all expressions and parameters to ensure that the types are compatible.
Any type mismatches are errors that must be corrected before the compiler will finish compiling
the class.
For example, in C/C++ you can assign a floating-point value to an integer as shown below
int n=12.345;
where in the above case the integer variable holds only the round part of the assigned fraction
value as n=12.
In Java, you cannot. Also, in C there is not necessarily strong type-checking between a
parameter and an argument. In Java, there is.
DATA TYPES:
The data, which gives to the computer in different types, are called Data Types or Storage
representation of a variable is called Data Type. Java defines 8 types of data: byte, short, int,
long, float, double, char and Boolean.
These can be put in Four types:
Integer: this group includes byte, short, int & long, which are whole valued signed numbers.
Floating-point numbers: float & double, which represents numbers with fractional precision.
Character: This represents symbols in a character set, like letters and numbers.
Boolean: This is a special type for representing true / false values.
Examples of boolean
class BoolTest b = false;
{ if(b) {
public static void main(String args[]) System.out.println("This is not executed.");}
{ System.out.println("10 > 9 is " + (10 > 9));
boolean b; }
b = false; }
System.out.println("b is " + b); Output:
b = true; b is false
System.out.println("b is " + b); b is true
if(b){ This is executed.
System.out.println("This is executed."); } 10 > 9 is true
Variables:
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime. In Java, all variables must be declared before
they can be used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...];
Ex: int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Constant identifiers:
Final keyword is used for constants. Constant identifiers consist of all capital letters. Internal
words are separated by an underscore (_).
Example: final double TAX_RATE = .05
} }
y = 100; // Error! y not known here }
// x is still known here. Output: x and y: 10 20 x is 40
System.out.print("\tx is " + x);
Types of variables: Java has 4 different kinds of variables
local variables
parameter variables
class variables
instance variables
Local variables:
A local variable will exists as long as the method in which they have been created is still running
As soon as the method terminates, all the local variables inside the method are destroyed.
Example: Scope of local variables:
class SomeClass class Scope2
{ {
public static void main(String args[]) public static void main(String args[ ]) {
{ void show(){
double x; double r;
…………… Local variables r=3.14;
int y; }
} System.out.println(r ); //Causes error is not
} } accessible outside the block
}
Non-overlapping (or disjoint) scopes:
It is possible to declare two variables with the same name in two different block scopes as shown
below
class Scope {
public static void main(String args[]) {
-------
{ double r;
{
String r;
} }
}
}
Parameter variables:
A parameter variable is used to store information that is being passed from the location of the
method call into the method that is called.
class ToolBox
{ a=1.0 b=2.0
public static double min(double a,double b) //Parameter variables
{ ……………….. }
}
class MyProgram
{
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Instance variables:
Non static variables that are declared inside a class are called as instance variables.
class StaticData
{
int a=10,b=20; //instance variables of StaticData class
}
Life and scope of Instance variables:
It is limited only the object specified upon the class
Literals
Integer Literals
Integers are probably the most commonly used type in the typical program. Any hole number
value is an integer literal. Examples are 1, 2, 3, and 42.
Decimal literals
These are all decimal values, meaning they are describing a base 10 number. There are two other
bases which can be used in integer literals
Example: int n=10;
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Octal literals
Octal (base eight). Octal values are denoted in Java by a leading zero. Normal decimal numbers
cannot have a leading zero.
Thus, the seemingly valid value 09 will produce an error from the compiler, since 9 is outside of
octal‟s 0 to 7 range.
Example: int n=07;
Hexadecimal literals:
Hexadecimal (base 16), A more common base for numbers used by programmers is
hexadecimal, which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits.
You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range of a
hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15.
Example: int n=0xfff;
Example Program:
class Literal System.out.print("decimal literal is:"+dec);
{ System.out.println("octal literal is:"+oct);
public static void main(String args[]) System.out.println("hexadecimal is:"+hex);
{ }
int dec=10,oct=07,hex=0xff; }
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component.
Example: float f=12.346f (or) 12.346F;
double d=34.5678d (or) 34.5678D;
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have, true
and false. The true literal in Java does not equal 1, nor does the false literal equal 0.
OPERATORS:
Operator is a Symbol. Java provides a rich set of operators as
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:
variable x = (expression)? value if true : value if false
int x = (10>20)? 100 : 200
Operator Precedence:
Expressions:
An expression is a construct made up of variables, operators, and method invocations, which are
constructed according to the syntax of the language that evaluates to a single value.
int a = 0;
arr[0] = 100;
System.out.println("Element 1 at index 0: " + arr[0]);
int result = 1 + 2; // result is now 3
Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a
complete unit of execution. The following types of expressions can be made into a statement by
terminating the expression with a semicolon (;). Ex: System.out.print(A+B);
Type Conversion and Casting:
We can assign a value of one type to a variable of another type. If the two types are compatible,
then Java will perform the conversion automatically. For example, it is always possible to assign
an int value to a long variable. However, not all types are compatible, and thus, not all type
conversions are implicitly allowed. For instance, there is no conversion defined from double to
byte.
But it is possible for conversion between incompatible types. To do so, you must use a cast,
which performs an explicit conversion between incompatible types.
Java„s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are satisfied:
• The two types are compatible.
• The destination type is larger than the source type.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
When these two conditions are met, a widening conversion (Small data type to Big data type)
takes place. For example, the int type is always large enough to hold all valid byte values, so no
explicit cast statement is required.
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. However, the numeric types are not compatible with char or
boolean. Also, char and boolean are not compatible with each other.
Java also performs an automatic type conversion when storing a literal integer constant into
variables of type byte, short, or long.
Casting Incompatible Types
The automatic type conversions are helpful, they will not fulfill all needs. For example, if we
want to assign an int value to a byte variable. This conversion will not be performed
automatically, because a byte is smaller than an int. This kind of conversion is sometimes
called a narrowing conversion, since you are explicitly making the value narrower so that it will
fit into the target type. To create a conversion between two incompatible types, you must use a
cast. A cast is simply an explicit type conversion.
It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
Example:
int a;
byte b;
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer
type: truncation. As integers do not have fractional components so, when a floating-point value
is assigned to an integer type, the fractional component is lost.
Example Program: Conversion.java
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Let‟s look closely at the type promotions that occur in this line from the program:
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is
float. Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then, in
d*s, the value of s is promoted to double, and the type of the sub expression is double.
Control Statements or Control Flow:
IF Statement
The IF statement is Java‘s conditional branch statement. It can be used to route program
execution through two different paths.
The general form of the if statement:
if (condition) statement1;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a Boolean value. If the
condition is true, then statement1 is executed.
IF –ELSE Statement
If the condition is true, then statement1 is executed. Otherwise statement2 is executed.
The general form of the if statement:
if (condition) statement1;
else statement2;
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates
to false.
void ifClause()
{
int a, b;
if(a < b)
a = 0;
else
b = 0;
}
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Nested ifs
A nested if is an if statement that is the target of another if or else. Here is an example:
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
Iteration Statements
Java‘s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.
The while Statement
The while statement continually executes a block of statements while a particular condition is
true. Its syntax can be expressed as:
while (expression)
{
Statements // body of loop
}
Note: The while statement evaluates an expression, which must return a Boolean value.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
// Use a for-each style for on a 1D array. // Use for-each style for on a 2D array
class ForEach { class ForEach3 {
public static void main(String args[]) { public static void main(String args[]) {
int nums[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0;
int sum = 0; int nums[ ][ ] = new int[3][5];
// use for-each style for to display and sum // give nums some values
the values for(int i = 0; i < 3; i++)
for(int x : nums) { for(int j=0; j < 5; j++)
System.out.println("Value is: " + x); nums[i][j] = (i+1)*(j+1);
sum += x; // use for-each to display & sum the values
} for(int x[ ] : nums) {
System.out.println("Summation: " + sum); for(int y : x) {
} System.out.println("Value is: " + y);
} sum += y;
Output: }}
Value is: 1 System.out.println("Summation: " + sum);
Value is: 2 }}
Value is: 3 Output:
Value is: 4 Value is: 1 Value is: 2 Value is: 3
Value is: 5 Value is: 4 Value is: 5
Value is: 6
Value is: 2 Value is: 4 Value is: 6
Value is: 7
Value is: 8 Value is: 10
Value is: 8
Value is: 9 Value is: 3 Value is: 6 Value is: 9
Value is: 10 Value is: 12 Value is: 15
Summation: 55 Summation: 90
Nested Loops
One loop may be inside another.
Ex: Nested.java
class Nested
{
public static void main(String args[])
{ Output:
int i, j; .........
for(i=1; i<10; i++) ........
{ .......
for(j=i; j<10; j++) ......
{ .....
System.out.print("."); ....
} ...
System.out.println(); ..
} .
}
}
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
As you can see in the above figure, object gets the memory in heap memory area. The reference
variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are
reference variables that refer to the objects allocated in memory.
3) Object and Class Example: Initialization through constructor
We will learn about constructors in java later.
Arrays:
An array is a group of similar-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
A one-dimensional array is a list of like-typed variables. To create an array, you first must create
an array variable of the desired type. The general form of a one dimensional array declaration is
type var-name[ ]; Here, type declares the base type of the array.
int month [ ];
Although this declaration establishes the fact that month is an array variable, no array actually
exists. In fact, the value of month is set to null, which represents an array with no value.
To link month with an actual, physical array of integers, you must allocate one using new and
assign it to month. new is a special operator that allocates memory.
The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];
We can create a three-dimensional array where first index specifies the number of tables,
second one number o0f rows and the third number of columns.
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
For example, the following two declarations are equivalent:
int al[ ] = new int[3];
int[ ] a2 = new int[3];
Constructors:
Constructor is a special method of a class which is invoked automatically whenever an object is
created. It has same name that of a class. A constructor initializes an object immediately upon
creation. A constructor has no return type; not even void. It cannot be abstract, final, native
,static or synchronized. this keyword refers another constructor in same class. A super keyword
will call constructor of super class constructors are of two type
1. Default constructor
2.Parameterised constructor
1. Default constructor:
A constructor that accepts no parameters is called default constructor. If no constructor is defined
for a class java system automatically generates the default constructor. A default constructor is
called when an instance is created for a class. The default constructor automatically initializes
all instance variables to zero.
Example:
class demo
{
int x,y;
float z;
demo()
{
x=1;
y=2;
z=3;
}
void display()
{
System.out.println("Values of x, y and z are:"+x+" "+y+" "+z);
}
}
class Demomain
{
public static void main(String args[])
{
demo d1=new demo( ); // this is a call for the above default constructor
d1.display();
}
}
Output: Values of x,y and z are: 1 2 3.0
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
In this example, we are going to copy the values of one object into another using java
constructor.
Example:
class Student6{ {
int id; System.out.println(id+" "+name); }
String name; public static void main(String args[])
Student6(int i,String n){ {
id = i; Student6 s1 = new Student6(111,"Karan");
name = n; Student6 s2 = new Student6(s1);
} s1.display();
Student6(Student6 s){ s2.display();
id = s.id; }}
name =s.name; Output: 111 Karan
} 111 Karan
void display()
Methods:
Method is an action required by an object. Methods allow the programmer to modularize the
program. All variables declared in method definitions are local variables. That means they are
known only in the method in which they are defined. Most methods have a list of parameters that
provide the means for communicating information between the methods. A methods parameters
are also local variables.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Here is an example. Inside main( ), the static method callme( ) and the static variable b are
accessed through their class name StaticDemo.
Ex: StaticByName.java
class StaticDemo { public static void main(String args[]) {
static int a = 42; StaticDemo.callme();
static int b = 99; System.out.println("b = " + StaticDemo.b);
static void callme() { }
System.out.println("a = " + a); }
} Output:
} a = 42
class StaticByName { b = 99
Access Specifiers:
There are 4 types of java access modifiers: private, public, protected and default
Access Specifiers are the keywords that alter the meaning and accessibility (scope) of a data
member of a class, method or constructor. They are, private, public, protected and default.
There are many non-access modifiers such as static, final, abstract, native, synchronized,
transient and volatile.
private:
It can be applied to variables and methods. Private members of a class are accessible from
within the class only. They cannot be accessed from outside the class and its subclass.
Ex: class A
{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Output: compile time error
Role of Private Constructor: If you make any class constructor private, you cannot create the
instance of that class from outside the class.
Ex: class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
} } Output: compile time error
Note: A class cannot be private or protected except nested class.
public:
It can be applied to variables (data members), methods and classes. Public member of class can
be accessed globally any other code. They can be accessed from outside the class and sub class.
A public class can be accessed from any package.
class Alpha
{
public int i;
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
private Y Y N Y N N N
public Y Y Y Y Y Y Y
protected Y Y N Y Y Y N
default Y Y Y Y Y N N
static Y Y Y - - - -
final Y Y Y - - - -
this Keyword:
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. this can be used inside any method to refer to the current object. That is, this
is always a reference to the object on which the method was invoked.
For example, if you have an Employee class with members 'firstName' and 'lastName' and let's
say you have a private method that formats a full name everytime there is a change in either the
first name or the last name. Then the formatFullName method can access the mebers using 'this'
keyword as follows:
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to perform
cleanup processing (destroying remaining objects).
gc( ) method
The gc( ) method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes. public static void gc( ){}
Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1(); Output:
TestGarbage1 s2=new TestGarbage1(); object is garbage collected
s1=null; object is garbage collected
s2=null;
System.gc();
} }
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC).
This thread calls the finalize() method before object is garbage collected.
Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will be
using is int read( ) throws IOException. Each time that read( ) is called, it reads a character
from the input stream and returns it as an integer value. It returns – 1 when the end of the stream
is encountered. As you can see, it can throw an IOException.
Example Program: // Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do { // read characters
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
Note: This output may look a little different from what you expected, because System.in is line
buffered, by default. This means that no input is actually passed to the program until you press
ENTER.
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
String readLine( ) throws IOException
The following program demonstrates BufferedReader and the readLine() method;
The program reads and displays lines of text until you enter the word ―stop‖:
Example Program: // Read a string from console using a BufferedReader
import java.io.*;
class BRReadLines {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
Java Scanner class
There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them. The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
There is a list of commonly used Scanner class methods:
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value
as a string.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public double nextDouble() it scans the next token as a double value.
public float nextDouble() it scans the next token as a float value.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
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:
String s1="Welcome";
String s2="Welcome"; //will not create new instance
In the beside example only one object will
be created. Firstly JVM will not find any
string object with the value "Welcome" in
string constant pool, so it will create a new
object. After that it will find the string
with the value "Welcome" in the pool, it
will not create new object but will return
the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
Java has more memory efficient, because no new objects are created if it exists already in string
constant pool.
2) By new keyword
String s=new String("Welcome"); //creates two objects and one reference variable
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Difference between StringBuffer and StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of differences
between StringBuffer and StringBuilder are given below:
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. StringBuilder is non-synchronized i.e.
thread safe. It means two threads not thread safe. It means two threads can
can't call the methods of call the methods of StringBuilder
StringBuffer simultaneously. simultaneously.
2) StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
System.out.println(s); // Kalpana
System.out.println(s.trim()); //Kalpana
Java String startsWith() and endsWith() method
String s="Kalpana";
System.out.println(s.startsWith("Ka")); //true
System.out.println(s.endsWith("a")); //true
Java String charAt() method
The string charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output:
S
h
Java String length() method
The string length() method returns length of the string.
String s="Kalpana ";
System.out.println(s.length());//7
Output:
7
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
String s1="Java is a programming language. Java supports OOP features.";
String replaceString=s1.replace("Java","CPP"); //replaces all occurrences of "Java" to "CPP"
System.out.println(replaceString);
Output: CPP is a programming language. CPP supports OOP features.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM (R15)
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.
import java.util.StringTokenizer;
public class Simple
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("my name is kalpana"," ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
my
name
is
kalpana
boolean hasMoreTokens( ) : checks if there is more tokens available.
String nextToken( ) : returns the next token from the StringTokenizer object.
StringTokenizer(String str) : creates StringTokenizer with specified string.
UNIT II - Inheritance – Types of Inheritance, Member access rules, 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,
accessing implementations through interface references, extending interface.
Packages- Defining, creating and accessing a package, Understanding CLASSPATH,
importing packages.
Inheritance
Inheritance can be defined as the process where one class acquires the properties methods
and fields of another. With the use of inheritance the information is made manageable in a
hierarchical order. The class which inherits the properties of other is known as subclass
derived class, child class and the class whose properties are inherited is known as super
class base class, parent class.
Inheritance is the mechanism of deriving new class from old one, old class is known as
super class and new class is known as subclass. The subclass inherits all of its instances
variables and methods defined by the super class and it also adds its own unique
elements. Thus we can say that subclass is specialized version of super class.
Benefits of Java’s Inheritance
1. Reusability of code
2. Code Sharing
3. Consistency in using an interface
Classes
Superclass(Base Class) Subclass(Child Class)
It is a class from which other classes It is a class that inherits some or all
can be derived. members from superclass.
extends Keyword
extends is the keyword used to inherit the properties of a class. Below given is the syntax of
extends keyword.
class Super{ Base Class
..... .... }
class Sub extends Super{
..... ..... } Derived Class
Multiple inheritance:
Deriving one subclass from more than one super classes is called multiple inheritance.
Eg. class A { statements ; }
class B { statements ; }
class C extends A, B { statements ; }
Note: Java does not support multiple inheritance with classes. But, it supports multiple
inheritance using interfaces.
Hybrid Inheritance: It is a combination of multiple and hierarchical inheritance.
A
HIERARCHICAL INHERITANCE
B C MULTIPLE INHERITANCE
D
A sub class uses the keyword “extends” to inherit a base class.
Variable “i” with no access modifier and we are using it in child class.
Program runs with no error in this case as members with default
access modifier can be used in child class
Output
Case3: Member Variables have private access modifier. If a member of class is declared as private
than it cannot be accessed outside the class not even in the inherited class.
Output:
Super Keyword:
Whenever a sub class needs to refer to its immediate super class, we can use the super
keyword. Super has two general forms
• The first calls the super class constructor.
• The second is used to access a member of the super class that has been hidden by a
member of a sub class
Syntax:
A sub class can call a constructor defined by its super class by use of the following form
of super.
super(arg-list);
here arg-list specifies any arguments needed by the constructor in the super class .
The second form of super acts like a”this” keyword. The difference between “this” and
“super” is that “this” is used to refer the current object where as the super is used to refer
to the super class.
The usage has the following general form:
super.member;
Example:
class x b=1;
{ }
int a; void display( )
x( ) {
{ super.display( );
a=0; System.out.println(b);
} }
void display( ) }
{ class super_main
System.out.println(a); {
} public static void main(String args[ ])
} {
class y extends x y y1=new y( );
{ y1.display( );
int b; }
y( ) }
{ Output: 0 1
super( );
super is a reference variable that is used to refer immediate parent class object. Uses of
super keyword are as follows:
1. super() is used to invoke immediate parent class constructors
2. super is used to invoke immediate parent class method
3. super is used to refer immediate parent class variable
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Example:
Output:
Output:
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Note: super() is added in each class constructor automatically by compiler. As default
constructor is provided by compiler automatically but it also adds super() for the first
statement. If you are creating your own constructor and you don‟t have super() as the first
statement, compiler will provide super() as the first statement of the constructor.
Example where super() is provided by compiler
Output:
Preventing Inheritance:
Final Keyword: ( last / concluding )
Final keyword can be used in the following ways:
Final Variable: Once a variable is declared as final, its value cannot be changed
during the scope of the program
Final Method: Method declared as final cannot be overridden
Final Class: A final class cannot be inherited
Using final with inheritance:
The keyword final has three uses.
• First it can be used to create the equivalent of a named constant.
• To prevent overriding.
• To prevent inheritance.
final data members:
Data member with final modifier becomes a constant.
Using final to prevent overriding:
To disallow a method from being overridden, specify final as a modifier at the start of the
declaration.
Methods declared as final cannot be overridden.
Syntax: final <return type> <method name> (argument list);
final returntype funname()
{-----
}
Using final to prevent inheritance:
Some times we may want to prevent a class from being inherited. In order to do this we
must precede the class declaration with final keyword.
Declaring a class as final implicitly declares all its methods as final. The final class can’ t
be sub classed or derived. This means that we can‟ t create a sub class from a final class.
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Example:
final class A { class
B extends A{
}}
The above code gives compile error. Because class A is a final class, which can‟ t be derived.
Example of Final Variable: Final variables work like const of C-language that can‟t be altered in
the whole program. That is, final variables once created can‟t be changed and they must be used
as it is by all the program code.
Output:
Generally, a super class method can be overridden by the subclass if it wants a different
functionality. If the super class desires that the subclass should not override its method, it
declares the method as final. ( it gives compilation error).
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Output
Example of Final Class: If we want the class not be sub-classed(or extended) by any other
class, declare it final. Classes declared final can not be extended.
Output
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Polymorphism
Polymorphism came from the two Greek words „poly‟ means many and „morphos‟ means
forms. If the same method has ability to take more than one form to perform several tasks
then it is called polymorphism.
It is of two types: Dynamic polymorphism and Static polymorphism.
Dynamic Polymorphism / Dynamic binding:
The polymorphism exhibited at run time is called dynamic polymorphism. In this dynamic
polymorphism a method call is linked with method body at the time of execution by JVM.
Java compiler does not know which method is called at the time of compilation. This is also
known as dynamic binding or run time polymorphism.
Method overloading and method overriding are examples of Dynamic Polymorphism in Java.
o Method Overloading: Writing two or o Method Overriding: Writing two or more
more methods with the same name, but methods in super & sub classes with same
with a difference in the method name and same signatures is called
signatures is called method over loading. method overriding.
Method signature represents the method WAP that contains a super and sub class
name along with the method parameters. which contains a method with same name
Method is called depending upon the and same method signature, behavior of the
difference in the method signature. The method is dynamically decided.
difference may be due to the following: // Dynamic polymorphism: overriding of
There is a difference in the no. of parameters. methods
void add (int a,int b) class Parent
void add (int a,int b,int c) {
difference in the data types of parameters. void move()
void add (int a,float b) {
void add (double a,double b) System.out.println ("Parent can move");
difference in the sequence of parameters. }
void swap (int a,char b) }
void swap (char a,int b) class Child extends Parent
//Dynamic polymorphism: Overloading {
methods void move()
class Sample {
{ void add(int a,int b) System.out.println ("Child can walk & run");
{s }
System.out.println ("sum of two="+ (a+b)); }
} class OverRide
void add(int a,int b,int c) { {
System.out.println("sum of 3="+ (a+b+c)); public static void main(String args[])
} {
} Parent a = new Parent ( );
class OverLoad Parent b = new Child (); // Animal reference
{ public static void main(String[] args) but Dog object (Up casting)
{ Sample s=new Sample ( ); a.move (); // runs method in Animal class
s.add (20, 25); b.move (); //Runs method in Dog class
s.add (20, 25, 30); }
} } }
Output: sum of two=45 Output: Parent can move
Sun of three=75 Child can walk & run
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting.
For example:
MRCET UNIT-II JP NOTES II B.TECH. I SEM
class A{}
class B extends A{}
A a=new B();//upcasting
Example
In this example a reference
is created “Ref1” of type
parent1.
To call an overridden
method of any class this
reference variable is
assigned an object of that
class. For ex. To call sum()
method of child class Ref1
is assigned object c1 of
childclass.
Output
Real time example of Java Runtime Polymorphism
Consider a scenario; Bank is a class that provides method to get the rate of interest. But, rate of
interest may differ according to banks. For example, SBI, ICICI and AXIS banks could provide
8%, 7% and 9% rate of interest.
EX1: class Bank{ Rule: Runtime polymorphism can't be
int getRateOfInterest(){return 0;} achieved by data members.
} Ex2:
class SBI extends Bank{ class Bike{
int getRateOfInterest(){return 8;} int speedlimit=90;
} }
class ICICI extends Bank{ class Honda3 extends Bike{
int getRateOfInterest(){return 7;} int speedlimit=150;
}
class AXIS extends Bank{ public static void main(String args[]){
int getRateOfInterest(){return 9;} Bike obj=new Honda3();
} System.out.println(obj.speedlimit);//90
class Test3{ } Output:90
public static void main(String args[]){
Bank b1=new SBI(); Bank b2=new ICICI(); Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
}}
Output: SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Another way, it shows only important things to the user and hides
the internal details for example sending sms, you just type the text and send the message.
You don't know the internal processing about the message delivery.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
3.
Note1: It can be applied to methods and classes. It cannot be used with data members.
Note2: It needs to be extended and its method implemented. It cannot be instantiated.
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
MRCET UNIT-II JP NOTES II B.TECH. I SEM
As shown in the figure given above, a class extends another class, an interface extends
another interface but a class implements an interface.
MRCET UNIT-II JP NOTES II B.TECH. I SEM
A programmer uses an abstract class when there are some common features shared by all
the objects. Interfaces are written when the programmer wants to leave the implementation to
third party vendors. An interface is a specification of method prototypes. All the methods in an
interface are abstract methods.
An interface is a specification of method prototypes.
An interface contains zero or more abstract methods.
All the methods of interface are public, abstract by default.
Once an interface is written any third party vendor can implement it.
All the methods of the interface should be implemented in its implementation classes.
If any one of the method is not implemented, then that implementation class
should be declared as abstract.
We cannot create an object to an interface.
We can create a reference variable to an interface.
An interface cannot implement another interface.
An interface can extend another interface.
A class can implement multiple interfaces.
Defining an interface:
An interface is defined much like a class.
This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Here is an example of an interface definition. It declares a simple interface that contains one
method called callback() that takes a single integer parameter.
interface Callback
{
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. The
general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. If a
class implements two interfaces that declare the same method, then the same method will be
used by clients of either interface. The methods that implement an interface must be declared
public.
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Packages in JAVA:
Java provides a mechanism for partitioning the class name space into more manageable
chunks. This mechanism is the package. The package is both a naming and a visibility control
mechanism. You can define classes inside a package that are not accessible by code
outside that package. You can also define class members that are only exposed to other
members of the same 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 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.
3) Java package removes naming collision.
4) A group of package called a library. The classes and interfaces of a package are likes
books in a library and can be reused several times.
Defining a Package:
• Creating a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the
specified package. The package statement defines a name space in which classes are stored.
Creating a Package:
•The general form of the package statement:
package pkg; //Here, pkg is the name of the package.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example: javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use
any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you
want to keep the package within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Welcome to package
Note: The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
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.
Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("
Hello");
}}
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Importing Packages:
Java includes the import statement to bring certain classes, or entire packages, into visibility.
The import statement is convenient. In a Java source file, import statements occur immediately
following the package statement (if it exists) and before any class definitions.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.). Finally, you specify either an explicit
classname or a star (*), which indicates that the Java compiler should import the entire
package.
MRCET UNIT-II JP NOTES II B.TECH. I SEM
6. Java.io: This package contains I/O support classes. They provide facilities for input and
output of data. They include classes for BufferedInputStream, BufferedOutputStream,
DataInputStream and DataOutputStream.
7. Javax.swing: this package helps to develop GUI like java.awt. The „x‟ in javax represents
that it is an extended package which means it is a package developed from another package
by adding new features to it. In fact, javax.swing is an extended package of java.awt.
User-Defined packages:
Just like the built in packages shown earlier, the users of the Java language can also create their
own packages. They are called user-defined packages. User-defined packages can also be
imported into other classes and used exactly in the same way as the Built-in packages.
Packages Examples:
Program 1: Write a program to create a package pack with Addition class.
//creating a package
package pack;
public class Addition
{ private double d1,d2;
public Addition(double a,double b)
{ d1 = a;
d2 = b;
}
public void sum()
{ System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}
Compiling the above program:
Program 3: Write a program to add one more class Subtraction to the same package
pack.
//Adding one more class to package pack:
package pack;
public class Subtraction
{
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Program 4: Write a program to access all the classes in the package pack.
//To import all the classes and interfaces in a class using import pack.*;
import pack.*;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10.5,20.6);
ob1.sum();
Subtraction ob2 = new Subtraction(30.2,40.11);
ob2.difference();
}
}
UNDERSTANDING CLASSPATH:
If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in
the classpath.
The CLASSPATH is an environment variable that tells the Java compiler where to look for
class files to import.
If our package exists in e:\sub then we need to set class path as follows:
We are setting the classpath to e:\sub directory and current directory (.) an
%CLASSPATH% means retain the already available classpath as it is.
Creating Sub package in a package: We can create sub package in a package in the format:
package packagename.subpackagename;
.: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package. To use the
classes and interfaces of pack2, we can write import statement as:
import pack1.pack2; Ex: import java.io.*;
MRCET UNIT-II JP NOTES II B.TECH. I SEM
Program 5: Program to show how to create a subpackage in a package.
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{
public void show ()
{
System.out.println ("Hello Java Learners");
}
}
ACCESSING A PACKAGES:
Access Specifier: Specifies the scope of the data members, class and methods.
private members of the class are available with in the class only. The scope of
private members of the class is “CLASS SCOPE”.
public members of the class are available anywhere . The scope of public members
of the class is "GLOBAL SCOPE".
default members of the class are available with in the class, outside the class and in its
sub class of same package. It is not available outside the package. So the
scope of default members of the class is "PACKAGE SCOPE".
protected members of the class are available with in the class, outside the class and in
its sub class of same package and also available to subclasses in different package
also.
Inheritance goes with extends keyword Inheritance goes with implements keywords.
The variables can have any acess specifier. The Variables should be public, static, final
Classes are created by putting the keyword Interfaces are created by putting the keyword
class prior to classname. interface prior to interfacename(super class).
Classes contain any type of methods. Classes Interfaces contain mustly abstract methods.
may or may not provide the abstractions. Interfaces are exhibit the fully abstractions
Exceptions:
•An exception (or exceptional event) is a problem or an abnormal condition that arises during
the execution of a program or at run time. In other words an exception is a run time error.
When an Exception occurs the normal flow of the program is disrupted and the program
terminates abnormally, therefore these exceptions are to be handled. An exception can occur for
many different reasons, including the following:
• A user has entered invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM
has run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
A java exception is an object that describes an exceptional condition that has occurred in a piece
of code. When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error. Now the exception is caught and processed.
Exception Handler:
It is a piece of code; Exceptions are conditions within the code. A developer can handle such
conditions and take necessary corrective actions. Exception Handling is a mechanism to handle
runtime errors such as ClassNotFound, IO, SQL, Remote etc.
IOException:
It is an Exception class. It is a part of java.io packages. It is required to be caught in every
method when readLine() is used. Else throws class is used to mention IOException.
Runtime Exceptions: A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are
ignored at the time of compilation.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable
E.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Catch:
This block takes corrective steps when an exception is thrown. It provides a suitable message to
the user. Then user will be able to proceed with the application.
A try block can follow multiple catch blocks.
Throw:
It is used to throw an exception.
Throws:
It is used to specify the possible exceptions that are caused by a method. But not handled by the
method.
Finally:
This block is followed by catch block. This used to close files, data base connections etc. This
block is executed irrespective of whether exception occurs or not.
try{
//Do something
}
catch(Exception ex)
{
//Catch exception hare using exception argument ex
}
The code which is prone to exceptions is placed in the try block, when an exception occurs; that
exception occurred is handled by catch block associated with it.
Example:
class ExceptionSample {
public static void main (String[] arrgs) // Main function
{
int no1, no2; //Data variables
no1=5; //Contain some value
no2=0; //contain some value
try // Try block
{
System.out.println(no1/no2); //attempt to divide number by 0
}
catch (Exception ex) // Catch block receive exception
{/* Display exception message */ System.out.println("Error
with defination: "+ex.getMessage());
} } }
User-defined exception (or) Custom Exception (or) Own Exception:
The built-in exceptions do not meet our specific requirements. We can define our own exception
classes such exceptions are known, as user-defined exception must extend the base class
exception.
Syn.: class classname extends Exception
{
---------
}
Example:
class InvalidAgeException extends Exception public static void main(String args[ ])
{ {
InvalidAgeException(String s) try
{ {
super(s); validate(13);
} }
} catch(Exception m)
class TestCustomException1 {
{ System.out.println("Exception occur: "+m);
}
static void validate(int age)throws InvalidAg
eException System.out.println("rest of the code...");
{ }
if(age<18) }
throw new InvalidAgeException("not valid"); Output:
Exception occured:
else InvalidAgeException:not valid
System.out.println("welcome to vote"); rest of the code...
}
By the help of custom exception, you can have your own exception and message. Let's see a
simple example of java custom exception.
Prepared by D. KALPANA, Asst.Professor, Dept. Of CSE Page 7
MRCET UNIT-III JP NOTES III B.TCH. I SEM
Multithreading
A program can be divided into a number of small processes. Each small process can be
addressed as a single thread (a lightweight process). Multithreaded programs contain two or
more threads that can run concurrently. This means that a single program can perform two or
more tasks simultaneously. For example, one thread is writing content on a file at the same time
another thread is performing spelling check.
An instance of Thread class is just an object, like any other object in java. But a thread of
execution means an individual "lightweight" process that has its own call stack. In java each
thread has its own call stack.
A Process consists of the memory space allocated by the operating system that can contain one
or more threads. A thread cannot exist on its own; It must be a part of process.
There are two distinct types of Multitasking i.e., Processor-based and Thread-based
Multitasking.
What is the difference between thread based and processor-based Multitasking
Thread Process
Thread is a light-weight process. Process is a heavily-weight process.
Threads share the address space Processes require their own separate address space.
In Thread-based multitasking, thread is Process-Based multitasking is a feature that allows
the smallest unit of code, which means your computer to run two or more
a single program can perform two or programs concurrently. For example you can listen
more tasks simultaneously. to music and at the same time chat with
For example a text editor can print and your friends on Facebook using browser.
at the same time you can edit text
provided that those two tasks are
perform by separate threads.
Inter thread communication is Inter process communication is expensive and
inexpensive, and context switching limited
from one thread to the next is lower in
cost.
Difference between Multi tasking and Multi threading
A multithreaded program contains two or more parts that can run concurrently. Each part of such
a program is called a thread, and each thread defines a separate path of execution. Thus,
multithreading is a specialized form of multitasking.
There are two distinct types of multitasking: process-based and thread-based.
A process is a program that is executing. Thus, process-based multitasking is the feature that
allows to run two or more programs concurrently. For example, process-based multitasking
enables you to run the Java compiler at the same time that you are using a text editor.
In process-based multitasking, a program is the smallest unit of code that can be dispatched by
the scheduler.
Concurrent Parallel
– Tasks that overlap in time – Tasks that run at the same time on different
processors
• The system might run them in parallel
on multiple processors
Two Queues One coffee machine Two Queues Two coffee machines
Creating a thread
Java defines two ways by which a thread can be created.
By implementing the Runnable interface.
By extending the Thread class.
Implementation of thread
Extends Implements
Run() method
In this case also, as we must override the run() and then use the start() method to start and run
the thread.
Example:
Interrupting threads:
Stopping a thread: A thread can be stopped from running further by issuing the following
statement-
th.stop();
By this statement the thread enters in a dead state. From stopping state a thread can never return
to a runnable state.
Use of stop() Method
The stop() method kills the thread on execution
Example:
Blocking a thread:
A thread can be temporarily stopped from running. This is called blocking or suspending of a
thread. Following are the ways by which thread can be blocked-
1. sleep( )
By sleep method a thread can be blocked for some specific time. When the specified time
gets elapsed then the thread can return to a runnable state.
Example:
2. suspend( )
By suspend method the thread can be blocked until further request comes. When the
resume() method is invoked then the returns to a runnable stste.
3. wait()
The thread can be made suspended for some specific conditions. When the notify() method is
called then tha blocked thread returns to the runnable state.
The difference between the suspending and stopping thread is that if a thread is suspended then
its execution is stopped temporarily and it can return to a runnable state. But in case, if a thread
is stopped then it goes to a dead state and can never return to runnable state.
Thread Priorities
There are various properties of threads. Those are,
\} Thread priorities
\} Daemon Threads
\} Thread group
Thread Priorities:
Every thread has a priority that helps the operating system determine the order in which threads
are scheduled for execution. In java thread priority ranges between,
MIN-PRIORITY (a constant of 1)
MAX-PRIORITY (a constant of 10)
By default every thread is given a NORM-PRIORITY(5).
The main thread always have NORM-PRIORITY.
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and very much platform dependent.
Example:
public clicker(int p) { try {
t = new Thread(this); Thread.sleep(10000);
t.setPriority(p); } catch (InterruptedException e) {
} System.out.println("Main thread
public void run() { interrupted.");
while (running) { }
click++; lo.stop();
} hi.stop();
} 4 Wait for child threads to
public void stop() { terminate. try {
running = false; hi.t.join();
} lo.t.join();
public void start() { } catch (InterruptedException e) {
t.start(); System.out.println("InterruptedException
} caught"); }System.out.println("Low-priority
} thread: " + lo.click);
class HiLoPri { System.out.println("High-priority thread: " +
public static void main(String args[]) { hi.click);
Thread.currentThread().setPriority(Thread.
MAX_PRIORITY); }
clicker hi = new }
clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new Output:
clicker(Thread.NORM_PRIORITY - 2); Low-priority thread: 4408112
lo.start(); High-priority thread: 589626904
hi.start();
EX2:
In the above
code, you can see Priorities of Thread is set to maximum for Thread A which lets it to run to
completion ahead of C which is set to minimum priority.
Output:
Daemon Thread:
In Java, any thread can be a Daemon thread. Daemon threads are like a service providers for
other threads. Daemon threads are used for background supporting tasks and are only needed
while normal threads are executing.
If normal threads are not running and remaining threads are daemon threads then the interpreter
exits. setDaemon(true/false) ? This method is used to specify that a thread is daemon
thread.public boolean isDaemon() ? This method is used to determine the thread is daemon
thread or not.
The core difference between user threads and daemon threads is that the JVM will only shut
down a program when all user threads have terminated. Daemon threads are terminated by the
JVM when there are no longer any user threads running, including the main thread of execution.
Use daemons as the minions they are.
import java.io.*;
public class DaemonThread extends Thread
{
public void run()
{
System.out.println("Enter run method");
System.out.println("In run method: currentThread() is" +Thread.currentThread());
Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process by which this synchronization
is achieved is called thread synchronization.
The synchronized keyword in Java creates a block of code referred to as a critical section. Every
Java object with a critical section of code gets a lock associated with the object. To enter a
critical section, a thread needs to obtain the corresponding object's lock.
synchronized(object)
{
// statements to be synchronized
}
As long as the thread holds the monitor, no other thread can enter the synchronized section of the
code. Writing the method as synchronized will make one thread enter the method and till
execution is not complete no other thread can get access to the method.
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, Event sources, Event classes, Event Listeners, Delegation
event model, handling mouse and keyboard events, Adapter classes.
Streams- Byte streams, Character streams, Text input/output.
APPLETS:
An applet is a program that comes from server into a client and gets executed at client side and
displays the result.
An applet represents byte code embedded in a html page. (Applet = bytecode + html) and run
with the help 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 have
a main () method.
To create applet we can use java.applet.Applet or javax.swing.JApplet class. All applets inherit
the super class „Applet‟. An Applet class contains several methods that help to control the
execution of an applet.
Advantages:
Applets provide dynamic nature for a webpage.
Applets are used in developing games and animations.
Writing and displaying (browser) graphics and animations is easier than
applications.
In GUI development, constructor, size of frame, window closing code etc. are not
required
Restrictions Can access any data or software Cannot access anything on the
available on the system system except browser‟s
services
Security Does not require any security Requires highest security for the
system as they are untrusted
Accessibility The java applications are Applets are designed just for
designed to work with the handling the client site
client as well as server. problems.
Client side / The applications don't Applets are designed for the
Server side have such type of criteria client site programming purpose
Example
public class MyClass import java.awt.*;
{ import java.applet.*;
public static void main(String
args[]) {} public
} class Myclass extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy() {}
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 connecting to database and retrieving the data and processing
the data is written.
Idle / Runnable:
public void stop (): This method is executed when the applet loses focus. Code related to
stopping threads and performing clean up operations are
closing the files and database,
written in this stop method.
Dead/Destroyed:
destroy (): This method is executed only once when the applet is terminated
public void
from the memory.
Executing above methods in that sequence is called applet life cycle.
We can also use public void paint (Graphics g) in applets.
//An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
3 Called first.
public void
init() {
4 initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
3 start or resume execution
}
4 Called when the applet is
stopped. public void stop() {
5 suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() {
5 perform shutdown activities
}
6 Called when an applet's window must be
restored. public void paint(Graphics g) {
7 redisplay contents of window
}
}
After writing an applet, an applet is compiled in the same way as Java application but running of
an 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:
<APPLET CODE=”name of the applet class file” HEIGHT = maximum height of applet in
pixels WIDTH = maximum width of applet in pixels ALIGN = alignment (LEFT, RIGHT,
MIDDLE, TOP, BOTTOM)>
<PARAM NAME = parameter name VALUE = its
value> </APPLET>
Execution: appletviewer programname.java or appletviewer programname.html
The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML page
which can be passed to the applet. The applet can access the parameter value using
getParameter () method, as: String value = getParameter (“pname”);
Example Program:
Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet {
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}}
Embedded an Applet
//First.java
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
public class First extends Applet
{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
OUTPUT: javac First.java
appletviewer First.java
TYPES OF APPLETS
Applets are of two types:
// Local Applets
// Remote Applets
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.
Ex3: Hai.java
import java.applet.*;
import java.awt.*;
/*<Applet code="hai" height="250" width="250">
<PARAM name="Message" value="Hai friend how are you ..?"></APPLET>
*/
class hai extends Applet
{
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
EVENT HANDLING
Event handling is at the core of successful applet programming. Most events to which the applet
will respond are generated by the user. The most commonly handled events are those generated
by the mouse, the keyboard, and various controls, such as a push button.
Events are supported by the java.awt.event package.
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, entering
a 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
java.awt.event.
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 java.util. 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 java.awt.event defines several types of events that are generated by various user
interface 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.
}
Adapter Classes
Java provides a special feature, called an adapter class , that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ) . The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and implement mouseDragged( ) . The empty
implementation of mouseMoved( ) would handle the mouse motion events for you.
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
EX: // Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new
MyMouseMotionAdapter(this)); }
}
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.
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 java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
} } }}
Now let's have a file input.txt with the following content:
This is test for copy file.
$javac CopyFile.java
$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 java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Example: Write a program to read data from the keyboard and write it to myfile.txt file.
import java.io.*;
class Test{
public static void main(String args[])
{
DataInputStream dis=new DataInputStream(System.in);
FileOutputstream fout=new
FileOutputStream("myfile.txt"); System.out.println("Enter
text @ at the end:”); char ch;
while((ch=(char)dis.read())!=‟@‟)
fout.write(ch);
fout.close();
}
}
Output: javac Test.java
Java Test
Java FileInputStream class obtains input bytes from a file. It is used for reading streams of raw
bytes such as image data. It should be used to read byte-oriented data for example to read image,
audio, video etc.
Example: Write a program to read data from myfile.txt using FileInputStream and display
it on monitor.
import java.io.*;
class ReadFile
{
public static void main(String args[])
{
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.
Control Fundamentals
The AWT supports the following types of controls:
3. Labels
4. Push buttons
5. Check boxes
6. Choice lists
7. Lists
8. Scroll bars
9. Text editing
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, Dialog
and 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.
Layout Managers
Prepared by D. KALPANA, Asst.Professor, Dept. Of CSE Page 3
MRCET UNIT-V JP NOTES III B.TCH. I SEM
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 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 java.awt.*;
/*
<applet code="Border" width="500" height="500">
</applet>
*/
public class Border extends java.applet.Applet
{
public void init()
{
setLayout( new java.awt.BorderLayout() );
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" );
}
}
AWT controls
Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string,
which it displays. Labels are passive controls that do not support any interaction with the user.
// Demonstrate
Labels import
java.awt.*; import
java.applet.*; /*
<applet code="LabelDemo" width=300 height=200>
</applet> */
public class LabelDemo extends Applet
{
public void init()
{
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
add labels to applet window
add(one);
add(two);
add(three);
}
}
Buttons:
The most widely used control is the push button. A push button is a component that contains a
label and that generates an event when it is pressed. Push buttons are objects of type Button.
Button class is useful to create push buttons. A push button triggers a series of events.
To create push button: Button b1 =new Button("label");
To get the label of the button: String l = b1.getLabel();
To set the label of the button: b1.setLabel("label");
To get the label of the button clicked: String str = ae.getActionCommand();
\{ Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <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.
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
checkbox Win98, winNT, solaris, mac;
TextField:
The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
paste keys, and mouse selections.
// Demonstrate text field.
import java.awt.*;
import
java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet implements ActionListener
{
TextField name, pass;
TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea .
\{ Demonstrate
TextArea. import
java.awt.*; import
java.applet.*;
/*
<applet code="TextAreaDemo" width=300
height=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.
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
Choice Controls
The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu. Choice menu is a popdown list of items. Only
one item can be selected.
· To create a choice menu: Choice ch = new Choice();
· To add items to the choice menu: ch.add ("text");
· To know the name of the item selected from the choice menu:
String s = ch.getSelectedItem ();
· To know the index of the currently selected item: int i = ch.getSelectedIndex();
This method returns -1, if nothing is selected.
//Demonstrate Choice
lists. import
java.awt.*; import
java.awt.event.*;
import java.applet.*;
/*
<applet code="ChoiceDemo" width=300
height=180> </applet>
*/
public class ChoiceDemo extends Applet implements ItemListener
{ Choice os, browser;
String msg = ""; public
void init() { os = new
Choice(); browser = new
Choice();
//add items to os list
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
\{ add items to browser list
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Netscape 5.x");
browser.add("Netscape 6.x");
browser.add("Internet Explorer
4.0"); browser.add("Internet
Explorer 5.0");
browser.add("Internet Explorer
6.0"); browser.add("Lynx 2.4");
browser.select("Netscape 4.x");
\{ add choice lists to
window add(os);
add(browser);
\{ register to receive item
events
os.addItemListener(this);
browser.addItemListener(
this);
}
Prepared by D. KALPANA, Asst.Professor, Dept. Of CSE Page 14
MRCET UNIT-V JP NOTES III B.TCH. I SEM
Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice
object, 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 only
one item.
= To add items to the list box: lst.add("text");
= To get the selected items: String x[] = lst.getSelectedItems();
= To get the selected indexes: int x[] = lst.getSelectedIndexes ();
// Demonstrate Lists.
import java.awt.*; import
java.awt.event.*; import
java.applet.*; /*
<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);
\{ To create a scrollbar : Scrollbar sb = new Scrollbar (alignment, start, step, min, max);
alignment: Scrollbar.VERTICAL, Scrollbar.HORIZONTAL
start: starting value (e.g. 0)
step: step value (e.g. 30) // represents scrollbar length
min: minimum value (e.g. 0)
max: maximum value (e.g. 300)
· To know the location of a scrollbar: int n = sb.getValue ();
· To update scrollbar position to a new position: sb.setValue (int position);
· To get the maximum value of the scrollbar: int x = sb.getMaximum ();
· To get the minimum value of the scrollbar: int x = sb.getMinimum ();
· To get the alignment of the scrollbar: int x = getOrientation ();
This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL.
// Demonstrate scroll bars.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<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 = Integer.parseInt(getParameter("width")); int
height = Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, width);
add(vertSB);
add(horzSB);
// register to receive adjustment events
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
// Update scroll bars to reflect mouse dragging.
public void mouseDragged(MouseEvent me) {
int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me) {
}
// Display current value of scroll bars.
public void paint(Graphics g) {
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
\} show current mouse drag position
g.drawString("*", horzSB.getValue(),
vertSB.getValue());
}
}
Graphics
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to
a 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 ends
at endX,endY.
The following applet draws several lines:
// Draw lines import
java.awt.*; import
java.applet.*; /*
Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively.
They 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 rectangle
are 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 java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300
height=200> </applet>
*/
public class Rectangles extends Applet {
public void paint(Graphics g) {
g.drawRect(10, 10, 60, 50); g.fillRect(100,
10, 60, 50); g.drawRoundRect(190, 10,
60, 50, 15, 15); g.fillRoundRect(70, 90,
140, 100, 30, 40);
}
}
Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods
are shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
// Draw
Ellipses
import
java.awt.*
; import
java.apple
t.*; /*
<applet code="Ellipses" width=300
height=200> </applet>
*/
public class Ellipses extends Applet
{ public void paint(Graphics g) {
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
} }
Prepared by D. KALPANA, Asst.Professor, Dept. Of CSE Page 19
MRCET UNIT-V JP NOTES III B.TCH. I SEM
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose
width and height are specified by width and height. The arc is drawn from startAngle through
the angular distance specified by sweepAngle. Angles are specified in degrees.
Zero degrees is on the horizontal, at the three o’clock position. The arc is drawn
counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is negative.
Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle would be 90
and the sweep angle 180.
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 polygon’s 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 several arcs: The following applet draws an
//Draw Arcs hourglass shape:
import
java.awt.*; // Draw Polygon
import import
java.applet.*; java.awt.*;
/* import
java.applet.*;
<applet code="Arcs" /*
width=300 height=200> <applet code="HourGlass"
</applet> width=230 height=210>
*/ </applet>
public class Arcs extends Applet { */
public void paint(Graphics g) { public class HourGlass extends Applet {
g.drawArc(10, 40, 70, 70, 0, 75); public void paint(Graphics g) {
g.fillArc(100, 40, 70, 70, 0, 75); int xpoints[] = {30, 200, 30, 200, 30};
g.drawArc(10, 100, 70, 80, 0, 175); int ypoints[] = {30, 30, 200, 200, 30};
g.fillArc(100, 100, 70, 90, 0, 270); int num = 5; g.drawPolygon(xpoints,
g.drawArc(200, 80, 80, 80, 0, 180); ypoints, num);
} }
} }
Prepared by D. KALPANA, Asst.Professor, Dept. Of CSE Page 20
MRCET UNIT-V JP NOTES III B.TCH. I SEM
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.
API such as JButton, JTextField, JTextArea,
The javax.swing package provides classes for java swing
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
AWT Swing
AWT components are called Heavyweight Swings are called light weight component
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 which is not available in AWT.
Also.Swing components are called
"lightweight" because they do not require a
native OS object to implement their
functionality. JDialog and JFrame are
heavyweight, because they do have a peer. So
components like JButton, JTextArea, etc., are
lightweight because they do not have an OS
peer.
JApplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must
be subclasses of JApplet. JApplet is rich with functionality that is not foundin Applet.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is
shown here:
void add(comp)
Here, comp is the component to be added to the content pane.
JFrame
Create an object to JFrame: JFrame ob = new JFrame ("title"); (or)
Create a class as subclass to JFrame class: MyFrame extends JFrame
Create an object to that class : MyFrame ob = new MyFrame ();
Example: Write a program to create a frame by creating an object to JFrame
class. //A swing Frame
import javax.swing.*;
class MyFrame
{
public static void main (String agrs[])
{ JFrame jf = new JFrame ("My Swing Frame...");
jf.setSize (400,200);
jf.setVisible (true);
jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}
Note: To close the frame, we can take the help of getDefaultCloseOperation () method of
JFrame class, as shown here: getDefaultCloseOperation (constant);
where the constant can be any one of the following:
・ JFrame.EXIT_ON_CLOSE: This closes the application upon clicking on close button.
・ JFrame.DISPOSE_ON_CLOSE: This disposes the present frame which is visible on
the screen. The JVM may also terminate.
・ JFrame.DO_NOTHING_ON_CLOSE: This will not perform any operation upon clicking
on close button.
・ JFrame.HIDE_ON_CLOSE: This hides the frame upon clicking on close button.
Window Panes: In swings the components are attached to the window panes only. A window
pane represents a free area of a window where some text or components can be displayed. For
example, we can create a frame using JFrame class in javax.swing which contains a free area
inside it, this free area is called 'window pane'. Four types of window panes are available in
javax.swing package.
Glass Pane: This is the first pane and is very close to the monitors screen. Any components to
be displayed in the foreground are attached to this glass pane. To reach this glass pane, we use
getGlassPane () method of JFrame class.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this pane. Root pane and glass pane are used in animations also.
For example, suppose we want to display a flying aeroplane in the sky. The aeroplane can be
displayed as a .gif or .jpg file in the glass pane where as the blue sky can be displayed in the root
pane in the background. To reach this root pane, we use getRootPane () method of JFrame class.
Layered Pane: This pane lies below the root pane. When we want to take several components
as a group, we attach them in the layered pane. We can reach this pane by calling
getLayeredPane () method of JFrame class.
Content Pane: This is the bottom most pane of all. Individual components are attached to this
pane. To reach this pane, we can call getContentPane () method of JFrame class.
Displaying Text in the Frame:
paintComponent (Graphics g) method of JPanel class is used to paint the portion of a component
in swing. We should override this method in our class. In the following example, we are writing
our class MyPanel as a subclass to JPanel and override the painComponent () method.
TEXT FIELDS
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components. One of its subclasses is
JTextField, which allows you to edit one line of text. Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add text field to content
pane jtf = new
JTextField(15);
contentPane.add(jtf);
}
}
BUTTONS
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that
allow you to control the behavior of buttons, check boxes, and radio buttons.
The JButton Class
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or
both to be associated with the push button. Some of its constructors are shown here:
· To create a JButton with text: JButton b = new JButton (“OK”);
· To create a JButton with image: JButton b = new JButton (ImageIcon ii);
· To create a JButton with text & image: JButton b = new JButton (“OK”, ImageIcon ii);
It is possible to create components in swing with images on it. The image is specified by
ImageIcon class object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<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();
contentPane.setLayout(new FlowLayout());
// Add buttons to content pane
cb = new JCheckBox("C++",
normal); cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
// Add text field to the content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
RADIO BUTTONS
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-
state buttons. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet implements ActionListener {
JTextField tf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
1. Add radio buttons to content pane
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
contentPane.add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
contentPane.add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
contentPane.add(b3);
2. Define a button group
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
contentPane.add(tf);
}
public void actionPerformed(ActionEvent ae) {
tf.setText(ae.getActionCommand());
}
}
SOFTWARE DEVELOPMENT
USING JAVA
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.