Professional Documents
Culture Documents
Method overloading
Method overloading is a concept that allows to declare multiple methods with same name but
different parameters in the same class. Java supports method overloading and always occur in the same
class (unlike method overriding). Method overloading is one of the ways through which java supports
polymorphism. Polymorphism is a concept of object oriented programming that deal with multiple
forms. We will cover polymorphism in separate topics later on.
Method overloading can be done by changing number of arguments or by changing the data type of
arguments. If two or more method have same name and same parameter list but differs in return type
can not be overloaded. Overloaded method can have different access modifiers and it does not have
any significance in method overloading.
There are two different ways of method overloading.
1. Different datatype of arguments
2. Different number of arguments
In this example the multiply() method is overloaded twice. The first method takes two
arguments and the second method takes three arguments. When an overloaded method is called Java
look for match between the arguments to call the method and its parameters. This match need not
always be exact, sometime when exact match is not found, Java automatic type conversion plays a
vital role.
We use inner classes to logically group classes and interfaces in one place so that it can be
morereadable and maintainable.
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
1) Nested classes represent a special type of relationship that is it can access all the
members(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because
itlogically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
Recursion
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain problems can
be solved quite easily. In the recursive program, the solution to the base case is provided and the
solution of the bigger problem is expressed in terms of smaller problems.
sint fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, base case for n < = 1 is defined and larger value of number can be solved by
converting to smaller one till base case is reached. How a particular problem is solved using recursion?
The idea is to represent a problem in terms of one or more smaller problems, and add one or more base
conditions that stop the recursion. For example, we compute factorial n if we know factorial of (n-1).
The base case for factorial would be n = 0. We return 1 when n = 0. Why Stack Overflow error occurs
in recursion? If the base case is not reached or not defined, then the stack overflow problem may arise.
Let us take an example to understand this.
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but the number will never reach 100.
So, the base case is not reached. If the memory is exhausted by these functions on the stack, it will
cause a stack overflow error. What is the difference between direct and indirect recursion? A function
fun is called direct recursive if it calls the same function fun. A function fun is called indirect recursive
if it calls another function say fun_new and fun_new calls fun directly or indirectly. Difference
between direct and indirect recursion has been illustrated in Table 1.
Direct recursion:
void directRecFun()
{
// Some code....
directRecFun();
// Some code...
}
Indirect recursion:
void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}
Some problems are inherently recursive like tree traversals, Tower of Hanoi, etc. For such
problems, it is preferred to write recursive code.
We can write such codes also iteratively with the help of a stack data structure.
For example refer In order Tree Traversal without Recursion, Iterative Tower of Hanoi
Every recursive program can be written iteratively and vice versa is also true.
The recursive program has greater space requirements than iterative program as all functions
will remain in the stack until the base case is reached.
It also has greater time requirements because of function calls and returns overhead.
.
The java.lang.String class provides a lot of built-in methods that are used to manipulate
string in Java. By the help of these methods, we can perform operations on String objects such
as trimming, concatenating, converting, comparing, replacing strings etc. Java String is a
powerful concept because everything is treated as a String if you submit any form in window
based, web based or mobile application.
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Stringoperation1.java
public class Stringoperation1
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}
Output:
SACHIN
sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
public class Stringoperation2
{
public static void main(String ar[])
{
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
}
}
Output:
Sachin
Sachin
Java String startsWith() and endsWith() method
The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.
Stringoperation3.java
public class Stringoperation3
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
}
}
Output:
true
true
Java String charAt() Method
The String class charAt() method returns a character at specified index.
Stringoperation4.java
public class Stringoperation4
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
}
}
Output:
S
H
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known as
parent-child relationship.
}
The extends keyword indicates that you are making a new class that derives from an
existingclass. The meaning of "extends" is to increase the functionality.
Example :
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
}}
class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String
args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal
{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog
{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String rgs[])
{ BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat(); }}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
A subclass includes all of the members of its super class but it cannot access those members
of the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.
super keyword in java
The super keyword in java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitlywhich is referred by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
d.printColor();
}}
Output:
Black
white
Keyword in Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only.
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:
1. Object obj=getObject();//we don't know what object will be returned from this method
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
obj.run();
}
1. class Bank{
}
class SBI extends Bank{
}
class ICICI extends Bank{
}
class AXIS extends Bank{
}
class Test2
{
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
A class that is declared with abstract keyword is known as abstract class in java. It can have abstract
and non-abstract methods (method with body). It needs to be extended and its method implemented.
It cannot be instantiated.
abstract method
1. abstract void printStatus();//no body and abstract
}
class Honda4 extends Bike{
obj.run();
}
1. }
Output:
running safely..