0% found this document useful (0 votes)
12 views25 pages

Unit 3

This document provides an overview of arrays in Java, including their declaration, initialization, and types, as well as advantages and disadvantages. It also covers inheritance, method overriding, and polymorphism in Java, explaining the concepts with examples. Additionally, it discusses binding types and their significance in Java programming.

Uploaded by

lavuletilaxmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views25 pages

Unit 3

This document provides an overview of arrays in Java, including their declaration, initialization, and types, as well as advantages and disadvantages. It also covers inheritance, method overriding, and polymorphism in Java, explaining the concepts with examples. Additionally, it discusses binding types and their significance in Java programming.

Uploaded by

lavuletilaxmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Unit-III

Arrays: Introduction, Declaration and Initialization of Arrays, Storage of


Array in Computer Memory, Accessing Elements of Arrays,

In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We
can store primitive values or objects in an array in Java. Like C/C++, we can also
create single dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection framework
is used in Java which grows automatically.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array
Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];
Example of Java Array

Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Test it Now

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declaration, instantiation


2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}
Test it Now

Output:

33
3
4
5
For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints
the array elements one by one. It holds an array element in a variable, then
executes the body of the loop.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){
2. //body of the loop
3. }

Let us see the example of print the elements of Java array using the for-each loop.

1. //Java Program to print the array elements using for-each loop


2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}

Output:

33
3
4
5

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic on any
array.

Let's see the simple example to get the minimum number of an array using a
method.

1. //Java Program to demonstrate the way of passing an array


2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}
Test it Now

Output:

Sorting of Arrays:

Sort Array in Ascending Order

The ascending order arranges the elements in the lowest to highest order. It is also
known as natural order or numerical order. We can perform sorting in the
following ways:

o Using the sort() Method


o Without using the method
o Using the for Loop
o Using the User Defined Method

Using the sort() Method

In Java, Arrays is the class defined in the java.util package that


provides sort() method to sort an array in ascending order. It uses Dual-Pivot
Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is
a static method that parses an array as a parameter and does not return anything.
We can invoke it directly using the class name. It accepts an array of type int, float,
double, long, char, byte.
Syntax:

1. public static void sort(int[] a)

Search for Values in Arrays,

SortArrayExample1.java

1. import java.util.Arrays;
2. public class SortArrayExample1
3. {
4. public static void main(String[] args)
5. {
6. //defining an array of integer type
7. int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
8. //invoking sort() method of the Arrays class
9. Arrays.sort(array);
10. System.out.println("Elements of array sorted in ascending order: ");
11. //prints array using the for loop
12. for (int i = 0; i < array.length; i++)
13. {
14. System.out.println(array[i]);
15. }
16. }
17. }

Output:

Array elements in ascending order:


5
12
22
23
34
67
90
10
1. public class SortArrayExample2
2. {
3. public static void main(String[] args)
4. {
5. //creating an instance of an array
6. int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65};
7. System.out.println("Array elements after sorting:");
8. //sorting logic
9. for (int i = 0; i < arr.length; i++)
10. {
11. for (int j = i + 1; j < arr.length; j++)
12. {
13. int tmp = 0;
14. if (arr[i] > arr[j])
15. {
16. tmp = arr[i];
17. arr[i] = arr[j];
18. arr[j] = tmp;
19. }
20. }
21. //prints the sorted element of the array
22. System.out.println(arr[i]);
23. }
24. }
25. }

Output:

Array elements after sorting:


-65
-4
-1
1
3
6
20
34
34
55
78
90

Inheritance in java:
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.

File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...
Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you


can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical


inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

Overriding:
Method Overriding in Java
1. Understanding the problem without method overriding
2. Can we override the static method
3. Method overloading vs. method overriding

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method


that has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Ex:
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. //Creating a child class
5. class Bike extends Vehicle{
6. public static void main(String args[]){
7. //creating an instance of child class
8. Bike obj = new Bike();
9. //calling the method with child class instance
10. obj.run();
11. }
12. }

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 and


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.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a


call to an overridden method is resolved at runtime rather than compile-time.
Example of Java Runtime Polymorphism
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

Dynamic binding:

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late Binding)

Understanding Type

Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.


1. int data=30;

Here data variable is a type of int.

2) References have a type


1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass.

1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is


known as static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding


1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }
Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding


1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
Test it Now
Output:dog is eating...

Instance of operator:

The java instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it


compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that has null value, it returns false.

Simple example of java instanceof

Let's see the simple example of instance operator where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }
Test it Now
Output:true

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method

abstract class Bike{

abstract void run();


}

class Honda4 extends Bike{

void run(){System.out.println("running safely");}

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

OUTPUT:

running safely

abstract class Shape{

abstract void draw();

//In real scenario, implementation is provided by others i.e. unknown by end


user

class Rectangle extends Shape{

void draw(){System.out.println("drawing rectangle");}

class Circle1 extends Shape{

void draw(){System.out.println("drawing circle");}


}

//In real scenario, method is called by programmer or user

class TestAbstraction1{

public static void main(String args[]){

Shape s=new Circle1();//In a real scenario, object is provided through


method, e.g., getShape() method

s.draw();

Interface in java:

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. There can be only


abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Java Interface Example


In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Package in java:

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.

Here, we will have the detailed learning of creating and using user-defined
packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.

3) Java package removes naming collision.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that
they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

package in java
Simple example of java package
The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package
If you are not using any IDE, you need to follow the syntax given
below:

javac -d directory javafilename


For example

javac -d . Simple.java
The -d switch specifies the destination where to put the generated class
file. You can use any directory name like /home (in case of Linux),
d:/abc (in case of windows) etc. If you want to keep the package within
the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the
class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.

import package.*;
import package.classname;
fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this
package will be accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package
will be accessible. Now there is no need to import. But you need to use
fully qualified name every time when you are accessing the class or
interface.

It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

You might also like