Unit I - V
Unit I - V
Unit I - V
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.
[Type here]
• 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.
• Each processing object contains logicthat defines the types of command objects that it
canhandle; 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.
[Type here]
• 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.
[Type here]
• 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:
[Type here]
• private: accessible only in this class.
• (package): accessible only in this package.
• protected: accessible only in this package and in all subclasses of this class.
• public: accessible everywhere this class is available.
[Type here]
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.
[Type here]
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.
[Type here]
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.
[Type here]
Object-Oriented Programming – Summary of Key Terms
Definitions of some of the key concepts in Object Oriented Programming (OOP)
Term Definition
Abstract Data Type A user-defined data type, including both attributes (its state) and
methods (its behavior).
Aggregation Objects that are made up of other objects are known as
aggregations. The relationship is generally of one of two types:
• Composition – the object is composed of other objects. This
form of aggregation is a form of code reuse. E.g. A Car is
composed of Wheels, a Chassis and an Engine
• Collection – the object contains other objects. E.g. a List
contains several Items; A Set several Members.
Attribute A characteristic of an object. Collectively the attributes of an
object describe its state. E.g. a Car may have attributes of
Speed, Direction, Registration Number and Driver.
Class The definition of objects of the same abstract data type. In Java
class is the keyword used to define new types.
Encapsulation The combining together of attributes (data) and methods
(behavior/processes) into a single abstract data type with a
public interface and a private implementation. This allows the
implementation to be altered without affecting the interface.
Inheritance Acquiring the properties from base class to derived class. The
first class is often referred to the base or parent class. The
child is often referred to as a derived or sub-class. Inheritance
is one form of object-oriented code reuse.
E.g. Both Motorbikes and Cars are kinds of Motor Vehicles and
therefore share some common attributes and behaviour but may
add their own that are unique to that particular type.
Interface The behaviour that a class exposes to the outside world; its
public face. Also called its contract‗. In Java interface is also a
keyword similar to class.
However a Java interface contains no implementation: simply
describes the behavior of an Object.
Member Variable A characteristic of an object or See attribute
Method The implementation of some behaviour of an object.
Message The invoking of a method of an object. In OOPs objects send
each other messages to achieve the desired behaviour.
Object An instance of a class. Objects have state, identity and
behaviour.
Overloading Allowing the same method name to be used for more than one
implementation. The different versions of the method vary
according to their parameter lists. If this can be determined at
compile time then static binding is used, otherwise
dynamic binding is used to select the correct method as
runtime.
[Type here]
Polymorphism Generally, the ability of different classes of object to respond to
the same message in different, class-specific ways. Polymorphic
methods are used which have one name but different
implementations for different classes.
E.g. Both the Plane and Car types might be able to respond to
a turnLeft message. While the behaviour is the same, the
means of achieving it are specific to each type.
Primitive Type The basic types which are provided with a given object
oriented programming language. E.g. int, float, double, char,
Boolean
Static(Early) Binding The identification at compile time of which version of a
polymorphic method is being called. In order to do this the
compiler must identify the class of an object.
Dynamic (Late) Binding The identification at run time. When the class of an object
cannot be identified at compile time, so dynamic binding must
be used.
Advantage of OOPs over Procedure-oriented programming language
OOPs makes development and maintenance easier where as in Procedure-
oriented programming language it is not easy to manage if code grows as project
size grows.
OOP provides data hiding whereas in Procedure-oriented programming language a
global data can be accessed from anywhere.
OOP provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming
language.
Procedure Oriented Programming Object Oriented Programming
In POP, program is divided into small parts In OOP, program is divided into parts
called functions called objects
Importance is not given to data but to Importance is given to the data rather than
functions as well as sequence of actions to beprocedures or functions because it works as
done. a real world
POP follows Top Down approach. OOP follows Bottom Up approach.
POP does not have any access specifier. OOP has access specifiers Public, Private,
Protected, etc.
In POP, Data can move freely from function In OOP, objects can move and communicate
to function in the system. with each other through member functions.
To add new data and function in POP is not so OOP provides an easy way to add new data and
easy (Project grows) function.
POP does not have any proper way for hiding OOP provides Data Hiding so provides more
data so it is less secure security
In POP, Overloading is not possible. Overloading is possible in the form of Function
Overloading and Operator Overloading.
Most function uses Global data for sharing Data cannot move easily from function to
that can be accessed freely from function to function, it can be kept public or private so we
function in the system. can control the access of data.
Example of POP are: C, VB, Pascal, etc. Example OOP: C++, JAVA, VB.NET, C#.NET.
[Type here]
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.
[Type here]
JVM (JAVA VIRTUAL MACHINE)
Java is both compiled and an interpreted lang. First the java compiler translates source code
into the byte code instructions. In the next stage the java interpreter converts the byte code
instructions to machine code. This machine within the computer‘ is known as the “Java Virtual
Machine” or JVM.
The JVM can be thought as a mini operating system that forms a layer of abstraction where the
underlying hardware. The portability feature of the .class file helps in the execution of the prg
on any computer with the java virtual machine. This helps in implementing the “write once and
run anywhere” feature of java.
[Type here]
Steps to compile a java prg:
? Open Dos prompt
? Set the path Ex: path=c:\jdk1.2.2\bin and press enter key
? Move to your working directory/folder
? Compile the prg Ex: javac filename.java
? Run the prg Ex: java filename
[Type here]
Java Buzzwords or Features of Java:
No discussion of the genesis of Java is complete without a look at the Java buzzwords. Although
the fundamental forces that necessitated the invention of Java are portability and security, other
factors also played an important role in mol ding the final form of the language. The key
considerations were summed up by the Java team in the following list of buzzwords:
1. Simple: Java follows the syntax of C and Object Oriented principles of C++. It eliminates the
complexities of C and C++. Therefore, Java has been made simple.
[Type here]
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,
[Type here]
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.
[Type here]
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
The Scope and Lifetime of Variables:
All of the variables used till now have been declared at the start of the main( ) method. However,
Java allows variables to be declared within any block. A block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope.
Most other computer languages define two general categories of scopes: global and local.
The scope defined by a method begins with its opening curly brace.
Objects declared in the outer scope will be visible to code within the inner scope. However, the
reverse is not true. Objects declared within the inner scope will not be visible outside it.
To understand the effect of nested scopes, consider the following program:
// demonstrate block scope. if(x == 10)
class Scope { // start new scope
{ int y = 20; // known only to this block
public static void main(String args[])
{ // x and y both known here.
int x; // code within main System.out.print("x and y:" +x+ " " + y);
x = 10; x = y * 2;
[Type here]
} }
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
{
[Type here]
public static void main(String args[]) {
double r;
r=ToolBox.min(1.0,2.0);
} }
Life and scope of parameter variable:
The life time of a parameter variable is the entire body of the method
• A parameter variable behaves like a local variable that is defined at the Start of the method
Class variables:
Variables that are declared with the keyword static are called as class variables
Life of class variables: Class variables exists for the entire execution of the java program
Scope of class variables: The scope can be public
class StaticData
{
static int a=10,b=20; //Access these variables through class name, because of static.
}
class StaticDemo
{
public static void main(String args[])
{
int sum=StaticData.a+StaticData.b;
System.out.println("sum is"+sum);
} }
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;
[Type here]
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.
[Type here]
Java Naming conventions
Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method etc. But, it is not forced to follow. So, it is known as
convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are
given according to java naming convention.
OPERATORS:
Operator is a Symbol. Java provides a rich set of operators as
[Type here]
The Bitwise Operators:
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; b = 13;
now in binary format they will be as follows: a = 0011 1100
Binary Left Shift Operator: << (left shift) b = 0000 1101
It is moved left by the number of bits specified by the right operand. -----------------
a&b = 0000 1100
Example: A << 2 will give 240 which is 1111 0000
a|b = 0011 1101
Binary Right Shift Operator: >> (right shift) a^b = 0011 0001
It is moved right by the number of bits specified by the right operand. ~a = 1100 0011
Example: A >> 2 will give 15 which is 1111
Shift right zero fill operator : >>> (zero fill right shift)
It is moved right by the number of bits specified by the right operand and shifted values
are filled up with zeros.
Example: A >>>2 will give 15 which is 0000 1111
[Type here]
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.
[Type here]
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);
}
}
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows:
First, all byte, short, and char values are promoted to int, as just described. Then, if one operand
is a long, the whole expression is promoted to long. If one operand is a float, the entire
expression is promoted to float. If any of the operands is double, the result is double.
Ex:
class Promote { double d = .1234;
public static void main(String args[]) { double result = (f * b) + (i / c) - (d * s);
byte b = 42; System.out.println((f * b) + " + " + (i / c) + "
char c = 'a'; - " + (d * s));
short s = 1024; System.out.println("result = " +
int i = 50000; result);
float f = 5.67f; }
}
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)
Ex: class WhileDemo
{
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.println("Count is: " + count);
count++;
}
}
}
Output: Count is:1 Count is:2..................Count is:10
do-while statement
The do-while loop always executes its body at least once, because its conditional expression is at
the bottom of the loop. Its syntax can be expressed as:
do
{
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are always
executed at least once and while terminates with semicolon.
Ex Program:
class DoWhileDemo
{
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
Output: Count is:1 Count is:2..................Count is:10
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often
refer to it as the "for loop" because of the way in which it repeatedly loops until a particular
condition is satisfied.
The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM
(R15)
Ex: class ForTick {
public static void main(String args[]) {
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}
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)
Unconditional Control Statements
Java supports the following types of unconditional control statements.
1. break:
it is used to break any loop control statement or any switch control statement.
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.print(i+" "); }
System.out.print(" Loop complete.");
}}
Output: 0 1 2 3 4 5 6 7 8 9 Loop complete.
2. continue
it is used to skip the current iteration.
// Using continue to skip the current iteration
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
if(i == 5) continue;
System.out.print(i+" ");
}
System.out.print(" Loop complete.");
}}
Output: 0 1 2 3 4 6 7 8 9 Loop complete.
3.goto:
The main drawback of goto statement in the c language is it decrease the readability of a
program to avoid that drawback. The goto in java is changed as goto break.
The syntax for the goto statement in java is:
Label:
{
Statements;
Break Label;
}
Example:
// Using break as a civilized form of
goto. class Break {
public static void main(String args[]) {
boolean t = true;
first:
{
second:
{
third:
{
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM
(R15)
System.out.println("Before the break.");
if(t) break second; // break out of second
block System.out.println("This won't
execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}}
Output:
Before the break.
This is after second block.
4. return:
The return control statement is used to jump the control from the called function to the calling
function.
Classes and Objects:
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical. A class in Java can
contain:
o fields
o methods
o constructors
o blocks
o nested class and interface
Declaring Member Variables
There are several kinds of variables:
• Member variables in a class—these are called fields.
• Variables in a method or block of code—these are called local variables.
• Variables in method declarations—these are called parameters.
Syntax to declare a class:
class <class_name>{
field;
method;
}
A class is declared by use of the class keyword
class classname type methodname2(parameter-list)
{ {
type instance-variable1; // body of method
type instance-variable2; }
// ... // ...
type instance-variableN; type methodnameN(parameter-list)
type methodname1(parameter-list) {
{ // body of method
// body of method }
} }
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM
(R15)
The data, or variables, defined within aExample:
class are called instance variables. TheClass demo { int x=1;; int y=2; float z=3;
code is contained within methods.void display()
Collectively, the methods and variables{
defined within a class are calledSystem.out.println(―values are:‖+x+--y+--z);
members of the class. Variables defined}
within a class are called instance}
variables.
OBJECTS:
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table,
car etc. It can be physical or logical (tangible and intangible). The example of intangible object is
banking system.
An object has three characteristics:
o state: represents data (value) of an object.
o behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
o identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
Object Definitions:
o Object is a real world entity.
o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class.
New keyword in Java
The new keyword is used to allocate memory at run time. All objects get memory in
Heap memory area.
Declaring Objects
When you create a class, you are creating a new data type. You can use this type to declare
objects of that type. However, obtaining objects of a class is a two-step process.
First, you must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that variable.
You can do this using the new operator.
Demo d1 = new demo( );
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM
(R15)
Object and Class Example: main within class
In this example, we have created a Student class that has two data members id and name. We are
creating the object of the Student class by new keyword and printing the objects value.
Here, we are creating main() method inside the class.
Student.java
class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Output:
0
null
Object and Class Example: main outside class
In real time development, we create classes and use it from another class. It is a better approach
than previous one. Let's see a simple example, where we are having main() method in another
class.
We can have multiple classes in different java files or single java file. If you define multiple
classes in a single java source file, it is a good idea to save the file name with the class name
which has main() method.
TestStudent1.java
class Student
{
int id;
String name;
}
class TestStudent1{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM
(R15)
Three Ways to initialize object
There are 3 ways to initialize object in java.
By reference variable
By method
By constructor
1) Object and Class Example: Initialization through reference
Initializing object simply means storing data into object. Let's see a simple example where
we are going to initialize object through reference variable.
TestStudent2.java
class Student{ TestStudent3.java
int id; class Student{
String name; int id;
} String name; }
class TestStudent2{ class TestStudent3{
public static void main(String args[]){ public static void main(String args[]) {
Student s1=new Student(); Student s1=new Student();
s1.id=101; Student s2=new Student();
s1.name="Sonoo"; s1.id=101; //Initializing object
System.out.println(s1.id+" "+s1.name);// s1.name="Sonoo";
printing members with a white space s2.id=102; //Initializing object
} } s2.name="Amit";
System.out.println(s1.id+" "+s1.name);
Output:
System.out.print(s2.id+" "+s2.name);
101 Sonoo
}}
We can also create multiple objects and
Output:
store information in it through reference
101 Sonoo
variable.
102 Amit
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.
TestStudent4.java
class Student{ public static void main(String args[]) {
int rollno; Student s1=new Student();
String name; Student s2=new Student();
void insertRecord(int r, String n) s1.insertRecord(111,"Karan");
{ rollno=r; s2.insertRecord(222,"Aryan");
name=n; s1.displayInformation();
} s2.displayInformation();
void displayInformation(){System.out.pr }}
intln(rollno+" "+name);}
Output:
}
111 Karan
class TestStudent4{
222Aryan
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];
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)
There are several motivations for modularizing a program with methods.
The divide and conquer approach makes program development more manageable.
Another motivation is reusability. That means using existing methods as building blocks
to create new programs.
A third motivation is to avoid repeating code in a program.
Packaging code as a method allows that code to be executed from several locations in a
program simply by calling the method
Procedure:
• 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, or void if the
method does not return a value.
• 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.
• The method body, enclosed between braces: the method's code, including the declaration
of local variables, goes here.
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 multi-word 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.
Parameter Passing:
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it
is known as call by value. The changes being done in the called method, is not affected in the
calling method.
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM
(R15)
Example of call by value in java
In case of call by value original value is not In case of call by reference original value is
changed. Let's take a simple example: changed if we made changes in the called
class Operation{ method. In this example we are passing
int data=50; object as a value. Example:
void change(int data){ data=data+100;//changes class Operation2{
will be in the local int data=50;
variable only void change(Operation2 op)
} { op.data=op.data+100;//changes will be
public static void main(String args[]){ Operation
in the instance variable
op=new Operation(); }
System.out.println("before change "+op.data); public static void main(String args[])
op.change(500); { Operation2 op=new Operation2();
System.out.println("after change "+op.data); System.out.print("before:"+op.data);
} op.change(op);//passing object
} System.out.println("after:"+op.data);
Output: before change 50 }}
after change 50 Output: before: 50
After: 150
Another Example: // Objects are passed by reference to achieve the concept of call-by-
reference in JAVA
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
*= 2;
/= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " +
ob.b); ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
} }
Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
JAVA PROGRAMMING UNIT-I III B.Tech. I SEM
(R15)
static : (constant / fixed)
It can be applied to data members, methods and some inner classes.
static data members :
1. static data members can be accessed by only static methods as well as non static.
2. static data members are not instance – specific. They are common to all objects of a
class. Therefore, they are known as class variables.
3. They are not destroyed between function calls.
4. They can be accessed directly with the class name. E.g., classname.variable_name;
5. For all objects of a class, only one copy of static members exists in memory and it
is shared by all objects. It is contrary to instance variables.
6. static variables are declared as static int x ;
static methods :
1. static method is a method whose definition is preceded by keyword static.
2. static methods can act upon only static variables.
3. static method can be called directly using class name without creating object.
4. The keyword “this” can‟ t be used inside a static method, as static members don‘ t belongs
to any particular object.
5. A static method can call only other static methods .
static block:
1. It is a piece of code enclosed in braces preceded by the keyword static.
2. static block is executed even before main() .
3. It is used to initialize some variables or any such things.
4. It can use only static variables & call only static methods.
The following example shows a class that has a static method, some static variables, and a
static initialization block:
// Demonstrate static variables, methods, and blocks: UseStatic.java
class UseStatic { Syntax:
static int a = 3; static int b; static
static void math(int x) { {
System.out.println("x = " + x); statements;
System.out.println("a = " + a); -------------
System.out.println("b = " + }
b);
} Output:
static { //Static block x=42
System.out.println("Staticblock initialized.");
b = a * 4; a=3
} b=12
public static void main(String args[]) {
math(42);
}}
To call a static method from outside its class, use following general form:
classname.method( )
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 = " +
static void callme() { StaticDemo.b);
System.out.println("a = " + a); }
} }
} Output:
class StaticByName { a = 42
b = 99
Concrete class: (real / actual)
Any class that can be instantiated is known as concrete class. All non-abstract class is nothing
but concrete classes.
Sno Constructor Method
1 Creates an instance of a class Group of statements
2 Cannot be abstract ,final,static,native or Can be final , abstract,static, native or
synchronized synchronized
3 NO return type not even void Will have all possible return types
including void
4 Has same that of a class Can be given any valid name
5 this keyword Refers another constructor this keyword refers to an instance of the
in the same class. class . cannot be used with static methods
6 Super keyword is used ot call constructor super calls the super class overridden
of super class method
7 By default no arguments are supplied to No default supply of arguments
constructor
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)
private void formatFullName()
{
this.fullName = String.format("%s %s", this.firstName, this.lastName);
}
Example 1:
class demo System.out.println("Values of x, y and z
{ are:"+x+" "+y+" "+z);
int x; }
int y; }
float z; class Demomain2
demo(int x,int y,int z) {
{ public static void main(String args[])
this.x=x; {
this.y=y; demo d1=new demo(1,2,3); // this is a call
this.z=z; for the above parameterized constructor
} d1.display();
void display() }}
{
Output: Values of x, y and z are:1 2 3.0
Example 2:
class ThisRef public static void main(String args[])
{ {
int age=40; ThisRef s=new ThisRef(20);
ThisRef(int age) System.out.print(s.age);
{ }
this.age = age; }
System.out.println(age); Op: 20
} 20 //without using this keyword 40
To differentiate between the local and instance variables we have used this keyword in
the constructor.
Garbage Collection
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects. To do so, we were using free() function in C
language and delete() in C++. But, in java it is performed automatically. So, java provides
better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM).
How can an object be unreferenced?
Object can be unreferenced using the following ways:
o By nulling the reference
o By assigning a reference to another
o By annonymous object
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)
Java Scanner Example to get input from console
Simple example of the Java Scanner class which reads the int, string & double value as an input:
import java.util.Scanner; String name=sc.next();
class ScannerTest System.out.println("Enter your fee");
{ double fee=sc.nextDouble();
public static void main(String args[]) System.out.println("Rollno:"+rollno+
{ " name:"+name+" fee:"+fee);
Scanner sc=new Scanner(System.in); sc.close();
System.out.println("Enter your rollno"); }
int rollno=sc.nextInt(); }
System.out.println("Enter your name");
Output:
Enter your rollno
111
Enter your name
Kalpana
Enter
450000
Rollno:111 name:Kalpana fee:450000
Strings:
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
Above code is same as: String s="javatpoint";
The java String is immutable i.e. it cannot be changed but a new instance is created. For
mutable class, you can use StringBuffer and StringBuilder class.
What is String in java
Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes.
For Example:
String s="welcome";
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
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 superclass.
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 It is a class that inherits some or all
classes 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. ISEM
Example:
Output:
Output:
MRCET UNIT-II JP NOTES II B.TECH. ISEM
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 theconstructor.
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. ISEM
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. ISEM
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. ISEM
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) void move()
difference in the data types of parameters. {
void add (int a,float b) System.out.println ("Parent can move");
void add (double a,double b) }
difference in the sequence of parameters. }
void swap (int a,char b) class Child extends Parent
void swap (char a,int b) {
void move()
//Dynamic polymorphism: Overloading
methods {
class Sample System.out.println ("Child can walk & run");
{ void add(int a,int b) }
{s }
System.out.println ("sum of two="+ (a+b)); class OverRide
} {
void add(int a,int b,int c) { public static void main(String args[])
System.out.println("sum of 3="+ {
(a+b+c)); Parent a = new Parent ( );
} Parent b = new Child (); // Animal reference
} but Dog object (Up casting)
class OverLoad a.move (); // runs method in Animal class
{ public static void main(String[] args) b.move (); //Runs method in Dog class
{ Sample s=new Sample ( ); }
s.add (20, 25); }
s.add (20, 25, 30); Output: Parent can move
} } Child can walk & run
Output: sum of two=45
Sun of three=75
MRCET UNIT-II JP NOTES II B.TECH. ISEM
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. ISEM
class
class A{}
B extends A{}
A a=new B();//upcasting
Example
In this example a reference is
created “Ref1” of type parent1.
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
int getRateOfInterest(){return 0;} be 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. ISEM
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. ISEM
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. ISEM
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. ISEM
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. ISEM
Save this file as , and put it in a directory called MyPack. Next, compile the file. Make sure that
the resulting .class file is also in the MyPack directory. Executing the AccountBalance class,
using the following command line:
java bal.AccountBalance
Remember, we should be in the directory above MyPack when you execute this command, or to
have your CLASSPATH environmental variable set appropriately.
AccountBalance is now part of the package MyPack. This means that it cannot be executed
by itself. That is, you cannot use this command line:
java AccountBalance (AccountBalance must be qualified with its package name. )
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. ISEM
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. ISEM
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. ISEM
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 Interfaces are created by putting the
keyword class prior to classname. keyword 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.
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.
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 your friends on Facebook using browser.
and 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.
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable
code. This means that a single program can perform two or more tasks simultaneously. For
instance, a text editor can format text at the same time that it is printing, as long as these two
actions are being performed by two separate threads.
Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking
handles the details.
Multitasking threads require less overhead than multitasking processes. Processes are
heavyweight tasks that require their own separate address spaces. Inter process communication
is expensive and limited. Context switching from one process to another is also costly.
Threads, on the other hand, are lightweight. They share the same address space and
cooperatively share the same heavyweight process. Inter thread communication is inexpensive,
and context switching from one thread to the next is low cost.
Multithreading enables you to write very efficient programs that make maximum use of the
CPU, because idle time can be kept to a minimum. This is especially important for the
interactive, networked environment in which Java operates, because idle time is common.
Benefits of Multithreading
1. Enables programmers to do multiple things at one time
2. Programmers can divide a long program into threads and execute them in parallel which
eventually increases the speed of the program execution
3. Improved performance and concurrency
4.
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.
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();
MRCET UNIT-III JP III B.TCH. I SEM
NOTES
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
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.
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
closing the files and database, stopping threads and performing clean up operations are
written in this stop method.
Dead/Destroyed:
public void destroy (): This method is executed only once when the applet is terminated
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
}
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.
PASSING PARAMETERS TO AN APPLET
Java applet has the feature of retrieving the parameter values passed from the html page. So, you
can pass the parameters from your html page to the applet embedded in your page. The param
tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. The
applet has to call the getParameter() method supplied by the java.applet.Applet parent class.
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) {
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
ComponentAdapter Listener Interface
ContainerAdapter ComponentListener
FocusAdapter ContainerListener
KeyAdapter FocusListener
MouseAdapter KeyListener
MouseMotionAdapter MouseListener
WindowAdapter MouseMotionListener
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)); }
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
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
MRCET UNIT-IV JP III B.TCH. I SEM
NOTES
Java FileInputStream class
It is useful to read data from a file in the form of sequence of bytes. It is possible to read
data from a text file using FileInputStream. i.e.,
FileInputStream fin= new FileInputStream(“myfile.txt”);
To read data from
the file is, ch=fin.read();
When there is no more data available to read then it returns -1.
The Output Stream is used to send data to the monitor. i.e., PrintStream, for displaying the data we can
use System.out.
System.out.print(ch);
Reading data from a text file using FileInputStream:
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[])
{
FileInputStream fin=new
FileInputStream("myfile.txt"); System.out.println(“File
Contents:”); int ch; while((ch=fin.read())!=-1)
{
System.out.println((char)ch);
}
fin.close();
}
}
Output: javac ReadFile.java
java ReadFile
UNIT V: GUI Programming with Java – AWT class hierarchy, component, container,
panel, window, frame, graphics.
AWT controls: Labels, button, text field, check box, check box groups, choices, lists,
scrollbars, and graphics.
Layout Manager – Layout manager types: border, grid and flow.
Swing – Introduction, limitations of AWT, Swing vs AWT.
Container
The Container is a component in AWT that can contain other components like buttons, textfields,
labels etc. The classes that extend Container class are known as container such as Frame, Dialog
and Panel.
Layout Managers
Every container has a default layout manager; therefore, when you make a new container, it
comes with a LayoutManager object of the appropriate type. You can install a new layout
manager at any time with the setLayout() method. Below, we set the layout manager of a
container to a BorderLayout:
setLayout ( new BorderLayout( ) );
Every component determines three important pieces of information used by the layout manager
in placing and sizing it: a minimum size, a maximum size, and a preferred size.
These are reported by the getMinimumSize(), getMaximumSize(), and getPreferredSize(),
methods of Component, respectively.
When a layout manager is called to arrange its components, it is working within a fixed area. It
usually begins by looking at its container's dimensions, and the preferred or minimum sizes of
the child components.
Layout manager types
Flow Layout
FlowLayout is a simple layout manager that tries to arrange components with their preferred
sizes, from left to right and top to bottom in the display. A FlowLayout can have a specified
justification of LEFT, CENTER, or RIGHT, and a fixed horizontal and vertical padding.
By default, a flow layout uses CENTER justification, meaning that all components are centered
within the area allotted to them. FlowLayout is the default for Panel components like Applet.
The following applet adds five buttons to the default FlowLayout.
import java.awt.*;
/*
<applet code="Flow" width="500" height="500">
</applet>
*/
public class Flow extends java.applet.Applet
{
public void init()
{
//Default for Applet is FlowLayout
add( new Button("One") );
add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}
If the applet is small enough, some of the buttons spill over to a second or third row.
Grid Layout
GridLayout arranges components into regularly spaced rows and columns. The components
are arbitrarily resized to fit in the resulting areas; their minimum and preferred sizes are
consequently ignored.
GridLayout is most useful for arranging very regular, identically sized objects and for
allocating space for Panels to hold other layouts in each region of the container.
GridLayout takes the number of rows and columns in its constructor. If you subsequently
give it too many objects to manage, it adds extra columns to make the objects fit. You can also
set the number of rows or columns to zero, which means that you don't care how many elements
the layout manager packs in that dimension.
For example, GridLayout(2,0) requests a layout with two rows and an unlimited number of
columns; if you put ten components into this layout, you'll get two rows of five columns each.
The following applet sets a GridLayout with three rows and two columns as its layout
manager;
import java.awt.*;
/*
<applet code="Grid" width="500"
height="500"> </applet>
*/
public class Grid extends java.applet.Applet
{
public void init()
{
setLayout( new GridLayout( 3, 2 ));
add( new Button("One") );
add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}
The five buttons are laid out, in order, from left to right, top to bottom, with one empty spot.
Border Layout
BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical
locations: "North," "South," "East," "West," and "Center," possibly with some padding between.
BorderLayout is the default layout for Window and Frame objects. Because each
component is associated with a direction, BorderLayout can manage at most five components; it
squashes or stretches those components to fit its constraints.
When we add a component to a border layout, we need to specify both the component and the
position at which to add it. To do so, we use an overloaded version of the add() method that
takes an additional argument as a constraint.
The following applet sets a BorderLayout layout and adds our five buttons again, named for
their locations;
import 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" );
}
}
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.
\{ 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>
*/
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);
Page 17
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.*; /*
SWINGS
Swing is a set of classes that provides more powerful and flexible components than are
possible with the AWT. Swing is a GUI widget toolkit for Java. It is part of Oracle's Java
Foundation Classes (JFC) that is used to create window-based applications. It is built on
the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
In addition to the familiar components, such as buttons, check boxes, and labels, Swing
supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Even familiar components such as buttons have more capabilities in Swing. For example, a
button may have both an image and a text string associated with it. Also, the image can be
changed as the state of the button changes.
Unlike AWT components, Swing components are not implemented by platform specific
code. Instead, they are written entirely in Java and, therefore, are platform-independent.
The term lightweight is used to describe such elements.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
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.
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>
*/
UNIT-V
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
[Type here] [Type here] [Type here]
*/
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-
[Type here] [Type here] [Type 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());
}
}
[Type here] [Type here] [Type here]
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.
Exploring java.lang
java.lang package is the default package in Java and it is automatically
imported into all Java programs.
There are many classes available in java.lang package. Some of the important
classes are :
Number Math
Object Runtime
String
StringBuffer
System Thread
ThreadGroup
Throwable
Cloneable
Comparable
Runnable
Java uses simple data types like int,float,double,char etc…But these simple types are not objects.
Java provides Wrapper classes to convert simple types to objects.
Wrapper classes:In java all are objects except the primitive data types.If we want to access
primitive data types as objects we should wrap the primitive data types within a class.
There are 6 Wrapper classes.They are the sub classes of Number.They are...
Double,Float,Byte,Short,Integer and Long. Double d=12.33;
f=12.33f;
Runtime :
Memory Management:
Even though Java provides automatic garbage collection,sometimes you will want to know
how large the object heap is and how much of it is left. To obtain these values, use totalMemory()
and freeMemory() methods defined in Runtime class.
Object :
clone() method is used to create a duplicate copy of the object on which it is called.Only
classes that implements Cloneable interface can be cloned. Cloneable interface defines no
members and it is a marker interface.
Thread :
Runnable :
This is an interface that must be implemented by any class that will initiate a separate
thread of execution.Runnable defines one abstract method called,run(), which is the entry point to
the thread.
ThreadGroup :