Unit 3
Unit 3
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.
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.
Output:
10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
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.
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.
Output:
33
3
4
5
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.
Output:
Sorting of Arrays:
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:
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:
Output:
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).
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
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
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
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.
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,:
Dynamic binding:
Understanding Type
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
If there is any private, final or static method in a class, there is static binding.
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).
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
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).
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
obj.run();
OUTPUT:
running safely
class TestAbstraction1{
s.draw();
Interface in java:
There are mainly three reasons to use interface. They are given below.
Syntax:
interface <interface_name>{
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Package in java:
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.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
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 . 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).
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.
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.
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.
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.