Java Unit-1
Java Unit-1
UNIT - I
Need for oop paradigm
The Structure of OOP is similar to that of a community that consists of agents interacting
with each other. These agents are also called as objects. An agent or an object plays a role of
providing a service or performing an action and other members of this community can access
these services or actions.
JAVA PROGRAMMING MRITS
Consider an eg, raju and ravi are good friends who live in two different cities far from each
other. If Raju wants to send flowers to ravi, he can request his local florist ‘hari’ to send
flowers to ravi by giving all the information along with the address.
Hari works as an agent (or object) who performs the task of satisfying raju’s request. Hari
then performs a set of operations or methods to satisfy the request which is actually hidden
from ravi, Hari forwards a message to ravi’s local florist. Then local florist asks a delivery
person to deliver those flowers to ravi.
The Agent Identity class defines agent identity. An instance of this class uniquely identifies
an agent. Agents use this information to identify the agents with whom they are interested in
collaborating.
The Agent Host class defines the agent host. An instance of this class keeps track of every
agent executing in the system. It works with other hosts in order to transfer agents.
The Agent class defines the agent. An instance of this class exists for each agent executing
on a given agenthost.
OOP uses an approach of treating a real world agent as an object.
Object-oriented programming organizes a program around its data (that is, objects) and a set
of well-defined interfaces to that data.
An object-oriented program can be characterized as data controlling access to code by
switching the controlling entity to data.
Responsibility
A fundamental concept in OOP is to describe behavior in terms of responsibilities. A
Request to perform an action denotes the desired result. An object can use any technique
that helps in obtaining the desired result and this process will not have any interference from
other object. The abstraction level will be increased when a problem is evaluated in terms of
responsibilities. The objects will thus become independent from each other which will help
in solving complex problems. An Object has a collection of responsibilities related with it
which is termed as ‘protocol’.
The Operation of a traditional program depends on how it acts on data structures. Whereas
an OOP operates by requesting data structure to perform a service.
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 ”content".
When a message is passed to an agent (or object) that is capable of performing an action, then that
action will be initiated in OOP. An object which receives the message sent is called ‘receiver’.
When a receiver accepts a message, it means that the receiver has accepted the responsibility of
processing the requested action. It then performs a method as a response to the message in order to
fulfill the request.
JAVA PROGRAMMING MRITS
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 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
run Fast getBackground
getFinalData compareTo setX
isEmpty
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.
JAVA PROGRAMMING MRITS
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.
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.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ in either of
these:
1. Number of parameters
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters
For example:
add(int, int)
add(int, float)
3. Sequence of Data type of parameters
For example:
add(int, float)
add(float, int)
Invalid case of method overloading:
If two methods have same name, same parameters and have different return type, then this is
not a valid method overloading example. This will throw compilation error.
int add(int, int)
float add(int, int)
Example 1: Overloading – Different Number of parameters in argument list
This example shows how method overloading is done by having different number of parameters
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);}
public void disp(char c, int num)
{
System.out.println(c + ""+num);}}
class Sample
{
JAVA PROGRAMMING MRITS
classHuman{
//Overridden method
publicvoid eat()
{
System.out.println("Human is eating");}}
classBoyextendsHuman{
//Overriding method
publicvoid eat(){
System.out.println("Boy is eating");}
publicstaticvoid main(String args[]){
Boy obj =newBoy();
//This will call the child class version of eat()
obj.eat();}}
Output:
Boyis eating
Advantage of method overriding
The main advantage of method overriding is that the class can give its own specific
implementation to a inherited method without even modifying the parent class code.
Rules of method overriding in Java
1. Argument list: The argument list of overriding method (method of child class) must match
the Overridden method (the method of parent class). The data types of the arguments and their
sequence should exactly match.
2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive
than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is
public then the overriding method (child class method ) cannot have private, protected and default
Access modifier, because all of these three access modifiers are more restrictive than public.
For e.g. This is not allowed as child class disp method is more restrictive(protected) than base
class(public)
class MyBaseClass{
public void disp()
{
System.out.println("Parent class method");}}
class MyChildClass extends MyBaseClass{
protected void disp(){
System.out.println("Child class method");}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();}}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot reduce the visibility of the inherited method from MyBaseClass
JAVA PROGRAMMING MRITS
However this is perfectly valid scenario as public is less restrictive than protected. Same access
modifier is also a valid one.
class MyBaseClass{
protected void disp()
{
System.out.println("Parent class method");}}
class MyChildClass extends MyBaseClass{
public void disp(){
System.out.println("Child class
method");} public static void main( String
args[]) { MyChildClass obj = new
MyChildClass(); obj.disp(); } }
Output:
Child class method
3. private, static and final methods cannot be overridden as they are local to the class.
However static methods can be re-declared in the sub class, in this case the sub-class method would
act differently and will have nothing to do with the same static method of parent class.
4. Overriding method (method of child class) can throw unchecked exceptions, regardless of
whether the overridden method (method of parent class) throws any exception or not. However the
overriding method should not throw checked exceptions that are new or broader than the ones
declared by the overridden method. We will discuss this in detail with example in the upcoming
tutorial.
5. Binding of overridden methods happen at runtime which is known as dynamic binding.
6. If a class is extending an abstract class or implementing an interface then it has to override
all the abstract methods unless the class itself is a abstract class.
Classes
Class − A class can be defined as a template/blueprint that describes the behavior/state that the
object of its type support.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well
as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
In object-oriented terms, we say that your bicycleis an instance of the class of objects known as
bicycles. 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 .javafile
Each field and method has an access level:
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
Each class has one of two possible access levels:
(package): class objects can only be declared and manipulated by code in this package
Public: class objects can be declared and manipulated by code in any package.
Object: Object-oriented programming involves inheritance. In Java, all classes (built-in or user-
defined) are (implicitly) subclasses of Object. Using an array of Object in the List class allows any
JAVA PROGRAMMING MRITS
kind of Object (an instance of any class) to be stored in the list. However, primitive types (int, char,
etc) cannot be stored in the list.
A method should be made static when it does not access any of the non-static fields of the
class, and does not call any non-static methods.
Java class objects exhibit the properties and behaviors defined by its class. A class can
contain fields and methods to describe the behavior of an object. Current states of a class‘s
corresponding object are stored in the object‘s instance variables.
Creating aclass:
A class is created in the following way
Class <class name>
{ Member variables;
Methods; }
Example
public class Dog {
String breed;
int age;
String color;
void barking() { }
void hungry() { }
void sleeping() { } }
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed. A local variable cannot be defined with
"static" keyword.
Instance variables − Instance variables are variables within a class but outside any method.
These variables are initialized when the class is instantiated. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword. A variable which is declared as static is called static
variable. It cannot be local. You can create a single copy of static variable and share among
all the instances of the class. Memory allocation for static variable happens only once when
the class is loaded in the memory.
Example
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
} }//end of class
Constructors
When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
JAVA PROGRAMMING MRITS
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
Following is an example of a constructor −
Example
public class Puppy {
public Puppy() { }
public Puppy(String name) {
// This constructor has one parameter, name. } }
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object
is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
Declaration − A variable declaration with a variable name with an object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Following is an example of creating an object −
Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name ); }
public static void main(String []args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" ); } }
If we compile and run the above program, then it will produce the following result −
Output
Passed Name is: tommy
Class Variables – Static Fields
We use class variables also known as Static fields when we want to share characteristics
across all objects within a class. When you declare a field to be static, only a single instance of the
associated variable is created common to all the objects of that class. Hence when one object
changes the value of a class variable, it affects all objects of the class. We can access a class variable
by using the name of the class, and not necessarily using a reference to an individual object within
the class. Static variables can be accessed even though no objects of that class exist. It is declared
using static keyword.
Class Methods – Static Methods
Class methods, similar to Class variables can be invoked without having an instance of the
class. Class methods are often used to provide global functions for Java programs. For example,
methods in the java.lang.Math package are class methods. You cannot call non- static methods from
inside a static method.
Accessing Instance Variables and Methods
Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path −
JAVA PROGRAMMING MRITS
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.
JAVA PROGRAMMING MRITS
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 in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java:
compile-time polymorphism
runtime polymorphism
We can perform polymorphism in java by method overloading and method overriding.
If you overload a static method in Java, it is the example of compile time polymorphism.
Here, we will focus on runtime polymorphism in java.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
class B extends A{}
A a=new B(); //upcasting
For upcasting, we can use the reference variable of class type or an interface type.
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, the subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
class Bike {
void run() {
System.out.println("running"); } }
class Splendor extends Bike {
void run() {
System.out.println("running safely with 60km"); }
JAVA PROGRAMMING MRITS
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.
Abstraction:
Abstraction in Java or Object oriented programming is a way to segregate 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 subclass.
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 runtime.
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.
Now the exception is caught and processed.
Increased understanding
Ease of maintenance
Ease of evolution
Object orientation eases maintenance by the use of encapsulation and information hiding
Definitions of some of the key concepts in Object Oriented Programming(OOP).
Term Definition
Abstract A user-defined data type, including both attributes (its state)
Data Type andmethods (its behavior). An object oriented language will
include means to define new types (see class) and create
instances of those classes (see object). It will also provide a
number of primitive types.
Aggregation Objects that are made up of other objects are known as aggregations. The
relationship is generally of one of two types:
Inheritance The derivation of one class from another so that the attributes and
methods of one class are part of the definition of another 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.
Derived classes are always ‗a kind of‘ their base classes. Derived
classes generally add to the attributes and/or behaviour of the base
class. Inheritance is one form of object-oriented code reuse. E.g.
Both Motorbikes and Cars are kinds of MotorVehicles and therefore
share some common attributes and behaviour but may add their own
that are unique to that particulartype.
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: it simply describes the behaviour expected of a
particular type of object, it doesn‘t so how that behaviour should
beimplemented.
Member Variable See attribute
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High-performance
Distributed
Dynamic
Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
Assuming that you have some programming experience, you
will not find Java hard to master. If you already understand the basic concepts of object-oriented
programming, learning Java will be even easier. Best of all, if you are an experienced C++
programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax
and many of the object-oriented features ofC++.
Robust
The multiplatform environment of the Web places extraordinary demands on a program,
because the program must execute reliably in a variety of systems. Thus, the ability to create robust
programs was given a high priority in the design of Java.
JAVA PROGRAMMING MRITS
To gain reliability, Java restricts you in a few key areas, to force you to find your
mistakes early in program development. At the same time, Java frees you from having to worry
about many of the most common causes of programming errors. Because Java is a strictly typed
language, it checks your code at compile time. However, it also checks your code at run time. To
better understand how Java is robust, consider two of the main reasons for program failure:
memory management mistakes and mishandled exceptional conditions (that is, run-time errors).
Memory management can be a difficult, tedious task in traditional programming environments.
For example, in C/C++, the programmer must manually allocate and free all dynamic memory.
This sometimes leads to problems, because programmers will either forget to free memory that
has been previously allocated or, worse, try to free some memory that another part of their code
is still using. Java virtually eliminates these problems by managing memory allocation and
deallocation for you. (In fact, deallocation is completely automatic, because Java provides
garbage collection for unused objects.) Exceptional conditions in traditional environments often
arise in situations such as division by zero or ―file not found, and they must be managed with
clumsy and hard-to-read constructs. Java helps in this area by providing object-oriented
exception handling. In a well-written Java program, all run-time errors can—and should—be
managed by your program.
Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you to
write programs that do many things simultaneously.
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 designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was write once; run anywhere, anytime,
forever. To a great extent, this goal was accomplished.
Distributed
Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing
a file. The original version of Java (Oak) included features for intra address- space messaging.
JAVA PROGRAMMING MRITS
This allowed objects on two different computers to execute procedures remotely. Java revived
these interfaces in a package called Remote Method Invocation (RMI). This feature brings an
unparalleled level of abstraction to client/server programming.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is
used to verify and resolve accesses to objects at run time. This makes it possible to dynamically
link code in a safe and expedient manner. This is crucial to the robustness of the applet
environment, in which small fragments of byte code may be dynamically updated on a running
system.
Security
Every time that you download a ―normal program, you are risking a viral infection.
Even so, most users still worried about the possibility of infecting their systems with a virus. In
addition to viruses, another type of malicious program exists that must be guarded against. This
type of program can gather private information, such as credit card numbers, bank account
balances, and passwords, by searching the contents of
your
computer‘slocalfilesystem.Javaanswersbothoftheseconcernsbyprovidingafirewall between a
networked application and your computer. When you use a Java- compatible Web browser, you
can safely download Java applets without fear of viral infection or malicious intent. Java
achieves this protection by confining a Java program to the Java execution environment and not
allowing it access to other parts of the computer.
Portability
Many types of computers and operating systems are in use throughout the world—and
many are connected to the Internet. For programs to be dynamically downloaded to all the
various types of platforms connected to the Internet, some means of generating portable
executable code is needed. As you will soon see, the same mechanism that helps ensure security
also helps create portability.
Data Types:
Java defines eight simple types of data: byte, short, int, long, char, float, double, and
Boolean. These can be put in four groups:
Integers this group includes byte, short, int, and long, which are for whole valued
signed numbers.
Floating-point numbers this group includes float and double, which represent numbers
with fractional precision.
Characters this group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean this group includes Boolean, which is a special type for representing true/false
values.
Integers:
The width and ranges of these integer types vary widely, as shown in this table:
JAVA PROGRAMMING MRITS
Floating-point:
There are two kinds of floating-point types, float and double, which represent single- and
double-precision numbers, respectively. Their width and ranges are shown here:
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] ...];
The type is one of Java‘s atomic types, or the name of a class or interface. The identifier is the
name of the variable. You can initialize the variable by specifying an equal sign and a value. To
declare more than one variable of the specified type, use a comma- separated list.
Here are several examples of variable declarations of various types. Note that some include an
initialization.
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'.
can be nested. For example, each time you create a block of code, you are creating a new, nested
scope. When this occurs, the outer scope encloses the inner scope. This means thatobjects
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.
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start newscope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + "" + y); x = y * 2;}
y = 100;
// Error! y not known here
// x is still known here.
System.out.println("x is " + x);}}
As the comments indicate, the variable x is declared at the start of main( )‘s scope and is
accessible to all subsequent code within main( ). Within theifblock, y is declared. Since a block
defines a scope, y is only visible to other code within its block. This is why outside of its block,
the line y = 100; is commented out. If you remove the leading comment symbol, a compile-time
error will occur, because y is not visible outside of its block. Within theifblock, x can be used
because code within a block (that is, a nested scope) has access to variables declared by an
enclosing scope.
Here is another important point to remember: variables are created when their scope is entered
and destroyed when their scope is left. This means that a variable will not hold its value once it
has gone out of scope. Therefore, variables declared within a method will not hold their values
between calls to that method. Also, a variable declared within a block will lose its value when
the block is left. Thus, the lifetime of a variable is confined to its scope. If a variable declaration
includes an initializer, then that variable will be reinitialized each time the block in which it is
declared is entered.
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);}}}
The output generated by this program is shown here:
y is:-1
y is now: 100 y is:-1
y is now: 100 y is:-1
y is now: 100
As you can see, y is always reinitialized to –1 each time the inner for loop is entered. Even
though it is subsequently assigned the value 100, this value is lost. One last point: Although
blocks can be nested, you cannot declare a variable to have the same name as one in an outer
scope.
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. For example, the following declares an array
named monthwith the type ―array of int:
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. newis 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];
Here, type specifies the type of data being allocated, size specifies the number of elements in the
array, and array-var is the array variable that is linked to the array. That is, to use new toallocate
an array, you must specify the type and number of elements to allocate. The elements in the array
allocated by new will automatically be initialized to zero.
This example allocates a 12-element array of integers and links them to month
month = new int[12];
After this statement executes, month will refer to an array of 12 integers. Further, all elements in
the array will be initialized to zero.
Another way to declare an array in single step is
type arr-name=new type[size];
Arrays can be initialized when they are declared. The process is much the same as that used to
initialize the simple types. An array initializer is a list of comma-separated expressions
JAVA PROGRAMMING MRITS
surrounded by curly braces. The commas separate the values of the array elements. The array
will automatically be created large enough to hold the number of elements you specify in the
array initializer. There is no need to use new.
For example, to store the number of days in each month, we do as follows
// An improved version of the previous program.
class AutoArray
{
public static void main(String args[])
{
int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
System.out.println(month[3] + " days."+month[2]);
} }
When you run this program, in the output it prints the number of days in April. As mentioned,
Java array indexes start with zero, so the number of days in April is month[3] or 30.
Here is one more example that uses a one-dimensional array. It finds the average of a set of
numbers.
// Average an array of values.
class Average
{
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
doubleresult = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5); } }
Output:
Average is12.3
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. To declare a
multidimensional array variable, specify each additional index using another set of square
brackets. For example, the following declares a two-dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. program :
// Demonstrate a two-dimensional array.
class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++)
{
JAVA PROGRAMMING MRITS
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + "");
System.out.println();}}}
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions
separately. We can allocate the second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
we can creates a two dimensional array in which the sizes of the second dimension are unequal.
// Manually allocate differing size second dimensions.
class TwoDAgain
{
public static void main(String args[])
{
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++)
{
twoD[i][j] = k; k++;
}
for(i=0; i<4; i++)
{
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + "");
System.out.println();}}}
JAVA PROGRAMMING MRITS
Output:
0
12
345
678
We can create a three-dimensional array where first index specifies the number of tables, second
one number o0f rows and the third number of columns.
// Demonstrate a three-dimensional array.
class threeDMatrix
{
public static void main(String args[])
{
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j
*k; for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
for(k=0; k<5; k++) System.out.print(threeD[i][j][k] + ""); System.out.println();
}
System.out.println();}}}
Output:
0000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24
Here, the square brackets follow the type specifier, and not the name of the array variable. For
example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
Output
012
3456
Operators:
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result. The operators in the following table are listed according to
precedence order. The closer to the top of the table an operator appears, the higher its
precedence. Operators with higher precedence are evaluated before operators with relatively
lower precedence. Operators on the same line have equal precedence. When operators of equal
precedence appear in the same expression, a rule must govern which is evaluated first. All binary
operators except for the assignment operators are evaluated from left to right; assignment
operators are evaluated right to left.
JAVA PROGRAMMING MRITS
Operator Precedence
Operators Precedence
Postfix expr++, expr--
Unary ++expr --expr +expr –expr ~ !
multiplicative */%
additive +-
Shift <<>>>>>
relational <><= >=instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
In general-purpose programming, certain operators tend to appear more frequently than theirs;
for example, the assignment operator "=" is far more common than the unsigned right shift
operator ">>>".
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
if(value1 == value2)
System.out.println("value1 == value2");
The data type of the value returned by an expression depends on the elements used in the
expression. The expression a= 0 returns an int because the assignment operator returns a value of
the same data type as its left-hand operand; in this case, cadence is an int. As you can see from
JAVA PROGRAMMING MRITS
the other expressions, an expression can return other types of values as well, such as boolean or
String.
For example, the following expression gives different results, depending on whether you perform
the addition or the division operation first:
x + y / 100 // ambiguous
You can specify exactly how an expression will be evaluated using balanced parenthesis rewrite
the expression as
(x + y) / 100 // unambiguous, recommended
If you don't explicitly indicate the order for the operations to be performed, the order is
determined by the precedence assigned to the operators in use within the expression. Operators
that have a higher precedence get evaluated first. For example, the division operator has a higher
precedence than does the addition operator. Therefore, the following two statements
areequivalent:
x + y / 100
x + (y / 100) // unambiguous, recommended
When writing compound expressions, be explicit and indicate with parentheses which operators
should be evaluated first.
Control Statements:
IF Statement
The general form of the ifstatement:
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 booleanvalue.
If the condition is true, then statement1 is executed. Otherwise,statement2 is executed.
IF –ELSE Statement
The general form of the ifstatement:
if (condition) statement1;
else statement2;
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates
to false.
void applyBrakes()
{
if (isMoving)
{
currentSpeed--;}
else
{
System.err.println("The bicycle has already stopped!");}}
JAVA PROGRAMMING MRITS
Output:
"August"
The body of a switch statement is known as a switch block. Any statement immediately
contained by the switch block may be labeled with one or more case or default labels. The switch
statement evaluates its expression and executes the appropriate case.
Looping statements:
to false. Using the while statement to print the values from 1 through 10 can be accomplished as
in the following program:
class WhileDemo
{
public static void main(String[] args)
{
int count = 1; while (count < 11)
{
System.out.println("Count is: " + count); count++; } } }
do-while statement
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 leastonce.
Program:
class DoWhileDemo
{
public static void main(String[] args){ int count = 1;
do {
System.out.println("Count is: " + count); count++;
} while (count <= 11);}}
In the loop body, you can use the loop variable you created rather than using an indexed
array element.
It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements }
Declaration − The newly declared block variable, is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
Expression − This evaluates to the array you need to loop through. The expression can
be an array variable or method call that returns an array.
Example
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(","); } } }
Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,
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.
Program:
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); } }
Output:
Conversion of int to byte. i and b 257 1
Conversion of double to int. d and i 323.142 323
Conversion of double to byte. d and b
323.14267 byte b = 50;
b = (byte)(b * 2);
JAVA PROGRAMMING MRITS
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.
Declaring Member Variables
There are several kinds of variables:
Member variables in a class—these are calledfields.
Variables in a method or block of code—these are called localvariables.
Variables in method declarations—these are calledparameters.
A class is declared by use of the class keyword
class classname
{
type instance-variable1; type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method}
type methodname2(parameter-list)
{
// body of method}
// ...
type methodnameN(parameter-list)
{
// body of method}}
The data, or variables, defined within a class are called instance variables. The code is contained
within methods. Collectively, the methods and variables defined within a class are called
members of the class. In most classes, the instance variables are acted upon and accessed by the
methods defined for that class. Variables defined within a class are called instance variables
because each instance of the class (that is, each object of the class) contains its own copy of these
variables. Thus, the data for one object is separate and unique from the data for another.
Example:
Classdemo
{
int x=1;
int y=2;
floatz=3;
void display()
{
System.out.println(“values ofx,yand zare:”+x+””+y+””+z);}}
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. The new
JAVA PROGRAMMING MRITS
operator dynamically allocates(allocates at run time) memory for an object and returns a
reference to it. This reference is, more or less, the address in memory of the object allocated by
new.
This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated.
In the above programs to declare an object of type demo:
Demo d1 = new demo();
This statement combines the two steps just described. It can be rewritten like this to show each
step more clearly:
demo d1; // declare reference to object
d1 = new demo(); // allocate a demo object
The first line declares d1 as a reference to an object of type demo. After this line executes, d1
contains the value null, which indicates that it does not yet point to an actual object. Any attempt
to use d1 at this point will result in a compile-time error. The next line allocates an actual object
and assigns a reference to it to d1.After the second line executes; you can use d1 as if it were a
demo object. But in reality, d1 simply holds the memory address of the actual demo object. T
Constructors:
A class contains constructors that are invoked to create objects from the class blueprint.
Constructor declarations look like method declarations—except that they use the name of the
class and have no return type. A constructor initializes an object immediately upon creation.
Constructors can be default or parameterized constructors.
A default constructor is called when an instance is created for a class.
Example Class demo
{
int x; int y; float
z; demo()
{
x=1, y=2, z=3;}
void display()
{
System.out.println(“valuesof x,yand zare:”+x+””+y+””+z); } }
Class demomain
{
Public static void main(String args[])
{
demo d1=new demo(); // this is a call for the above default
constructor d1.display(); } }
Parameterized constructor:
Class demo
{
int x; int y; float z;
demo(int x1,int y1,int z1)
{
x=x1;y=y1; z=z1; }
JAVA PROGRAMMING MRITS
void display()
{
System.out.println(“valuesof x,yand zare:”+x+””+y+””+z); } }
Class demomain
{
Public static void main(String args[])
{
demo d1=new demo(1,2,3); // this is a call for the above parameterized constructor
d1.display(); } }
This Keyword:
Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the thiskeyword. thiscan 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. You can use this
anywhere a reference to an object of the current class‘ type is permitted. Example:
Class demo
{
int x; int y; float z;
demo(int x,int y,int z)
{
this.x=x; this.y=y; this.z=z;}
void display()
{
System.out.println(“valuesof x,yand zare:”+x+””+y+””+z); } }
Class demomain
{
Public static void main(String args[]) {
demo d1=new demo(1,2,3); // this is a call for the above parameterized
constructor d1.display(); } }
Output:
Values of x, y and z are:1 2 3
To differentiate between the local and instance variables we have used this keyword int the
constructor.
Garbage Collection:
Since objects are dynamically allocated by using the new operator, objects are destroyed
and their memory released for later reallocation. In some languages, such as C++, dynamically
allocated objects must be manually released by use of a delete operator. Java takes a different
approach; ithandles deallocation for you automatically. The technique that accomplishes this is
called garbage collection. It works like this: when no references to an object exist, that object is
assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There
is no explicit need to destroy objects as in C++.
The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed. For example,
if an object is holding some non-Java resource such as a file handle or window character font,
then you might want to make sure these resources are freed before an object is destroyed. To
JAVA PROGRAMMING MRITS
handle such situations, Java provides a mechanism called finalization. By using finalization, you
can define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls
that method whenever it is about to recycle an object of that class. Inside the finalize( ) method
you will specify those actions that must be performed before an object is destroyed. The garbage
collector runs periodically, checking for objects that are no longer referenced by any running
state or indirectly through other referenced objects. Right before an asset is freed, the Java run
time calls the finalize( ) method on the object. The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
OverloadingMethods:
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. Suppose that you have a class that can
use calligraphy to draw various types of data (strings, integers, and so on) and that contains a
method for drawing each data type. It is cumbersome to use a new name for each method—for
example, drawString, drawInteger, drawFloat, and so on. 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.
public class DataArtist {
...
public void draw(String s) {...}
public void draw(int i) {...}
public void draw(double f) {...}
public void draw(int i, double f) {...}}
Overloaded methods are differentiated by the number and the type of the arguments
passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique
methods because they require different argument types. 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.
Overloading Constructors:
We can overload constructor methods
class Box {
double width;
doubleheight;
double depth;
JAVA PROGRAMMING MRITS
Parameter Passing:
In general, there are two ways that a computer language can pass an argument to a
subroutine.The first way is call-by-value.In this method copies the value of an argument into the
formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine
have no effect on the argument.
The second way an argument can be passed is call-by-reference. In this method, a reference to an
argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this
reference is used to access the actual argument specified in the call. This means that changes
made to the parameter will affect the argument used to call the subroutine.
Java uses both approaches, depending upon what is passed.
In Java, when you pass a simple type to a method, it is passed by value. Thus, what occurs to the
parameter that receives the argument has no effect outside the method. For example, consider the
following program:
// Simple types are passed by value.
class Test {
void meth(int i, int j)
{ i *= 2;
j /=2;}}
class CallByValue
{public static void main(String args[])
{Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + "" + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + "" + b);}}
Output
a and b before call: 15 20
a and b after call: 15 20
we can see, the operations that occur inside meth( ) have no effect on the values of a and
bused in the call; their values here did not change to 30 and 10.
When we pass an object to a method, the situation changes dramatically, because objects are
passed by reference. Keep in mind that when you create a variable of a class type,you are only
creating a reference to an object. Thus, when you pass this reference to a method, the parameter
that receives it will refer to the same object as that referred to by the argument. This effectively
means that objects are passed to methods by use ofcall-by-reference. Changes to the object inside
the method do affect the object used as an argument.
Example:
JAVA PROGRAMMING MRITS
Recursion:
Java supports recursion. Recursion is the process of defining something in terms of itself.
As it relates to Java programming, recursion is the attribute that allows a method to call itself. A
method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number.
The factorial of a number N is the product of all the whole numbers between 1 and N. For
example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use of a
recursive method:
// A simple example of recursion.
class Factorial
{
// this is a recursive function
int fact(int n)
{
int result;
if(n==1)
return 1;
else
result = fact(n-1) * n;
return result;}}
class Recursion {
public static void main(String args[])
{ Factorial f = new Factorial();
JAVA PROGRAMMING MRITS
String Handling:
Strings, which are widely used in Java programming, are a sequence of characters. In
Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
There are two ways to create String object:
By string literal
By new keyword
By string literal
The most direct way to create a string is to write −
String greeting = "Hello world!";
By new keyword
String s=new String("Welcome");//creates two objects and one reference
variable
EXAMPLE
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);}}
Output
java
strings
example
when you create a String object, you are creating a string that cannot be changed. That is,
once a String object has been created, you cannot change the characters that comprise that
string.The difference is that each time you need an altered version of an existing string, a new
String object is created that contains the modifications. The original string is left unchanged.
This approach is used because fixed, immutable strings can be implemented more efficiently
than changeable ones.
For those cases in which a modifiable string is desired, there is a companion class to String
called StringBuffer, whose objects contain strings that can be modified after they arecreated.
JAVA PROGRAMMING MRITS
Both the String and StringBuffer classes are defined in java.lang. Thus, they are available to all
programs automatically. Both are declared final, which means that neither of these classes may
be subclassed.
Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
String Length:
The length of a string is the number of characters that it contains. To obtain this value, call the
length( ) method.
int length( )
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
It prints 3 as the output since the string as 3 characters.
charAt( )
To extract a single character at specified index from a String, you can refer directly to an
individual character via the charAt( ) method. It has this general form:
JAVA PROGRAMMING MRITS
String comparision
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
equals()
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String object. It returns true if
the strings contain the same characters in the same order, and false otherwise. The comparison is
case-sensitive.
To perform a comparison that ignores case differences, call equalsIgnoreCase( ).When it
compares two strings, it considers A-Z to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object.
==
It compares the memory location of string.
compareTo()
To know whether two strings are identical. For sorting applications, you need to know
which is less than, equal to, or greater than the next. A string is less than another if it comes
before the other in dictionary order. A string isgreater than another if it comes after the other in
dictionary order. The String methodcompareTo( ) serves this purpose. It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String.
Equals:
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //true
System.out.println(s1.equals(s4)); //false
} }
class Teststringcomparison2{
public static void main(String args[]){
JAVA PROGRAMMING MRITS
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equalsIgnoreCase(s2)); //true
} }
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2); //true (because both refer to same instance)
System.out.println(s1==s3); //false(because s3 refers to instance created in nonpool)
} }
indexOf()
The String class provides two methods that allow you to search a string for a specified
character or substring:indexOf( ) Searches for the first occurrence of a character orsubstring.
lastIndexOf( )
Searches for the last occurrence of a character orsubstring.
substring( )
we can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a copy of
the substring that begins at startIndex and runs to the end of the invokingstring.
The second form of substring( ) allows you to specify both the beginning and ending index of
the substring:
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The
string returned contains all the characters from the beginning index, up to,but not including, the
ending index.
replace( )
The replace( ) method replaces all occurrences of one character in the invoking string with
another character. It has the following general form:
String replace(char original, char replacement)
StringBuffer Constructors:
StringBuffer defines these three constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
The default constructor (the one with no parameters) reserves room for 16 characters
without reallocation.
The second version accepts an integer argument that explicitly sets the size of the buffer.
JAVA PROGRAMMING MRITS
The third version accepts a String argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without reallocation.
StringBuffer allocates room for 16 additional characters when no specific buffer length is
requested, because reallocation is a costly process in terms of time.
Also, frequent reallocations can fragment memory. By allocating room for a few extra
characters, StringBuffer reduces the number of reallocations that take place.
ensureCapacity( )
If you want to preallocate room for a certain number of characters after a StringBuffer
has been constructed, you can use ensureCapacity( ) to set the size of the buffer.
ensureCapacity( ) has this general form:
void ensureCapacity(int capacity)
Here, capacity specifies the size of the buffer
append( )
The append( ) method concatenates the string representation of any other type of data to
the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types
and for Object. Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
String.valueOf( ) is called for each parameter to obtain its string representation.
insert( )
The insert( ) method inserts one string into
another. StringBuffer insert(int index,
String str) StringBuffer insert(int index,
char ch) StringBuffer insert(int index,
Object obj)
Here, index specifies the index at which point the string will be inserted into the
invokingStringBuffer object
reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
This method returns the reversed object on which it was called.
replace( )
To replaces one set of characters with another set inside a StringBuffer object. Its
signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the
substring at startIndex through endIndex–1 is replaced.
Inheritance
Hierarchical Abstractions
Example:
Inheritance:
Inheritance is a Java language feature, used to model hierarchical abstraction. Inheritance
means taking a class (called the base class) and defining a new class (called the subclass) by
specializing the state and behaviors of the base class.
Subclasses specialize the behaviors of their base class
The subclasses inherit the state and behaviors of their base class
They can have additional state and behaviors
Inheritance is mainly used for code reusability and to reduce the complexity of the program.
Base Class:
A class that is being inherited is known as Base class Forex:
Classx
{
Void method ();}
class y extends x
{}
In the above example the class x is known as the base class.When we create an object for the
base class then that object is known as base class object.
Sub class:
The class that is inheriting the base class Is known as sub class.In the example above
since class y is inheriting the class x, class y is known as the subclass to class x.
Definition of substitutability:
Assigning derived class object to parent class reference variables is known as
substitutability.
The concept of substitutability is fundamental to many of the powerful software
development techniques in object oriented programming.
The idea is that the type given in a declaration of variable doesn‘t have to match the type
associated with value the variable is holding.
It can also be used through interfaces.
FORMS OF INHERITANCE:
The choices between inheritance and overriding, subclass and subtypes, mean that inheritance
can be used in a variety of different ways and for different purposes.
Many of these types of inheritance are given their own special names. We will describe some of
these specialized forms of inheritance.
Specialization
Specification
Construction
Generalization or Extension
Limitation
Variance
Specialization Inheritance:By far the most common form of inheritance is for specialization . A
good example is the Java hierarchy of Graphical components in the AWT:
Component
Label
JAVA PROGRAMMING MRITS
Button
TextComponent
TextArea
TextField
CheckBox
Scrollbar
Each child class overrides a method inherited from the parent in order to specialize the class in
someway.
Specification Inheritance:
If the parent class is abstract, we often say that it is providing a specification for the
child class, and therefore it is specification inheritance (a variety of specialization inheritance).
Example: Java Event Listeners, ActionListener, MouseListener, and so on specify behavior, but
must besubclassed.
Inheritance for Construction:
If the parent class is used as a source for behavior, but the child class has no is-a
relationship to the parent, then we say the child class is using inheritance for construction.
An example might be subclassing the idea of a Set from an existing List class.
Generally not a good idea, since it can break the principle of substitutability, but
nevertheless sometimes found in practice. (More often in dynamically typed languages,
such as Smalltalk).
Inheritance for Generalization or Extension:
If a child class generalizes or extends the parent class by providing more functionality,
and overrides any method, we call it inheritance for generalization.
The child class doesn't change anything inherited from the parent, it simply adds new
features is called extension.
An example is Java Properties inheriting form Hashtable.
Inheritance for Limitation:
Ifachildclassoverridesamethodinheritedfromtheparentinawaythatmakesit unusable (for
example, issues an error message), then we call it inheritanceforlimitation. For example,
youhave an existing List data type that allows items to be inserted ateither end,
andyouoverridemethodsallowinginsertionatoneendinordertocreateaStack.
Generally not a good idea, since it breaks the idea of substitution. But again, it is
sometimes found in practice.
Inheritance for Variance:
Two or more classes that seem to be related, but its not clear who should be the parent
and who should be the child.
Example: Mouse and TouchPad and JoyStick
Better solution, abstract out common parts to new parent class, and use subclassing for
specialization.
Summary of Forms of Inheritance:
Specialization:The child class is a special case of the parent class; in other words, the child class
is a subtype of the parent class.
Specification:The parent class defines behavior that is implemented in the child class but not in
the parent class.
JAVA PROGRAMMING MRITS
Construction:The child class makes use of the behavior provided by the parent class, but is not
a subtype of the parent class.
Generalization:The child class modifies or overrides some of the methods of the parent class.
Extension:The child class adds new functionality to the parent class, but does not change any
inherited behavior.
Limitation:The child class restricts the use of some of the behavior inherited from the parent
class.
Variance:The child class and parent class are variants of each other, and the class- subclass
relationship is arbitrary.
Combination:The child class inherits features from more than one parent class. This is multiple
inheritance.
BENEFITS OF INHERITANCE:
Software Reuse
Code Sharing
Improved Reliability
Consistency of Interface
Rapid Prototyping
Polymorphism
Information Hiding
COSTS OF INHERITANCE:
Execution speed
Program size
Message Passing Overhead
Program Complexity
This does not mean you should not use inheritance, but rather than you must understand
the benefits, and weigh the benefits against the costs.
TYPES OF INHERITANCE:
void display()
{ a=
0;
System.out.println(a);}}
class y extends x
{
int b;
void show()
{ B=
1;
System.out.println(b);}}
class show_main
{
Public static void main(String args[])
{
y y1=new y(); y1.display();
y1.show();}}
Output:
0
1
Since the class y is inheriting class x, it is able to access the members of class x. Hence
the method display() can be invoked by the instance of the class y.
Output
0
1
2
Since class z is inheriting class y which is in turn a sub class of the class x, indirectly z can
access the members of class x.
Hence the instance of class z can access the display () method in class x, the show () method in
class y.
Problems:
In java multiple level inheritances is not possible easily. We have to make use of a
concept called interfaces to achieve it.
Access Specifers:
The different access specifiers used are
Public
Private
Protected
Default
Private members can be accessed only within the class in which they aredeclared.
Protected members can be accessed inside the class in which they are declared and also in
the sub classes in the same package and sub classes in the otherpackages.
Default members are accessed by the methods in their own class and in the sub classes of
the samepackage.
Public members can be accessedanywhere.
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 classconstructor.
The second is used to access a member of the super class that has been hidden by a
member of a subclass
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 .
Thesecondformofsuperactslikea―thiskeyword. Thedifferencebetweenthisandsuper is that ―this is
used to refer the current object where as the super is used to refer to the super class.
JAVA PROGRAMMING MRITS
Example:
class Animal {
Animal(){
System.out.println("animal is created");} }
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created"); } }
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog(); }}
Output:
animal is created
dog is created
Output:
Compile Time Error
Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with
100kmph");} public static void main(String args[]){a
Honda honda= new Honda();
honda.run();}}
What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final
variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
JAVA PROGRAMMING MRITS
Any class that contains one or more abstract methods must also be declared abstract..
Such types of classes are known as abstract classes.
Abstract classes can contain both abstract and non-abstract methods. Let us consider the
following example:
abstract class A
{
abstract void callme(); void call()
{
System.out.println(“HELLO”);}}
class B extends A
{
Void callme()
{
System.out.println(“GOOD MORNING”);}}
class abstractdemo
{
Public static void main(String args[])
{
B b=new B();
b.callme();
b.call();}}
Output:
GOOD MORNING HELLO