Java R19 - UNIT-3
Java R19 - UNIT-3
3.1 ARRAYS Let’s review: Obtaining an array is a two-step process. First, you must declare a variable of the desired
array type. Second, you must allocate the memory that will hold the array, using new, and assign it to
3.1.1 Introduction: the array variable. Thus, in Java all arrays are dynamically allocated.
An array is a group of like-typed variables that are referred to by a common name. Arrays of any type A program that creates an array of the number of days in each month:
can be created and may have one or more dimensions. A specific element in an array is accessed by its // Demonstrate a one-dimensional array.
index. Arrays offer a convenient means of grouping related information. class Array {
public static void main(String args[]) {
3.1.2 Declaration and Initialization of Arrays int month_days[];
month_days = new int[12];
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30;
create an array variable of the desired type. month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31;
month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31;
Declaration: System.out.println("April has " + month_days[3] + " days.");
}
The general form of a one-dimensional array declaration is }
type var-name[ ]; When you run this program, 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_days[3] or 30.
Here, type declares the element type (also called the base type) of the array. The element type
determines the data type of each element that comprises the array. Thus, the element type for the array Initialization:
determines what type of data the array will hold.
Arrays can be initialized when they are declared. The process is much the same as that used to initialize
For example, the following declares an array named month_days with the type “array of int”: the simple types. An array initializer is a list of comma-separated expressions surrounded by curly
int month_days[]; 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
Although this declaration establishes the fact that month_days is an array variable, no array actually new.
exists. In fact, the value of month_days is set to null, which represents an array with no value. To link For example, to store the number of days in each month, the following code creates an initialized array
month_days with an actual, physical array of integers, you must allocate one using new and assign it to of integers:
month_days. new is a special operator that allocates memory.
// An improved version of the previous program.
The general form of new as it applies to one-dimensional arrays appears as follows: class AutoArray {
array-var = new type [size]; public static void main(String args[ ]) {
int month_days[ ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
Here, type specifies the type of data being allocated, size specifies the number of elements in the array, or
and array-var is the array variable that is linked to the array. That is, to use new to allocate an array, you int month_days[ ] = new int [ ] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //you may use new
must specify the type and number of elements to allocate. The elements in the array allocated by new System.out.println("April has " + month_days[3] + " days.");
will automatically be initialized to zero (for numeric types), false (for boolean), or null. }
}
This example allocates a 12-element array of integers and links them to month_days: When you run this program, you see the same output as that generated by the previous version.
month_days = new int[12]; Java strictly checks to make sure you do not accidentally try to store or reference values outside of the
range of the array. The Java run-time system will check to be sure that all array indexes are in the
After this statement executes, month_days will refer to an array of 12 integers. Further, all elements in correct range. For example, the run-time system will check the value of each index into month_days to
the array will be initialized to zero. make sure that it is between 0 and 11 inclusive. If you try to access elements outside the range of the
array (negative numbers or numbers greater than the length of the array), you will cause a run-time
error.
Page 1 Page 2
JAVA PROGRAMMING JAVA PROGRAMMING
The operator new which is a keyword, allocates memory for storing the array elements.
For example with the following declaration
int [] num = new int [4];
The compiler allocates 4 memory spaces each equal to 4 bytes for storing the int type values of elements
of array numbers. When an array is created as above, elements of the array are automatically initialized
to 0 by the compiler.
int num [ ] = {10,20,30,40};
Page 3 Page 4
JAVA PROGRAMMING JAVA PROGRAMMING
The number of elements (size) of the array may change during the execution of the program. This
feature is unlike C and C++ wherein the array once declared is of fixed size, that is, the number of
elements cannot be changed.
In Java, however, you may change the number of elements by dynamically retaining the array name. In
this process, the old array is destroyed along with the values of elements.
Example:
int [ ] num = new int [5];
num = new int [10];
Searching an array for a value is often needed. Let us consider the example of searching for your name
among the reserved seats in a retail reservation chart, air travel reservation chart, searching for a book in
a library, and so on.
Two methods are employed: linear search and binary search for sorted arrays.
Sorting of arrays if often needed in many applications of arrays. For example, in the preparation of
examination results, you may require to arrange the entries in order of grades acquired by students or in
alphabetical order in dictionary style. The arrays may be sorted in ascending or descending order.
Several methods are used for sorting the arrays that include the following:
1. Bubble sort
2. Selection sort
3. Sorting by insertion method
4. Quick sort
3.1.10 Class Arrays
The package java.util defines the class arrays with static methods for general processes that are carried
out on arrays such as sorting an array for full length of the array or for part of an array, binary search of
an array for the full array or part of array, for comparing two arrays if they are equal or not, for filling a
part of the full array with elements having a specified value, and for copying an array to another array.
The sort method of arrays class is based on quick sort technique.
The methods are applicable to all primitive types as well as to class objects.
Page 5 Page 6
JAVA PROGRAMMING JAVA PROGRAMMING
Page 7 Page 8
JAVA PROGRAMMING JAVA PROGRAMMING
Page 9 Page 10
JAVA PROGRAMMING JAVA PROGRAMMING
Whenever we inherit the base class members into derived class, when we creates an object of Single Inheritance: It means when a base class acquired the properties of super class
derived class, JVM always creates the memory space for base class members first and later memory class Animal
space will be created for derived class members. {
void eat()
Page 11 Page 12
JAVA PROGRAMMING JAVA PROGRAMMING
{ Class Y extends X
System.out.println("eating..."); {
} public void methodY()
} {
class Dog extends Animal System.out.println("class Y method");
{ }
void bark() }
{ Class Z extends Y
System.out.println("barking..."); {
} public void methodZ()
} {
class TestInheritance System.out.println("class Z method");
{ }
public static void main(String args[]) public static void main(String args[])
{ {
Dog d=new Dog(); Z obj = new Z();
d.bark(); obj.methodX(); //calling grand parent class method
d.eat(); obj.methodY(); //calling parent class method
} obj.methodZ(); //calling local method
} }
In this example base class is Dog and super class is Animal: }
Example:
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived
class A
class, thereby making this derived class the base class for the new class. As you can see in below flow
{
diagram C is subclass or child class of B and B is a child class of A
public void methodA()
Example:
{
Class X System.out.println("method of Class A");
{ }
public void methodX() }
{ class B extends A
System.out.println("Class X method"); {
}
public void methodB()
} {
Page 13 Page 14
JAVA PROGRAMMING JAVA PROGRAMMING
System.out.println("method of Class B"); Note: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often
} leads to problems in the hierarchy. This results in unwanted complexity when further extending the
} class.
class C extends A
{ Hybrid Inheritance in Java
public void methodC() A hybrid inheritance is a combination of more than one types of inheritance. For example when class A
{ and B extends class C & another class D extends class A then this is a hybrid inheritance, because it is a
System.out.println("method of Class C"); combination of single and hierarchical inheritance.
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
} The diagram is just for the representation, since multiple inheritance is not possible in java
class JavaExample
{ class C
public static void main(String args[]) {
{ public void disp()
B obj1 = new B(); {
C obj2 = new C(); System.out.println("C");
D obj3 = new D(); }
} }
}
Output: class A extends C
method of Class A {
method of Class A public void disp()
method of Class A {
System.out.println("A");
Multiple Inheritance: }
}
Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class.
The inheritance we learnt earlier had the concept of one base class or parent. The problem with class B extends C
“multiple inheritance” is that the derived class will have to manage the dependency on two base classes. {
public void disp()
{
System.out.println("B");
}
class D extends A
{
Page 15 Page 16
JAVA PROGRAMMING JAVA PROGRAMMING
Page 17 Page 18
JAVA PROGRAMMING JAVA PROGRAMMING
Page 19 Page 20
JAVA PROGRAMMING JAVA PROGRAMMING
} An abstract class is one which contains some defined methods and some undefined
void show() methods. Undefined methods are also known as unimplemented or abstract methods.
{ Abstract method is one which does not contain any definition.
System.out.println("i and j values are"+i+" "+j);
} To make the method as abstract we have to use a keyword called abstract before the function
} declaration.
class B extends A
{ Syntax for ABSTRACT CLASS: abstract return_type method_name (parameters list);
int k;
B(int a, int b, int c) // A Simple demonstration of abstract.
{ abstract class A
super(a, b);//super class constructor {
k = c; abstract void callme();
}
// display k – this overrides show() in A // concrete methods are still allowed in abstract classes
void show() void callmetoo()
{ {
super.show(); System.out.println("This is a concrete method.");
System.out.println("k: " + k); }
} }
class B extends A
} {
void callme()
class Override {
{ System.out.println("B's implementation of callme.");
}
public static void main(String args[]) }
{ class AbstractDemo
B subOb = new B(1, 2, 3); {
subOb.show(); // this calls show() in B public static void main(String args[])
{
} B b = new B();
} b.callme();
3.2.8 Method Overriding // Refer 2nd unit b.callmetoo();
3.2.9 Dynamic Method Dispatch // Refer 2nd unit }
}
3.2.10 Abstract Classes: Notice that no objects of class A are declared in the program. As mentioned, it is not possible to
instantiate an abstract class.
In JAVA we have two types of classes. They are concrete classes and abstract classes.
One other point: class A implements a concrete method called callmetoo( )
• A concrete class is one which contains fully defined methods. Defined methods are also known as
implemented or concrete methods. With respect to concrete class, we can create an object of that
class directly.
Page 21 Page 22
JAVA PROGRAMMING JAVA PROGRAMMING
3.3 Interface in Java class classname [extends superclass] [implements interface [,interface...]] {
// class-body
3.3.1 Introduction
}
An interface in java is a blueprint of a class.
It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction.
If a class implements more than one interface, the interfaces are separated with a comma.
There can be only abstract methods in the java interface not method body.
It is used to achieve abstraction and multiple inheritance in Java.
Here is a small example class that implements the Callback interface shown earlier.
Using the keyword interface, you can fully abstract a class’ interface from its implementation.
That is, using interface, you can specify what a class must do, but not how it does it.
class Client implements Callback
Interfaces are syntactically similar to classes, but they lack instance variables, and their methods {
are declared without any body // Implement Callback's interface
Variables can be declared inside of interface declarations. public void callback(int p)
They are implicitly final and static, meaning they cannot be changed by the implementing class. {
They must also be initialized. All methods and variables are implicitly public. System.out.println("callback called with " + p);
}
3.3.2 Declaring an Interface }
An interface is defined much like a class. This is the general form of an interface: Notice that callback( ) is declared using the public access specifier.
access interface name { It is both permissible and common for classes that implement interfaces to define additional members
return-type method-name1(parameter-list); of their own. For example, the following version of Client implements callback( ) and adds the method
return-type method-name2(parameter-list); nonIfaceMeth( ):
type final-varname1 = value;
type final-varname2 = value;
// ... class Client implements Callback
return-type method-nameN(parameter-list); {
type final-varnameN = value; // Implement Callback's interface
} public void callback(int p)
{
Here is an example of an interface definition. It declares a simple interface that contains one method System.out.println("callback called with " + p);
called callback( ) that takes a single integer parameter. }
void nonIfaceMeth()
interface Callback {
{ System.out.println("Classes that implement interfaces " +
void callback(int param); "may also define other members, too.");
} }
}
3.3.3 Implementing Interfaces
Accessing Implementations Through Interface References:
Once an interface has been defined, one or more classes can implement that interface. To implement an You can declare variables as object references that use an interface rather than a class type.
interface, include the implements clause in a class definition, and then create the methods defined by the Any instance of any class that implements the declared interface can be referred to by such
interface. The general form of a class that includes the implements clause looks like this: a variable. When you call a method through one of these references, the correct version will
be called based on the actual instance of the interface being referred to.
Page 23 Page 24
JAVA PROGRAMMING JAVA PROGRAMMING
The following example calls the callback( ) method via an interface reference variable: }
Page 25 Page 26
JAVA PROGRAMMING JAVA PROGRAMMING
Page 27 Page 28
JAVA PROGRAMMING JAVA PROGRAMMING
public void square (int a); public static void main(String args[])
{
// static method int a = 5;
static void show()
{ // lambda expression to define the calculate method
System.out.println("Static Method Executed"); Square s = (int x)->x*x;
}
} // parameter passed and return type must be
// same as defined in the prototype
class TestClass implements TestInterface int ans = s.calculate(a);
{ System.out.println(ans);
// Implementation of square abstract method }
public void square (int a) }
{
System.out.println(a*a); Output:
} 25
public static void main(String args[])
{
TestClass d = new TestClass();
d.square(4);
Output:
16
Static Method Executed
3.3.10 FunctionalInterface annotation is used to ensure that the functional interface can’t have
more than one abstract method. In case more than one abstract methods are present, the compiler flags
an ‘Unexpected @FunctionalInterface annotation’ message.
@FunctionalInterface
interface Square
{
int calculate(int x);
}
class Test
{
Page 29 Page 30