Professional Documents
Culture Documents
JAVA Programming Language - Lang - Shayan Roy PDF
JAVA Programming Language - Lang - Shayan Roy PDF
Buy ( );
Sell ( );
Repair ( ); Paint ( ); Move ( );
As you can understand, if we execute these methods,
then one or some of the attribute values will be
accessed or changed. For example, to Buy ( ) or Sell (
) the chair, its price attribute will be changed. To
Repair ( ) a chair, we may change its dimensions,
weight or material. To Paint ( ) a chair its color
property will be changed. To Move ( ) a chair, we
change its location.
THE CONCEPT OF CLASS
If some objects are found to have a similar set of
attributes and a similar set of methods, then these
objects can be grouped together into a class. A class
is a collection of declaration of the attribute
variables and the definition of the methods. Once
the class has been defined, we can create as many
objects of a class as we need just as we declare
variables of a data type. In the light of a class, an
object can also be defined as an instance or
occurrence of a class.
We may declare the CHAIR class as having declared
variables like height, width, breadth, colour, material,
weight, price and location and defined the methods
like Buy ( ), Sell ( ), Repair ( ), Paint ( ) and Move ( ).
Now, in order to declare a new object Chair4, all we
need to do is write the following statement
CHAIR Chair4; (Equivalent to int n;)
And the job is done.
Each object has its own space in memory where it can
store its own attribute set, because each object is
expected to have a unique attribute set of its own.
However, there is no need to store separate copies of
the methods for each individual objects, as the coding
for the methods need not be changed for each object.
Writing the actual program in an object oriented
system is fairly easy. All we have to do is to execute
the appropriate methods with the appropriate object.
For example, if we want to sell Chair2, then we may
write
Chair2.Sell ( );
And if we want to move Chair3 then we may write
Chair3.Move ( );
PROGRAMMING IN JAVA
Now it is the time to write the first program in Java.
The following is the code for a program for adding
two numbers. We are assuming that you have some
knowledge of the C and C++ language.
import java.io.*;
class Ayan {
public static void main(String args[]) throws IOException {
int a, b, c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter first number : ); a = Integer.parseInt(br.readLine());
System.out.print(\n\tEnter second number : ); b = Integer.parseInt(br.readLine());
c = a + b; System.out.print(\n\tThe sum of +a+ and +b+ is : +c); }
}
Let us explain this program line by line.
===================================
import java.io.*;
int a, b, c;
This is the normal variable declaration statement.
===================================
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
javac Ayan.java
The compilation process creates a new file called
Ayan.class, which is the byte code of the program
(equivalent to the executable code in C / C++).
HOW TO EXECUTE THIS PROGRAM
Staying within the Command Prompt, type the
following command:
java Ayan
WRAPPER CLASSES
Because Java is a strictly object oriented programming
language, the data type themselves are created as
objects. We have to consider that all the data types that
we have mentioned here are themselves the objects of
some class. The classes from which the data type
themselves are declared as objects are called Wrapper
classes. All such classes are part of the java.lang
package.
The Number wrapper class is the super class for six
other wrapper classes that deals with all the numeric
data types. These classes are Double, Float, Byte,
Short, Integer and Long. In the previous example
where we have shown that the integer value is taken
using the Integer.parseInt ( ) method, we can say that
the parseInt ( ) method is a member method of the
Integer wrapper class. Similarly, the new Float ( ) and
new Double ( ) expression are calling the constructors
of the Float and Double wrapper classes respectively,
where the floatValue ( ) and doubleValue ( ) methods
are the member methods of these classes.
ARRAYS IN JAVA
Only the declaration procedure is different in
comparison to C / C++
Single dimensional array:
int arr[] = new int[5];
Two dimensional matrix
int m[][] = new int[2][3];
CONSTRUCTORS
A constructor is a member method of any class whose
objective is to initialize the attributes of an object of
that class. A constructor has the following special
properties:
1. The name of the constructor is exactly the same as
the name of the class
2. Although it is a method, a constructor does not have
any return type. Not even the void type.
3. A constructor method need not be called separately
using an object of that class. The constructor is called
automatically whenever an object of that class is
created.
4. Depending upon its use, a constructor may or may
not receive any argument.
The following program demonstrates the use of
different types of constructors:
import java.io.*;
class ABC {
char a;
int b;
double c;
ABC() // DEFAULT CONSTRUCTOR, TAKES NO ARGUMENT {
a = F;
b = 10;
c = 3.1248;
}
ABC(char a1, int b1, double c1) // PARAMETERIZED CONSTRUCTOR, TAKES
ARGUMENTS {
a = a1; b = b1; c = c1;
}
ABC(ABC obj) // COPY CONSTRUCTOR, TAKES AN ENTIRE OBJECT AS
ARGUMENT {
a = obj.a; b = obj.b; c = obj.c;
}
void output() {
System.out.print(\n\n\tCHAR : +a); System.out.print(\n\tINT : +b);
System.out.print(\n\tDOUBLE : +c);
}
}
class Ayan {
public static void main(String args[]) {
ABC obj1 = new ABC(); // CALLING DEFAULT CONSTRUCTOR
ABC obj2 = new ABC(D, 25, 36.997); // CALLING PARAMETERIZED
CONSTRUCTOR ABC obj3 = new ABC(obj2); // CALLING COPY CONSTRUCTOR
obj1.output(); obj2.output(); obj3.output();
}
}
INHERITANCE
Inheritance is an integral feature of any object oriented
programming language. Inheritance is the process of
creating a new class out of an existing class. In Java
terminology, the existing class is called the super
class and the newly created class is called sub class.
Due to inheritance the subclass may inherit some or all
the features of the base class.
Whenever there is a need to create a new class, the
programmer has two choices. Either he/she can create
the class, its attributes and the methods out of scratch,
that may take a lot of labour, time (and thereby,
money). Another option is to look out in the collection
of already created classed and trying to find out a class
that most closely matches the attribute set and the
method set of the class that is required to be created. If
such a class can be found, then all that is needed to be
done is to create the new class (sub class) out of the
already created class (super class) and directly inherit
the common attributes and the methods, and add only
those attributes and methods which are needed
specifically for the derived class. This may save a lot
of labour, time and money.
In a sense, inheritance encourages the concept of code
reuse, that is, to reuse the existing code to create new
code units.
Inheritance also gives birth to another pair of terms
called generalization and specialization. In a class
hierarchy, where a set of super class gives birth to a set
of sub classes in a top down manner, the more we
climb upwards this inheritance tree, the fewer amounts
of details would be visible. The top levels of the class
hierarchy always present those features which are
common to all the underlying classes. This is called
generalization. On the other if we descend the
inheritance tree, we would reach the sub classes that
keeps adding newer features. So, more specific
features will be visible in the bottom levels of the class
hierarchy. This is called specialization.
TYPES OF INHERITANCE SUPPORTED IN
JAVA Java supports the three types of inheritance
depicted here.
Single Inheritance
Only one sub class is created out of only one super
class.
A
B
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
Hierarchical Inheritance
The following program shows how we can create a
new class using hierarchical inheritance.
import java.io.*;
class A
{
int a;
A(int a1) {
} a = a1;
void outputA()
{ System.out.print(\n\tFirst number : +a); }
}
class B extends A
{ int b;
B(int a1, int b1)
{ super(a1);
b = b1;
}void outputB()
{
} System.out.print(\n\tSecond number : +b); }
class C extends A
{
int c;
C(int a1, int c1) {
super(a1); c = c1;
}
void outputC() {
System.out.print(\n\tThird number : +c);
}}
class InheritanceTest {
public static void main(String args[]) { B obj1 = new B(10, 20);
C obj2 = new C(100, 200);
obj1.outputA(); obj1.outputB();
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com obj2.outputA(); obj2.outputC(); }
}
METHOD OVERRIDING
This program also stands as an example of what is
called method overriding. We have already discussed
method overloading in the earlier chapter, which
means redefining the same method having the same
name with different signature and different body.
Method overriding is the technique of redefining a
method of the super class in the body of a sub class
derived from that super class.
import java.io.*;
// METHOD OVERRIDING
class A
{
void greetings() {
System.out.print(\n\tHi!!); }
}
class B extends A
{
void greetings() // ONLY THE BODY IS DIFFERENT {
System.out.print(\n\tHello!!); }
}
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
class InheritanceTest {
public static void main(String args[]) {
A obj1 = new A(); B obj2 = new B();
obj1.greetings(); // CALLING THE METHOD OF CLASS A obj2.greetings(); //
CALLING THE METHOD OF CLASS B }
}
md mypack
Step 2: Change to the newly created subdirectory.
cd mypack
Step 3: Within this subdirectory, create a new file with
.java extension.
edit IO.java
Step 4: The very first statement inside this new file
would be
package mypack;
import java.io.*;
interface A
{
void methodA();
}
interface B extends A
{
void methodB(); // INTERFACE B INHERITS THE METHOD OF INTERFACE A,
ALSO DECLARES
} // A METHOD OF ITS OWN.
class C implements B // CLASS C HAS BOTH THE METHODS AVAILABLE {
public void methodA() // METHOD OF INTERFACE A OVERRIDEN HERE {
System.out.print(\n\tInterface As method.); }
public void methodB() // METHOD OF INTERFACE B OVERRIDEN HERE {
System.out.print(\n\tInterface Bs method.); }
public void methodC() // THIS IS CLASS CS OWN METHOD {
System.out.print(\n\tClass Cs method.); }
}
class Ayan {
public static void main(String args[]) {
C obj = new C();
obj.methodA(); obj.methodB(); obj.methodC();
}
}
If a new class is created from an interface, the
implements keyword is used. If a new interface is
created from another interface, the extends keyword
is used.
Teacher of Computer Science and Software Technology
1/1A, Ananda Chatterjee Lane, Kolkata 700003. Phone: 033 2554 6084. Email:
ayankumarchatterjee@yahoo.com
EXCEPTION HANDLING
The term exception is a short form for any runtime
error that is caused during the execution of the
program and that disturbs the normal flow of
execution. When an error occurs in a Java method, it is
handled by the Java Runtime Environment in the
following manner.
Every time a runtime error occurs in a Java method, it
becomes the responsibility of the method to detect the
type of exception that has occurred. To help this job,
the java.lang package contains a group of classes that
are known as the exception classes. Each one of these
classes defines one particular type of exceptional
situation. When the Java method determines what type
of exception has occurred (by consulting the library of
the exception classes) it creates an object of the
particular type of exception class and delivers that
object to the runtime system. This process is called
throwing the exception. After the exception object
has been thrown, the Java method stops the execution
of the program at the statement where the exception
has occurred.
The runtime system, as a response to the throwing of
the exception object, begins to search the same
program to find out an exception handler. A piece of
code is termed an exception handler if it receives, as
its argument, an object of the same exception class as
was thrown to the runtime system. If such an
exception handler is found, the control is transferred to
the exception handler. The exception handler contains
some simple, user friendly error messages that tell the
user what error has occurred and how to deal with it so
that it does not occur the next time.
If the runtime system does not find an appropriate
exception handler, then the runtime system displays a
default error message. In both the cases, the program
that has encountered the exception is prevented to
continue beyond the point where the exception has
been encountered.
HOW TO IMPLEMENT EXCEPTION
HANDLING IN JAVA
There are three blocks of code that are used in Java to
implement the concept of exception handling.
try block: This is a block of code where we include
all those statements that we expect to cause some
exception.
try {
Java statements; }
import java.io.*;
class ExceptionTest
{
public static void main(String args[]) {
int a, b, c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print(\n\tEnter first number : ); a = Integer.parseInt(br.readLine());
System.out.print(\n\tEnter second number : ); b = Integer.parseInt(br.readLine());
try {
c = a / b;
System.out.print(\n\tThe result of division : +c);
}
catch(ArithmeticException e)
{
System.out.print(\n\tCannot divide a number by zero.);
}
}
catch(IOException e)
{
System.out.print(\n\tThis is an Input Output Exception.); }
catch(NumberFormatException e)
{
System.out.print(\n\tThis is a Number Format Exception.);
}finally
{
System.out.print(\n\tFinally block, will be executed anyway.); }
}
}
MULTITHREADING
A thread can be considered as a part of a process that
can be executed independently by the CPU. Any
running program is called a process. Normally, a CPU
can execute one process at a time. In case of
multiprogramming, the CPU divides its execution time
into several time slots and executes one process in one
time slot. A process may have to be executed for many
time slots before it completes its execution.
The concept of multithreading goes one step further
and divides the CPU time slots in such a way that the
CPU can execute different threads of the programs in
different time slots. A process can be broken down
into several threads. In Java terminology, such a
process is called a multithreaded process. Otherwise
the process is called a single threaded process.
An example of multithreading is the ability of a
program like the Internet Explorer to allow the user to
view a webpage, print that webpage on the printer and
download a file, all seemingly at the same time. These
tasks of the same process appear to be running
concurrently, because each task has been assigned to a
new thread. The main advantage of multithreading is
the speed of execution of the program.
DIFFERENCE BETWEEN THREAD AND
PROCESS
The main difference between a thread and a process is
that a thread cannot exist on its own. A thread can only
exist by being part of a process. The end user cannot
execute the thread directly without running the process
in which this thread is a part. On the other hand, a
process may consist of one or more threads, depending
upon which the process is termed as single threaded or
multithreaded process, respectively.
HOW IS MULTITHREADING IMPLEMENTED
There are two different ways to implement
multithreading in a Java program. The first one is to
create the class by extending it form the Thread class.
class MyThread extends Thread {
: :
}
STRING HANDLING
In C or C++ programming languages, a character array
is called a string. There are some fundamental
difference between an array of any other data type and
that of a character data type.A null character (\0) is
automatically appended at the end of the character
string, which does not happen in the case of an array
of any other data type. Additionally, while trying to
make input or output with a character array, the entire
array can be manipulated at once, but to do the same
with an array of any other data type, we must have to
use loops.
In Java, there is absolutely no difference between an
array of any other data type and an array of character
data type. In order to deal with strings in the same way
as done in C or C++, Java provides a class called
String (S is capital) which is part of the java.lang
system package.
There are several different ways to declare and
initialize an object of the string class.
1. As a normal object of the String class, using the
parameterized constructor of the class.
{
String s;
int i;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(\n\tEnter a string : ); s = br.readLine();
for(i = 0 ; i <= s.length() ; i++)
System.out.print(\n\t+s.substring(0, i));
// STARTING FROM THE 0 INDEX, EXTRACTING i NUMBER OF CHARACTERS
}}
javac Calculator.java