0% found this document useful (0 votes)
18 views

Unit Ii

1. Inheritance is a mechanism where one class acquires properties of another class. This allows code reusability and single inheritance, multi-level inheritance, hierarchical inheritance, and hybrid inheritance are possible in Java. 2. Method overriding occurs when a subclass defines a method with the same name, parameters and return type as a method in its superclass. The subclass method overrides the superclass method. 3. The final keyword can be used with variables, methods, and classes. It provides constants, prevents method overriding for final methods, and disallows subclassing for final classes.

Uploaded by

uday franklin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit Ii

1. Inheritance is a mechanism where one class acquires properties of another class. This allows code reusability and single inheritance, multi-level inheritance, hierarchical inheritance, and hybrid inheritance are possible in Java. 2. Method overriding occurs when a subclass defines a method with the same name, parameters and return type as a method in its superclass. The subclass method overrides the superclass method. 3. The final keyword can be used with variables, methods, and classes. It provides constants, prevents method overriding for final methods, and disallows subclassing for final classes.

Uploaded by

uday franklin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

UNIT – II

Inheritance :
Inheritance is a mechanism in which one class can acquire the properties of another
class. Here, one object acquires all the properties and behaviors of parent object.

The idea behind inheritance is that you can create new class from existing classes .So
that new class will inherit or reuse methods and variables of its parent class and you can add new
methods and variables.

Inheritance represents the IS –A relationship .

we use inheritance for

1. method overriding(Run time polymorphism)


2. code reusability

Syntax of Inheritance:

class subclassname extends superclassname

----

----

// members

The keyword extends indicates that you are making a new class that derives from
an existing class. In the terminology of java , a class that is inherited is called a
superclass. The new class is called a subclass.

Ex :

Java Inheritance Example


Programmer IS – A Employee

class Employee
{
float salary=40000;
}

class Programmer extends Employee


{
int bonus=10000;

public static void main(String args[])


{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Types of Inheritance:

1. Single inheritance
2. Multi level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

1. Single Inheritance :

when a single derived class is created from a single base class then
the inheritance is called as single inheritance.

2. Multi level Inheritance:

when a derived class is created from another derived class, then


that inheritance is called as multi level inheritance.

3. Heirarchical Inheritance:
when more than one derived class are created from a single base
class,then that inheritance is called as heirarchical inheritance.
4.Multiple inheritance:

when a derived class is created from more than one base class then
that inheritance is called as multiple inheritance.But multiple inheritance is
not supported by java using classes and can be done using interfaces.

5.Hybrid Inheritance:

Any combination of single,hierarchical and multilevel inheritances is


called as hybrid inheritance.
1.write a java program to implement the concept of Single inheritance

class A
{
int i;
void showi()
{
System.out.println("i = " + i);
}
}
class B extends A
{
int j;
void showj()
{
System.out.println("j = " +j);
}
void sum()
{
System.out.println("sum = " + (i+j));
}

class Inheritance
{
public static void main(String args[])
{
A obj1=new A();
B obj2=new B();
obj1.i=10;
obj2.i=30;
obj2.j=20;
obj1.showi();
obj2.showj();
obj2.sum();
}
}
output :

2. Write a java program to implement multilevel inheritance


class A
{
int a;
void showa()
{
System.out.println("a = "+ a);
}
}
class B extends A
{
int b;
void showb()
{
System.out.println("b =" +b);
}
}
class C extends B
{
int c;
void showc()
{
System.out.println("c = " +c);
}
void sum()
{
System.out.println("sum = " + (a+b+c));
}
}
class MInheritance
{
public static void main(String args[])
{
C obj1 = new C();
obj1.a=10;
obj1.b=20;
obj1.c=30;
obj1.showa();
obj1.showb();
obj1.showc();
obj1.sum();
}
}

output :

3. Write a java program to implement Hierarchical Inheritance


class A
{
int a;
void showa()
{
System.out.println("a = "+ a);
}
}

class B extends A
{
int b;
void showb()
{
System.out.println("b =" +b);
}
void sum()
{
System.out.println("sum = " + (a+b));
}
}

class C extends A
{
int c;
void showc()
{
System.out.println("c = " +c);
}
void sum()
{
System.out.println("sum = " + (a+c));
}
}

class HInheritance
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
obj1.a=10;
obj1.b=20;
obj1.showa();
obj1.showb();
obj1.sum();
obj2.a=30;
obj2.c=40;
obj2.showa();
obj2.showc();
obj2.sum();
}
}
output:

Super Keyword:

The super is a reference variable that is used to refer immediate


parent class object.whenever you create the instance of subclass an
instance of parent class is created implicitly i.e referred by super
reference variable.

usage of super keyword:

1. super is used to refer immediate parent class instance variable.


2. super is used to invoke immediate parent class method.
3. super() is used to invoke immediate parent class constructor.

1. super at variable level :

if super class and sub class has variable with the same name
then super is used to point the super class member.
syntax : super.member

either method or instance variable

Ex :
class A
{
int i=10;
}
class B extends A
{
int i=20;
void display()
{
System.out.println("value of sub class i = " + i);
System.out.println("value of superclass i = "+super.i);
}
}
class SuperDemo
{
public static void main(String args[])
{
B obj1= new B();
obj1.display();
}
}
Output :

2. super is used to invoke immediate parent class method:


The super keyword can also be used to invoke parent
class method. It should be used in case subclass contains the
same method as parent class.

Ex :
class Person
{
void message()
{
System.out.println("Base class message method");
}
}
class Student extends Person
{
void message()
{
System.out.println("derived class message method");
}
void display()
{
message();
super.message();
}
}

class SuperDemo1
{
public static void main(String args[])
{
Student obj1= new Student();
obj1.display();
}
}

output :

3.super() at constructor level :

The super keyword can also be used to invoke the parent class
constructor as given below.

Ex :

class A
{
A()
{
System.out.println("Base class constructor");
}
}
class B extends A
{
B()
{
super();
System.out.println("derived class constructor");
}
}

class SuperDemo2
{
public static void main(String args[])
{
B obj1 =new B();
}
}
output :

Note :

1. super() is added in each class constructor automatically by compiler. As


we know well that default constructor is provided by compiler
automatically, but it also adds super() as the first statement.

when a class hierarchy is created, constructors are called inorder of


derivation from super class to sub class. If super() is used ,it must be the
first statement in the subclass constructor.

final keyword:

In java, final keyword is used at

(i)variable level – To make value of variable constant

(ii)method level – Method cannot be overriden

(iii)class level – class can’t be inherited

(i) final at variable level :-


It is always good to write final variables in capital letters. Final variables
should be initialized while declaration.By default final variables are read
only.
Ex: final int x=10;
x=20; // if we attempt to modify x, it will generate an error
class Bike
{
final int speedlimit=60;
void run()
{
speedlimit=100;
}
public static void main(String args[])
{
Bike b=new Bike();
b.run();
}
}
(ii)final method :
A java method with final keyword is called final method and it can
not be overridden in subclass. Final methods can be inherited to the
child class but can’t override.

Ex :
class Bike
{
final void run()
{
System.out.println(“running”);
}
}
class Honda extends Bike
{
void run() //error, final methods can’t be overridden
{
System.out.println(“running safely”);
}
}

(iii)final class :
java class with final keyword is called final class in java.Final class is
complete in nature and cannot be inherited.

final class Bike

{
void run()
{
System.out.println(“running”);
}
}
class Honda extends Bike // error cannot inherit
{
void run()
{
System.out.println(“running safely”);
}
}

(ii)
Method Overriding:

In a class hierarchy, when a method in a subclass has the same name and
type signature as a method in its 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 with in its subclass, it will always
refer to the version of that method defined by the subclass. super class method
version will be hidden.

Ex:

class Bank
{
int getRateofInterest()
{
return 0;
}
}

class SBI extends Bank


{
int getRateofInterest()
{
return 10;
}
}

class Axis extends Bank


{
int getRateofInterest()
{
return 20;
}
}
class OverrideDemo
{
public static void main(String args[])
{
SBI s= new SBI();
Axis a= new Axis();
System.out.println("SBI rate of interest is " +s.getRateofInterest());
System.out.println("Axis rate of interest is " + a.getRateofInterest());
}
}

The super class version of getRateofInterest() (Bank) is hidden.


Note : If we want to call superclass getRateofInterest() method, we can do so by
using super.getRateofInterest() inside subclass getRateofInterest() method as
follows.
int getRateofInterest()
{
super.getRateofInterest();
---
}
Ex 2 : Write a java program to illustrate the concept of overriding.
class Animal
{
void move()
{
System.out.println("animal can move");
}
}
class Dog extends Animal
{
void move()
{
System.out.println("Dog can walk and run");
}
}
class OverrideDemo1
{
public static void main(String args[])
{
Animal a= new Animal();
a.move();
Dog d=new Dog();
d.move();
Animal a1=new Dog();
a1.move();
}
}

Rules for method overriding :


1. Entire signature of the method must be same i.e argument list should be
exactly the same as that of overridden method. Return type should be
same.
2. A method declared as final can not be overridden.
3. A method declared static cannot be overridden but can be re-declared.
4. private methods cannot be overriden

Dynamic Method Dispatch:(Run time polymorphism)


It is a mechanism by which a call to an overridden method is resolved at runtime. This is how java
implements Runtime polymorphism. When a overridden method is called by a reference ,java
determines which version of the method to execute based on the type of object it refers to.

Ex :
parent p=new parent();

child c=new child();

parent p= new child(); // possible,upcasting

child c= new parent(); // incompatible, down casting

Ex : write a java program to illustrate the concept of runtime polymorphism


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

class Rectangle extends Shape


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

class Circle extends Shape


{
void draw()
{
System.out.println("drawing circle...");
}
}
class Triangle extends Shape
{
void draw()
{
System.out.println("drawing triangle...");
}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

Ex2 : Write a java program to implement Runtime polymorphism

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
}
class Cat extends Animal
{
void eat()
{
System.out.println("eating rat...");
}
}
class Lion extends Animal
{
void eat()
{
System.out.println("eating meat...");
}
}
class RunTimePolymorphism1
{
public static void main(String[] args)
{
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}
}

Differences between method overloading and method overriding

Method overloading Method Overriding

1.writing 2 or more methods with the same 1. writing 2 or more methods with the same
name but with different signature is called name and same signature is called method
method Overloading Overriding

2.Method overloading is done in the same class 2.Method overriding is done in super and sub
classes

3. In method overloading method return type 3. In method overriding method return types
can be same or different. should be same.

4.JVM decides which method is called 4. JVM decides which method is called
depending on the difference in method depending on the object used to call the
signatures at compile time method at run time.

5.This is called as compile time polymorphism 5.This is called as Run time polymorphism

6.same method is defined to perform different 6.In method overriding the subclass method
tasks in method overloading. overrides (replaces) super class method.
abstract method and abstract class:
abstract method :
An abstract method is a method without method body. It is a
method which must be overridden by its subclass.
sometimes we want to define a super class that declares the
structure of a given abstraction without providing a complete
implementation of every method. That is we want to create a super class
that only defines a generalized form that will be shared by all of its sub
classes, leaving it to each subclass to fill in the details.

Syntax :
abstract returntype methodname(parameter list);

abstract class :
Any class that contains one or more abstract methods must also be
declared as abstract and it is called abstract class.
syntax:
abstract class classname
{
--------
--------
abstract returntype methodname(parameterlist);
}

points to remember:
1.we can not create objects to an abstract class.
2. we can not declare abstract constructors.
3. we can not declare abstract static methods.
4. abstract classes can have constructors, member variables and normal
methods in addition to abstract methods.
5.all the abstract methods of a abstract class should be implemented in
its sub class.
6.if any abstract method is not implemented then that subclass should be
declared as abstract.
In this case we can’t create an object to the sub class.
7. we can’t declare a class as both abstract and final.
when to use :
abstract methods are usually declared when two or more subclasses
are expected to do a similar thing in different ways through different
implementations.
Ex : Write a java program to implement abstract class to calculate
areas of different shapes.

abstract class A
{ abstract void squareArea(int a);
abstract void rectangleArea(int l, int b);
abstract void circleArea(float r);
}
class B extends A
{
void squareArea(int a)
{
System.out.println("Area of square = " + (a*a));
}
void rectangleArea(int l,int b)
{
System.out.println("Area of rectangle= " + (l*b));
}
void circleArea(float r)
{
System.out.println("area of circle = " +(3.14*r*r));
}
}
class AbstractDemo
{
public static void main(String args[])
{
B obj= new B();
obj.squareArea(5);
obj.rectangleArea(5,10);
obj.circleArea(2.5f);
}
}

packages :
package : A package is a group of similar types of classes, interfaces and sub-
packages. A package is a directory for holding java files. A package can be defined
as a collection used for grouping a variety of classes and interfaces based on their
functionality.

Packages in java can be categorized into two types

1. built-in packages

2. user-defined package.

Built-in packages :

java has many predefined packages which can be used in programs and are
given by sun micro systems. Some of them are java, lang, awt, javax, swing, net,
io, util, sql etc.
java.lang : consists of primary classes and interfaces essential for developing a
basic java program.

Java. math : provides classes for performing arbitrary-precision integer arithmetic


(BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal). This
reference will take you through simple and practical methods available in java.

java.util :Contains classes such as vectors, hash tables, date etc.

java.io:Stream classes for I/O

java.awt:Classes for implementing GUI – windows, buttons, menus etc.

java.net:Classes for networking

java.applet: Classes for creating and implementing applets

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.


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:

1. javac -d directory javafilename

For example

1. 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.

1. import package.*;
2. import package.classname;
3. 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();
10. obj.msg();
11. }
12. }
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();
10. obj.msg();
11. }
12. }
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 impo
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();
}
10. }
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported excluding the classes and interfa
subpackages. Hence, you need to import the subpackage as well.

Note: Sequence of the program must be package then import then class.

Ex 2 :

package mypack;

class Addition
{
void sum(int a,int b)
{
System.out.println(“ sum = “ + (a+b));
}
}

save : Addition.java
compile: javac -d . Addition.java

----------------------------------

package mypack;
class Subtraction
{
void diff(int a,int b)
{
System.out.println(“Difference =” + (a-b));
}
}

save : Subtraction.java
compile : javac -d . Subtraction.java

-------------------------
package mypack;
import mypack.*;
class PackDemo
{
public static void main(String args[])
{
Addition a = new Addition();
Subtraction b = new Subtraction();
a.sum(10,20);
b.diff(10,20);
}
}
save : PackDemo.java
Compile : javac -d . PackDemo.java
Execute : java mypack.PackDemo

in the above programs , Addition and Subtraction ,PackDemo classes


are placed in the package called mypack. Any class can import the
classes of the same package or from the other packages.Here,
PackDemo class is importing the classes from mypack. compile all the
three programs using the above commands and we can execute
PackDemo class which is in mypack package with the statement
“java mypack.PackDemo” or move to mypack directory and execute
using the statement “ java PackDemo” or you can set the CLASSPATH
and then execute your program.

Setting the classpath:


if the class files are not in the current directory, we need to set
the classpath. Whenever, we execute / compile any class files, JDK tools
javac and java , search the package / class file in the user classpath
which is the current directory by default. If the classes are not in the
current directory, then we need to set the classpath.
The classpath can be set in two ways :
1. It is an environment variable which can be set using the system
utility in the control panel or at the DOS prompt as shown:
set CLASSPATH = %CLASSPATH% ; d:\mypack;

%classpath% is used to keep the existing path intact and append


our new path to it.

To make the changes permanent, edit the environment variable in


the control panel
right click on
computer-> properties -> Advanced System Setting ->
Engironment variables -> classpath
2. To use user defined packages, we can use –classpath option
Ex : javac –cp “d:\mypack” PackDemo.java
Sub Packages :
sub packages can be designed in hierarchy i.e one package can be
a part of another package. This can be achieved by specifying multiple
names of packages at various levels of hierarchy separated by dots.

syntax :
package rootpackagename.subpackagename;
using packages :
To import all the classes in a package, we can use wildcard
notation.
import java.awt.*;
to import a specific class we can specify the classname as
import java.awt.Rectangle;
classes in a package java.lang are automatically imported . For all other
classes , you must supply an import statement.
Example :
Recursive program to calculate factorial in a package.
package p1;
public class RecFactorial
{
public long fact(int n)
{
if(n==0)
return 1;
else
return(n*fact(n-1));
}
}
save : RecFactorial.java
compile : javac -d . RecFactorial.java
-------------------------------------------

package p2;
import p1.*;
class Test
{
public static void main(String args[])
{
RecFactorial obj = new RecFactorial();
System.out.println("factorial = " +obj.fact(5));
}
}
save : Test.java
compile :javac -d . Test.java
execute : java
Static :
static member can be accessed independently without an object. When a member is
declared as static, it can be accessed before any objects of its class are created, and without
reference to any object.

The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1. static variables :

class / static variables declaration is preceeded with the keyword static. They are
declared inside a class but outside a method.The most important point about static variables is
that there exists only a single copy of static variables per class. All objects of the class share this
variables. By default, static variables are initialized to their default values according to their
respective types.

java does not allow global variables . The closest thing we can get to a global variable in
java is to make the instance variable in the class static.

When a variable is declared with the keyword static ,it is called as a class variable.

 It is a variable which belong to the class and not to object.


 They are initialized only once, at the start of execution. These are initialized first, before
the initialization of any instance variables.
 A single copy to be shared by all instances of a class.
 A static variable can be accessed directly by the class name and does not need any object.
syntax :
classname.variablename

Example :

//Java Program to demonstrate the use of static variable


class Student
{
int rollno;//instance variable
String name; //instance variable
static String college ="ITS";//static variable

//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display the values
void display ()
{
System.out.println(“rollno= “ + rollno);
System.out.println(“name “ = +name);
System.out.println(“college =” +college);
}
}
//Test class to show the values of objects
public class TestStaticVariable1
{
public static void main(String args[])
{
Student s1 = new Student(501,"Kranthi");
Student s2 = new Student(1201,"Anand");
s1.display();
s2.display();
}
}

Note : As we have mentioned above, static variables will get the memory only once, if any object changes
the values of the static variable, it will remain its value.
Ex :
//Java Program to illustrate the use of static variable which
//is shared with all objects.
class CounterEx
{
static int count=0;//will get memory only once and retain its value

CounterEx()
{
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[])


{
//creating objects
CounterEx c1=new CounterEx();
CounterEx c2=new CounterEx();
Counter2 c3=new Counter2();
}
}
output:
1
2
3
Note :
if count is not a static variable in the above program , the output will be
1
1
1

2. java static method :

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Restrictions for the static method

There are 3 main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.
2. They cannot refer to this or super in any way.
3. They cannot access non-static data.

Ex1 :

class A{
int a=40;//non static

public static void main(String args[])


{
System.out.println(a);
}
}
output : compile time error
Ex2:Write a static method that calculates cube of a given number.
class Calculate
{
static int cube(int x)
{
return(x*x*x);
}
public static void main(String args[])
{
int result=Calculate.cube(5);
System.out.println("result ="+ result);
}
}

Ex3: static method that access data member and can change the value of it.
class Student
{
int rollno;
String name;
static String college= "MIC";
static void change()
{
college="MIC College";
}
Student(int r, String n)
{
rollno=r;
name=n;
}
void display()
{
System.out.println(rollno + " " + name +" "+ college);
}
public static void main(String args[])
{
Student.change();
Student s1= new Student(501,"aaa");
Student s2= new Student(502,"bbb");
s1.display();
s2.display();
}
}
output :
501 aaa MIC College
502 bbb MIC College

Note :
Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem of extra
memory allocation.

3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.
o static blocks are executed first, even than the static methods.

class A
{
static i;
static
{
System.out.println("static block is invoked");
i=10;
}
public static void main(String args[])
{
System.out.println("Now main method is invoked");
System.out.println(A.i);
}
}

Q) Can we execute a program without main() method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not
possible to execute a Java class without the main method.
this keyword:-
“this” can be used inside any method to refer to the current object. “this” is
always a reference to the object on which the method was invoked.

Usage of java this keyword

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1. this : To refer current class instance variable


When a local variable has the same name as an instance variable, the
local variable hides the instance variable.
this keyword can be used to resolve any name space collisions that
might occur between instance variables and local variables.

program to illustrate the use of this to refer current class instance variable :

class Student1
{
int rollno;
String name;
Student1(int rollno, String name)
{
this.rollno= rollno;
this.name=name;
}
void show()
{
System.out.println(rollno + " " +name);
}
}
class ThisEx
{
public static void main(String args[])
{
Student1 s= new Student1(1,"aaa");
s.show();
}
}
2. this : To invoke current class method:
“this” can be used to invoke current class method. If you don’t use the
this keyword , compiler automatically adds this keyword while invoking
the method.
Write a program to illustrate the use of this to invoke current class method
class A
{
void method1()
{
System.out.println("hello method 1");
}
void method2()
{
System.out.println("hello method 2");
this.method1();
}
}

class ThisEx1
{
public static void main(String args[])
{
A obj = new A();
obj.method2();
}
}
3. this : To invoke current class constructor
the this() constructor call can be used to invoke the current class
constructor. It is used to reuse the constructor.
We can call default constructor from parameterized constructor.

Write a program to illustrate the use of thisto invoke current class constructor
class A
{
A()
{
System.out.println("hello A");
}
A(int x)
{
this();
System.out.println(x);
}
}

class ThisEx2
{
public static void main(String args[])
{
A obj = new A(10);
}
}
Arrays
An array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

we can access a specific element in the array by specifying its index within square brackets.

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 :

Array with single dimension is called 1D array.


Syntax to Declare an Array in Java:

1. dataType[] arrayname; (or)


2. dataType []arrayname; (or)
3. dataType arrayname[];
4. datatype arrayname[] = new datatype[size]
 here datatype declares the base type of the array. This base type determines what
type of elements that the array will hold.
 arrayname is the name of the array.
 size specifies the number of elements stored in the array.
 new is to allocate memory for an array. The elements in the array allocated by
new will automatically be initialized to zero.

Instantiation of an Array in Java

Ex : datatype arrayname[];
arrayname=new datatype[size];

initializing array elements:

int marks[] = new int[5];

Marks[0] Marks[1] Marks[2] Marks[3] Marks[4]

marks[0]=60;
marks[1]=70;
marks[2]=90;
//initializing
marks[3]=50;
marks[4]=40

Marks[0] Marks[1] Marks[2] Marks[3] Marks[4]


60 70 90 50 40

we can pass the values from keyboard to the array by using a loop.

for(int i=0;i<5;i++)
{
marks[i]=s.nextInt();
}

Array values can be printed as

for(int i=0; i < 5 ;i++)

System.out.println(marks[i]);

Ex1 : write a java program to initialize array and display the array elements.

class ArrayEx1
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Ex2:Write a JAVA program to sort for an element in a given list of elements


using bubble sort

import java.util.Scanner;
class BubbleSort
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int i,n,j,temp;
int a[]= new int[20];
System.out.println("enter n value");
n = s.nextInt();
System.out.println("Enter elements in sorted order");
for(i=0;i<n;i++)
{
System.out.println("enter a[" + i + "] =");
a[i]=s.nextInt();
}
for(i=1;i<=n-1;i++)
{
for(j=0;j<=n-2;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("sorted elements are");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}

Ex 3 :Write a JAVA program to search for an element in a given list of


elements using binary search mechanism.

import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int i,temp,key,low,high,mid,flag=0;
int a[]= new int[20];
System.out.println("enter n value");
int n = s.nextInt();
System.out.println("Enter elements in sorted order");
for(i=0;i<n;i++)
{
System.out.println("enter a[" + i + "] =");
a[i]=s.nextInt();
}
System.out.println("Enter element to search for");
key=s.nextInt();
low=0;
high=n-1;
while(low<=high)
{
mid = (low+high)/2;
if(key == a[mid])
{
System.out.println("key found at " + (mid+1) + " location");
flag=1;
break;
}
else if(key < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if(flag==0)
System.out.println("key not found");
}
}
Ex4:Write a JAVA program to sort for an element in a given list of elements
using merge sort.

import java.util.Scanner;
class MergeSortEx
{
static void mergesort(int a[],int low, int high)
{
if(low<high)
{
int mid=(low + high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
else
return;
}
static void merge(int a[],int low, int mid, int high)
{
int b[]=new int[a.length];
int i,j,k;
i=low;
j=mid+1;
k=0;
while(i<=mid && j <= high)
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}

while(i<=mid)
b[k++]=a[i++];
while(j<=high)
b[k++]=a[j++];
for(i=low,j=0;i<=high;i++,j++)
a[i]=b[j];
}

public static void main(String args[])


{
int n,i;
Scanner s=new Scanner(System.in);
System.out.println("Enter N value");
n=s.nextInt();
int a[]=new int[n];
System.out.println("enter " + n + " values");
for(i=0;i<n;i++)
{
a[i]=s.nextInt();
}
mergesort(a,0,n-1);
System.out.println("sorted list is ");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}

Note :

The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the


array in negative, equal to the array size or greater than the array size while traversing the array.

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array


class ArrayEx2
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.

//Java Program to illustrate the jagged array


class TestJaggedArray
{
public static void main(String[] args)
{
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++)
{
for (int j=0; j<arr[i].length; j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}

Ex : write java program to implement matrix addition


class MatrixAdd
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}
}

Multiplication of 2 Matrices in Java


In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the
columns of the second matrix which can be understood by the image given below.

//Java Program to multiply two matrices


public class MatrixMultiplicationExample
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}

}
Command line arguments

A command line argument is the information that directly follows the


programs name on the command line when it is executed.

These are the parameters that are passed into a program while executing.
These arguments are stored as string data type in a string array args[] of main()
method.

The first command line argument is stored as args[0] and second as args[1]
and so on.

Ex:

class CommandLine
{
public static void main(String args[])
{
for(int i=0;I < args.length; i++)
System.out.println(args[i]);
}
}
ouput:
d:\> java CommandLine CSE IT MECH
CSE
IT
MECH
Ex2 : write a program which computes sum of 2 numbers by accepting the data
from command prompt

class Sum
{
public static void main(String args[])
{
int n= args.length;
System.out.println(“No of arguments = “ + n);
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int z = x + y;
System.out.println(“sum =” + z);
}
}
output:
d:\> javac Sum.java

d:\> java Sum 10 20


sum=30

Ex3 : write a program which checks whether given no is even or odd by taking
data from keyboard.
class EvenOdd
{
public static void main(String args[])
{
int n = Integer.parseInt(args[0]);
if(n%2==0)
System.out.println( n + " is even");
else
System.out.println(n + " is odd");

}
}
output : d:\> javac EvenOdd.java
d:\> java EvenOdd 5
5 is odd

Nested classes :

In java, it is possible to define a class within another class, such classes are
known as nested classes.

1) The scope of the nested class(inner class) is bounded by the scope of its
enclosing class(outer class).
2) Additionally, it can access all the members of outer class including private
data members and methods. However, reverse is not true i.e the enclosing
outer class does not have access to the nested class.
3) A nested class is also a member of its enclosing class.
4) As a member of its enclosing class, a nested class can be declared
private,public, protected , default.
Syntax :
class Outer
{
----
class Inner
{
----
----
}
----
}
Types of nested classes
1.static nested class
2. Inner class
Nested classes

inner class or non-static Nested classes

static Nested classes local classes Anonymous classes

Static nested classes :


A static nested class is associated with its outer class. Like static class
methods, a static nested class can not refer directly to instance variables or
methods defined in its enclosing class. It can use them only through an
object reference.
The syntax for creating object of static nested class is

Outer.Inner nestedobj = new Outer.Inner();


Ex: Java Program to demonstrate static nested class
class Outer
{
static int x=10;
int y=20;
private static int z=30;
static class Inner
{
void display()
{
Outer obj = new Outer();
System.out.println(x + “ “ + z);
System.out.println(“y = “ + y); // cannot access non static member
directly
System.out.println(obj.y) //can access through object
}
}
}
class OuterDemo
{
public static void main(String args[])
{
Outer.Inner obj= new Outer.Inner();
obj.display();
}
}
2. Inner classes : An inner class is non-static nested class. To Instantiate a
inner class, you must first instantiate the outer class.Then create the inner
object within the outer object.
syntax:
Outer.Inner Innerobj = outerobj.new Inner();
there are two special kinds of inner class
1. local inner class
2. Anonymous inner classes

1.Local inner class :

It can access all the members of outer class.

Ex:

class Outer

static int x=10;

int y=20;

private int z=30;

class Inner

void display()

System.out.println(“x=”+x +”y=”+y+”z=”+z);

//It can access static,instance and also private members

of outer class.

}}
class OuterDemo
{
public static void main(String args[])
{
Outer outerobj= new Outer();
Outer.Inner innerobj=outerobj.new Inner();
innerobj.display();
}
}

2.Anonymous inner classes : are the classes with no name and for them only a
single object is created. It should be used if you have to override method of a
class or interface. Anonymous inner classes are useful in writing implementation
classes for listened interfaces in graphics programming.

Java Anonymous inner class can be created by two ways:

1.Class (may be abstract or concrete).

2.Interface

Ex:

abstract class Person{


abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Java anonymous inner class example using
interface
interface Eatable
{
void eat();
}
class TestAnonymousInner1
{
public static void main(String args[])
{
Eatable e=new Eatable()
{
public void eat()
{
System.out.println("nice fruits");
}
};
e.eat();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy