Saturday, 30 September 2017

Abstract Class & Interface in Java

     Abstract Class & Interface in Java 

       Here is the most important topic on Java Abstract class and interface, Abstraction is the very important aspects in Object oriented Programming and we can achieve abstraction with the help of Abstract class and interface, this topic is equally important for interview point of view. So lets take a look ,if you have any questions please comment below .





If a class contain any abstract method then the class is declared as abstract class. It can have abstract and non-abstract methods (method with body).

Abstraction in Java:

Abstraction is a process of hiding the implementation details and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.
Abstraction in Java:
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class:

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.
Syntax:
abstract class class_name {
}
Abstract method:

Method that are declared without any body within an abstract class is known as abstract method. Any class that extends an abstract class must implement all the abstract methods declared by the super class.
Syntax:
abstract return_type function_name ( );    // No definition
NOTE: Instead of curly braces({ }) an abstract method will have a semicolon( ; ) at the end.
Example  of Abstract class
abstract class A
{
abstract void callme();
}
class B extends A
{
void callme()
{
  System.out.println("this is callme.");
}
public static void main(String[] args)
{
  B b=new B();
  b.callme();
}
}
Output : this is callme.

Points to Remember:

1. Abstract classes are not Interfaces. They are different,
2. An abstract class must have an abstract method.
3. Abstract classes can have Constructors, Member variables and Normal methods.
4. Abstract classes are never instantiated.
5. When you extend Abstract class with abstract method, you must define the abstract method in the child class, or make the child class abstract.
When to use Abstract Methods & Abstract Class??

Ans) Abstract methods are usually declared where two or more subclasses are expected to do a similar thing in different ways through different implementations. These subclasses extend the same Abstract class and provide different implementations for the abstract methods.

An interface in java is a blueprint of a class. It has static constants and abstract methods only.
Java Interface also represents IS-A relationship.
Syntax
interface interface_name {
}
Example:
/*Actual Code*/
interface Moveable
{
int AVERAGE-SPEED=0;   //what you declare
void move();
}
/*Compiler Code*/
interface Moveable
{
public static final int AVERAGE-SPEED=40;   //what compiler sees
public abstract void move();
}
NOTE : Compiler automatically converts methods of Interface as public and abstract, and the data members as public, static and final by default.
Interface differs from a class in following ways:

1. You cannot instantiate an interface.
2. An interface does not contain any constructors.
3. All of the methods in an interface are abstract.
4. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
5. An interface is not extended by a class; it is implemented by a class.
6. An interface can extend multiple interfaces.

NOTE : A class extends another class, an interface extends another interface but a class implements an interface.

Why we use Java interface??

1. It is used to achieve complete abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.

Rules for using Interface:

1. Methods inside Interface must not be static, final, native or strictfp.
2. All variables declared inside interface are implicitly public static final variables(constants).
3. All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword.
4. Interface can extend one or more other interface.
5. Interface cannot implement a class.
6. Interface can be nested inside another interface.

Example :Interface implementation :
interface Moveable
{
int AVG-SPEED = 60;
void move();
}
class Vehicle implements Moveable
{
public void move()
{
  System.out.println("Average speed is"+AVG-SPEED");
}
public static void main (String[] arg)
{
  Vehicle vc = new Vehicle();
  vc.move();
}
}
Output :

Average speed is 60.
Multiple inheritance in Java by interface:
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.
Example:

interface Printable{ 
   void print(); 

 
interface Showable{ 
   void show(); 

 
class A implements Printable,Showable{ 
 
public void print(){
   System.out.println("Hello");
public void show(){
   System.out.println("Java");

 
public static void main(String args[]){ 
A a = new A(); 
a.print(); 
a.show(); 

Output:
Hello
Java
Interface inheritance:
A class implements interface but one interface extends another interface.

Example:

interface Printable{ 
   void print(); 
interface Showable extends Printable{ 
   void show(); 
class Testinterface2 implements Showable{ 
 
  public void print(){
    System.out.println("Hello");
  } 
  public void show(){
   System.out.println("Java");
  } 
 
  public static void main(String args[]){ 
    Testinterface2 obj = new Testinterface2(); 
    obj.print(); 
    obj.show(); 
  } 

Output:
Hello
Java
Nested Interface in Java:
Note: An interface can have another interface i.e. known as nested interface.
Example:
intserface printable{ 
void print(); 
interface MessagePrintable{ 
   void msg(); 

}
Difference between abstract class and interface?
1.Abstract class can have abstract and non-abstract methods.
2.Interface can have only abstract methods.
3.Abstract class doesn't support multiple inheritance.
4.Interface supports multiple inheritance.
5.Abstract class can have final, non-final, static and non-static variables. 6.Interface has only static and final variables.
7.Abstract class can have static methods, main method and constructor. Interface can't have static methods, main method or constructor.
8.Abstract class can provide the implementation of interface.
9.Interface can't provide the implementation of abstract class.
10.The abstract keyword is used to declare abstract class.
11.The interface keyword is used to
declare interface.
Example:
public abstract class Shape {
    public abstract void draw();
} Example:
public interface Drawable{
    void draw();
}
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Inheritance in Java : Inheritance Top most Conclusion

   

                      Inheritance



  One of the most Basic building blocks of object oriented Programming is inheritance with the help of inheritance Programming task is becoming very simple and lucid ,all we know importance of inheritance a d Java support various types of inheritance excpet Multiple inheritance 







Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class whose properties are inherited is known as superclass (base class, parent class) and the class which inherits the properties of other is known as subclass (derived class, child class).
Inheritance represents the IS-A relationship, also known as parent-child relationship.

extends Keyword

extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.
class Super
{
    String name;
}
class Sub extends Super    
{           
    //methods and fields
    String name; 
    void show()
    {
          super.name = "Super Class";   //name of Super class
          name = "Sub Class";    //name of Sub class
    }
}
super Keyword
In Java, super keyword is used by a subclass whenever it need to refer to its immediate super class.
1. It is used to differentiate the members of superclass from the members of subclass, if they have same names.
2. It is used to invoke the superclass constructor from subclass.
super.variable
super.method();
Purpose of Inheritance
1. To promote Code Reusability.
2. To use Polymorphism.
Types of Inheritance
1. Single Inheritance
When a class extends only one class then we call it a single inheritance. The below examples shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A.
class A {
}
class  B  extends  A {
}
2. Multilevel Inheritance
When a class extends only one class then we call it a single inheritance. The below examples shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A.
class A {
}
class  B  extends  A {
}
class  C  extends B {
}
3. Heirarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.
class A {
}
class  B  extends  A {
}
class  C  extends A {
}
class  D  extends A {
}
NOTE : Multiple inheritance is not supported in java.
Q. Why multiple inheritance is not supported in java???
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
Example:
class A

void msg()
{
System.out.println("Hello");


class B

void msg()
{
System.out.println("Welcome");


class C extends A,B //suppose if it were 
{    
  
Public Static void main(String args[])

  C obj=new C(); 
   obj.msg();           
//Now which msg() method would be invoked? 



Output:
Compile Time Error





If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Example:
class Employee{ 
  int id; 
  String name; 
  Address address; //Address is a class 
  ... 
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
Why use Aggregation??
For Code Reusability.
When use Aggregation??
1. Code reuse is also best achieved by aggregation when there is no IS-A relationship.
2. Inheritance should be used only if the relationship IS-A is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Friday, 29 September 2017

Constructor In Java : Top Most Conclusion

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor:
Constructor name must be same as its class name.
Constructor must not have any explicit return type.
Constructrs can not be abstract, static, final or synchronized.
Example:
class Car
{
String name ;
String model;
Car( )     //Constructor
{
  name ="";
  model="";
}
}
Two types of Constructor:
1.Default constructor
(no-arg constructor) : Default constructor provides the default values to the object like 0, null etc.
2.Parameterized constructor
Default constructor provides the default values to the object like 0, null etc.
Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked
NOTE : If there is no constructor in a class, compiler automatically creates a default constructor.
Constructors Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters.
Why do we Overload constructors ?
Constuctor overloading is done to construct object in different ways.
Example:
class Cricketer
{
String name;
String team;
int age;
Cricketer ()   //default constructor.
{
  name ="";
  team ="";
  age = 0;
}
Cricketer(String n, String t, int a)   //constructor overloaded
{
  name = n;
  team = t;
  age = a;
}
Cricketer (Cricketer ckt)     //constructor similar to copy constructor of c++
{
  name = ckt.name;
  team = ckt.team;
  age = ckt.age;
}
public String toString()
{
  return "This is " + name + " of "+team;
}
}
public class test
{
public static void main (String[] args)
{
  Cricketer c1 = new Cricketer();
  Cricketer c2 = new Cricketer("Sachin", "India", 43);
  Cricketer c3 = new Cricketer(c2 );
  c1.name = "Virat";
  c1.team= "India";
  c1.age = 27;
  System.out.println(c1);
  System.out.println(c2);
  System.out.println(c3);
}
}
Output:
This is Virat of India
This is Sachin of India
This is Sachin of India
Difference between constructor and method in java
Constructor Method
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object.
Constructor must not have return type. Method must have return type.
Object is a physical entity. Class is a logical entity.
Constructor is invoked implicitly. Method is invoked explicitly.
Object is created many times as per requirement. Class is declared once.
The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class name. Method name may or may not be same as class name.
Q. What is constructor chaining in Java??
NOTE : Constructor chaining is a phenomena of calling one constructor from another constructor of same class. Since constructor can only be called from another constructor in Java, constructor chaining is used for this purpose.
class Test
{
Test()
{
  this(10);
}
Test(int x)
{
  System.out.println("x="+x);
}
}
Output:
x=10
Q. Does constructor return any value??
Ans:Yes, Constructor return current class instance (You cannot use return type yet it returns a value).
this keyword is used to refer current class object.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method(implicitly).
this can be passed as an argument in the method or constructor call.
this keyword can also be used to return the current class instance.
Example:
class Box
{
  Double width, weight, dept;
  Box (double w, double h, double d)
  {
   this.width = w;
   this.height = h;
   this.depth = d;
  }
}
Here the this is used to initialize member of current object.
NOTE : Call to this() must be the first statement in constructor.
this is used to call overloaded constructor (or constructor chaining) in java.
class Car
{
private String name;
public Car()
{
  this("BMW");    //oveloaded constructor is called.
}
public Car(Stting n)
{
  this.name=n;   //member is initialized using this.
}
}
this is also used to call Method of that class.
public void getName()
{
System.out.println("BeTheDeveloper");
}
public void display()
{
this.getName();
System.out.println();
}
this is used to return current Object.
public Car getCar()
{
return this;
}
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
variable (also known as class variable).
method (also known as class method).
block.
nested class.
static variable
If you declare any variable as static, it is known static variable.
1. The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
2. The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
NOTE : Java static property is shared to all objects.
Example: Program of counter by static variable.
class Counter{ 
static int count=0;//will get memory only once and retain its value 
 
Counter(){ 
count++; 
System.out.println(count); 

 
public static void main(String args[]){ 
 
Counter c1=new Counter(); 
Counter c2=new Counter(); 
Counter c3=new Counter(); 
 


Output:
1     
2      
3
Static variable vs Instance Variable
Static variable Instance Variable
Represent common property. Instance Variable.
Accessed using class name. Accessed using object.
get memory only once. get new memory each time a new object is created.
Static Method
If you apply static keyword with any method, it is known as static method.
1. A static method belongs to the class rather than object of a class.
2. A static method can be invoked without the need for creating an instance of a class (or objects).
3. static method can access static data member and can change the value of it.
Example: Program to get cube of a given number by static method.
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); 
  } 

Output: 125
Restrictions for static method
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class A{ 
int a=40;  //non static 
  
public static void main(String args[]){ 
  System.out.println(a); 

}       
Output: Compile Time Error
Q. Why java main method is static??
Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
static Block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class S2{ 
  static{System.out.println("static block is invoked");} 
  public static void main(String args[]){ 
   System.out.println("main method is invoked"); 
  } 

Output:
static block is invoked
main method is invoked

Object Oriented Programming : Methods

1.Methods in Java

Method describe behavior of an object. A method is a collection of statements that are group together to perform an operation.

Syntax:

modifier return-type methodName ( parameter-list )
{
       //body of method
}

Example of a Method

public String getName(String st)
{
String name="betheDeveloper.com";
name=name+st;
return name;
}

Modifier : Modifier are access type of method and its optional to use.

Return Type : A method may return value.

Method name : Actual name of the method.

Parameter : Value passed to a method.

Method body : Collection of statement that defines what method does.

Parameter Vs. Argument:

Parameter is variable defined by a method that receives value when the method is called. Parameter are always local to the method they dont have scope outside the method. While argument is a value that is passed to a method when it is called.

The finalize( ) Method:

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general form:

protected void finalize( )
{
   // finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.

2.Call-by-value and Call-by-reference

There are two ways to pass an argument to a method.

Call-by-value:

In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments.

Call-by-reference:

In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.

NOTE : In Java, when you pass a primitive type to a method it is passed by value whereas when you pass an object of any type to a method it is passed as reference.

Example of call-by-value.

public class Test
{
    public void callByValue(int x)
    {
        x=100;
    }
    public static void main(String[] args)
    {
       int x=50;
        Test t = new Test();
        t.callByValue(x);//function call
        System.out.println(x);
    }
   
}
Output : 50
Example of call-by-reference.

public class Test
{
    int x=10;
    inty=20;
    public void callByReference(Test t)
    {
        t.x=100;
        t.y=50;
    }
    public static void main(String[] args)
    {
      
        Test ts = new Test();
        System.out.println("Before "+ts.x+" "+ts.y);
        ts.callByReference(ts);
        System.out.println("After "+ts.x+" "+ts.y);
    }
   
}
Output :
Before 10 20
After 100 50

3.Method Overloading in Java

If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

Advantage of method overloading:

Method overloading increases the readability of the program.

Different ways to overload the method:

By changing number of arguments.

By changing the data type.

NOTE : In java, Methood Overloading is not possible by changing the return type of the method.

In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.

Different ways of Method overloading

1 Method overloading by changing data type of Arguments:

Example

class Calculate
{
void sum (int a, int b)
{
  System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
  System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
  Calculate  cal = new Calculate();
  cal.sum (8,5);      //sum(int a, int b) is method is called.
  cal.sum (4.6, 3.8); //sum(float a, float b) is called.
}
}
Output :

Sum is 13
Sum is 8.4
You can see that sum() method is overloaded two times. The first takes two integer arguments, the second takes two float arguments.

2. Method overloading by changing no. of argument:

Example

class Area
{
void find(int l, int b)
{
  System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h)
{
  System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args)
{
  Area  ar = new Area();
  ar.find(8,5);     //find(int l, int b) is method is called.
  ar.find(4,6,2);    //find(int l, int b,int h) is called.
}
}
Output :
Area is 40
Area is 48

In this example the find() method is overloaded twice. The first takes two arguments to calculate area, and the second takes three arguments to calculate area.

Example of Method overloading with type promotion.

class Area
{
void find(long l,long b)
{
  System.out.println("Area is"+(l*b)) ;
}
void find(int l, int b,int h)
{
  System.out.println("Area is"+(l*b*h));
}
public static void main (String[] args)
{
  Area  ar = new Area();
  ar.find(8,5);     //automatic type conversion from find(int,int) to find(long,long).
  ar.find(2,4,6)    //find(int l, int b,int h) is called.
}
}
Output :
Area is 40
Area is 48

Q. Why Method Overloaing is not possible by changing the return type of method???

In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur. because there was problem.

class Calculation3{ 
  int sum(int a,int b){System.out.println(a+b);} 
  double sum(int a,int b){System.out.println(a+b);} 
 
  public static void main(String args[]){ 
  Calculation3 obj=new Calculation3(); 
  int result=obj.sum(20,20); //Compile Time Error 
 
  } 
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called.

Variable Arguments(var-args):

typeName... parameterName

In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.

Example

public class VarargsDemo {

   public static void main(String args[]) {
      // Call method with variable args 
  printMax(34, 3, 3, 2, 56.5);
      printMax(new double[]{1, 2, 3});
   }

   public static void printMax(double... numbers) {
   if (numbers.length == 0) {
      System.out.println("No argument passed");
      return;
   }

   double result = numbers[0];

   for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println("The max value is " + result);
   }
}
Output:

The max value is 56.5
The max value is56.5

Object Oriented Programming : Class and Object

1.Object Oriented Programming

Since Java is an object oriented language, complete java language is build on classes and object. Java is also known as a strong Object oriented programming language(oops).

OOPS is a programming approach which provides solution to problems with the help of algorithms based on real world. It uses real world approach to solve a problem. So object oriented technique offers better and easy way to write program then procedural programming model such as C, ALGOL, PASCAL.

One of the eight classes of java.lang package are known as wrapper class in java. The list of eight wrapper classes are given below.

Main Features of OOPS

1.Class

2.Object.

3.Inheritence

4.Polymorphism

5.Encapsulation

6.Abstraction

7.Instance

8.Method

9.Message

Now Let see one by one All the Basic Building Blocks of  object oriented Programming

1.Class

In Java everything is encapsulated under classes. Class is the core of Java language. Class can be defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class defines new data type. Once defined this new type can be used to create object of that type.

A class is declared using class keyword. A class contain both data and code that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods.

Object is the physical as well as logical entity whereas class is the logical entity only.

A class in java can contain:

data member

method

constructor

block.

class and interface 

 

Syntax:

class < class_name > {
        data member;
        method;
}

Rules for Java Class:

A class can have only public or default(no modifier) access specifier.

It can be either abstract, final or concrete (normal class).

It must have the class keyword, and class must be followed by a legal identifier.

It may optionally extend one parent class. By default, it will extend java.lang.Object.

It may optionally implement any number of comma-separated interfaces.

The class's variables and methods are declared within a set of curly braces {}.

Each .java source file may contain only one public class. A source file may contain any number of default visible classes.

Finally, the source file name must match the public class name and it must have a .java suffix.

A simple class example:

Suppose, Student is a class and student's name, roll number, age will be its property. Lets see this in Java syntax.

class Student.
{
String name;
int rollno;
int age;
}
When a reference is made to a particular student with its property then it becomes an object, physical existence of Student class.

2.Object

An entity that has state and behavior is known as an object. Object is an instance of class. You may also call it as physical existence of a logical template class.

An object has three characteristics:

state : represents data (value) of an object.

behavior : represents the behavior (functionality) of an object such as deposit, withdraw etc.

identity : Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.

There are three steps when creating an object from a class:

Declaration : A variable declaration with a variable name with an object type.

Instantiation : The 'new' keyword is used to create the object.

Initialization : The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Student std=new Student(); //here std is object of class Student

After the above statement std is instance/object of Student class. Here the new keyword creates an actual physical copy of the object and assign it to the std variable. It will have physical existence and get memory in heap area. The new operator dynamically allocates memory for an object.

Q. Difference between object and class ???

Object Class
Object is an instance of a class. Class is a blueprint or template from which objects are created.
Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc. Class is a group of similar objects.
Object is a physical entity. Class is a logical entity.
Object is created through new keyword mainly e.g.
Student s1=new Student(); Class is declared using class keyword e.g.
Object is created many times as per requirement. Class is declared once.
Object allocates memory when it is created. Class doesn't allocated memory when it is created.
There are many ways to create object in java such as new keyword, newInstance() method, clone() method, factory method and deserialization. There is only one way to define class in java using class keyword.

Q. What are the different ways to create an object in Java ??

There are many ways to create an object in java. They are:

By new keyword.

By newInstance() method.

By clone() method.

By factory method etc.

3.Methods in Java

Method describe behavior of an object. A method is a collection of statements that are group together to perform an operation.

Syntax:

modifier return-type methodName ( parameter-list )
{
       //body of method
}

Example of a Method

public String getName(String st)
{
String name="betheDeveloper.com";
name=name+st;
return name;
}

Modifier : Modifier are access type of method and its optional to use.

Return Type : A method may return value.

Method name : Actual name of the method.

Parameter : Value passed to a method.

Method body : Collection of statement that defines what method does.

Parameter Vs. Argument:

Parameter is variable defined by a method that receives value when the method is called. Parameter are always local to the method they dont have scope outside the method. While argument is a value that is passed to a method when it is called.

The finalize( ) Method:

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general form:

protected void finalize( )
{
   // finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.





Thursday, 28 September 2017

Top 5 String Interview Questions : In Java

1.Write a Java Program to count vowels in a String. It accept a String from command prompt

Program :

public class VowelCounter {

     public static void main(String args[]) {
          System.out.println("Please enter some text");
          Scanner reader = new Scanner(System.in);                 

      String input = reader.nextLine();
          char[] letters = input.toCharArray();

      int count = 0;
    
      for (char c : letters) {
           switch (c) {
              case 'a':
                  case 'e':
                  case 'i':
                  case 'o':
                  case 'u':
                      count++;
          break;
          default:
                  // no count increment
          }

       }
            System.out.println("Number of vowels in String [" + input + "] is : " + count);
     }

}

Output :

Please enter some text
How many vowels in this String
Number of vowels in String [How many vowels in this String] is

2.Write a Program to reverse a String

Program :

public class StringReverseExample {

    public static void main(String args[]) throws FileNotFoundException, IOException {

        //original string
        String str = "Sony is going to introduce Internet TV soon";
        System.out.println("Original String: " + str);

        //reversed string using Stringbuffer
        String reverseStr = new StringBuffer(str).reverse().toString();
        System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);

        //iterative method to reverse String in Java
        reverseStr = reverse(str);
        System.out.println("Reverse String in Java using Iteration: " + reverseStr);

        //recursive method to reverse String in Java
        reverseStr = reverseRecursively(str);
        System.out.println("Reverse String in Java using Recursion: " + reverseStr);

    }

    public static String reverse(String str) {
        StringBuilder strBuilder = new StringBuilder();
        char[] strChars = str.toCharArray();

        for (int i = strChars.length - 1; i >= 0; i--) {
            strBuilder.append(strChars[i]);
        }

        return strBuilder.toString();
    }

    public static String reverseRecursively(String str) {

        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }

        return reverseRecursively(str.substring(1)) + str.charAt(0);

    }
}

3.Write a Java Programs for String Anagram Example.

Program :

public class AnagramCheck {
  
  
    public static boolean isAnagram(String word, String anagram){      
        if(word.length() != anagram.length()){
            return false;
        }
      
        char[] chars = word.toCharArray();
      
        for(char c : chars){
            int index = anagram.indexOf(c);
            if(index != -1){
                anagram = anagram.substring(0,index) + anagram.substring(index +1, anagram.length());
            }else{
                return false;
            }          
        }
      
        return anagram.isEmpty();
    }
  
 

4.Write a  Java Program to find duplicate characters in String.

Program :

public class FindDuplicateCharacters{

    public static void main(String args[]) {
        printDuplicateCharacters("Programming");
        printDuplicateCharacters("Combination");
        printDuplicateCharacters("Java");
    }

    /*
     * Find all duplicate characters in a String and print each of them.
     */
    public static void printDuplicateCharacters(String word) {
        char[] characters = word.toCharArray();

        // build HashMap with character and number of times they appear in String
        Map<Character, Integer> charMap = new HashMap<Character, Integer>();
        for (Character ch : characters) {
            if (charMap.containsKey(ch)) {
                charMap.put(ch, charMap.get(ch) + 1);
            } else {
                charMap.put(ch, 1);
            }
        }

        // Iterate through HashMap to print all duplicate characters of String
        Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
        System.out.printf("List of duplicate characters in String '%s' %n", word);
        for (Map.Entry<Character, Integer> entry : entrySet) {
            if (entry.getValue() > 1) {
                System.out.printf("%s : %d %n", entry.getKey(), entry.getValue());
            }
        }
    }

}

Output:

List of duplicate characters in String 'Programming'
g : 2
r : 2
m : 2
List of duplicate characters in String 'Combination'
n : 2
o : 2
i : 2
List of duplicate characters in String
'Java'
a:2

Wednesday, 27 September 2017

Exception Handling In Java : Top most Conclusion on Exception handling

Exception Handling In Java : Top most Conclusion on Exception handling 



One of the most important topic in Java is Exception handling,  as we know Programming is buddy task  and to handle exception Java Provide by default mechanism called Exception handling .it is also one of the hot topic in interviews whether you are Fresher or experience one exception handling is one of most important topic of the interviewer so guys take a look of my new blog post on Exception handling if you havea ny Question Please comment below..



Exception Handling is the mechanism to handle runtime errors. We need to handle such exceptions to prevent abrupt termination of program.
A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc


What is exception ??

In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime
The code that's responsible for doing something about the exception is called an exception handler.


What is exception handling ??

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario.
statement 1;
statement 2;
statement 3; //exception occurs
statement 4;
statement 5;.
Suppose there is 5 statements in your program and there occurs an exception at statement 3, rest of the code will not be executed i.e. statement 4 and 5 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.
Exception class Hierarchy:
- All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy.
Throwable -> Exception -> RuntimeException
- Exception class is for exceptional conditions that program should catch. This class is extended to create user specific exception classes.
- RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for programs.
Exception are categorized into 3 category:

1) Checked Exception (Compile-time)
The exception that can be predicted by the programmer.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.
1. Using equals() method:
equals() method compares two strings for equality. Its general syntax is,

2) Unchecked Exception (Run-time)
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.

3) Error
Errors are typically ignored in code because you can rarely do anything about an error. Example : if stack overflow occurs, an error will arise. This type of error is not possible handle in code.


2. try-catch

Java Exception Handling Keywords.
There are 5 keywords used in java exception handling.
1) try
2) catch
3) finally
4) throw
5) throws.
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch.
try {
     //code that may throw exception
} catch(Exception_class_Name ref){
    // Handle exception
}
Syntax of try-finally block.
try {
        //code that may throw exception
} finally {
       // code to excecute anyhow
}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
Example using Try and catch
class Excp
{
public static void main(String args[])
{
  int a,b,c;
  try
  {
   a=0;
   b=10;
   c=b/a;
   System.out.println("This line will not be executed");
  }
  catch(ArithmeticException e)
  {
   System.out.println("Divided by zero");
  }
  System.out.println("After exception is handled");
}
}
Output :
Divided by zero
After exception is handled
An exception will thrown by this program as we are trying to divide a number by zero inside try block. The program control is transfered outside try block. Thus the line "This line will not be executed" is never parsed by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program controls continue with the next line in the program. Thus the line "After exception is handled" is printed.


Multiple catch blocks
A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single try block.If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.
Example for Multiple Catch blocks.
class Excep
{
public static void main(String[] args)
{
  try
  {
   int arr[]={1,2};
   arr[2]=3/0;
  }
  catch(ArithmeticException ae)
  {
   System.out.println("divide by zero");
  }
  catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("array index out of bound exception");
  }
  catch(Exception ex)
  {
   System.out.println("any other exception");
  }
}
}
Output : divide by zero
NOTE: At a time only one Exception is occured and at a time only one catch block is executed.
Example for Unreachable Catch block
While using multiple catch statements, it is important to remember that exception sub classes inside catch must come before any of their super classes otherwise it will lead to compile time error.
class Excep
{
public static void main(String[] args)
{
  try
  {
   int arr[]={1,2};
   arr[2]=3/0;
  }
  catch(Exception e)    //This block handles all Exception
  {
   System.out.println("Generic exception");
  }
  catch(ArrayIndexOutOfBoundsException e)    //This block is unreachable
  {
   System.out.println("array index out of bound exception");
  }
}
}
Output : Compile-time error
NOTE: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.
Java Programming & Examples. Get More Example from
https://play.google.com/store/apps/details?id=com.nilstechsys.javaprogrammingexample
Nested try statement
try statement can be nested inside another block of try. Nested try block is used when a part of a block may cause one error while entire block may cause another error. In case if inner try block does not have a catch handler for a particular exception then the outer try is checked for match.
class Excep
{
public static void main(String[] args)
{
  try
  {
   int arr[]={5,0,1,2};
   try
   {
    int x=arr[3]/arr[1];
   }
   catch(ArithmeticException ae)
   {
    System.out.println("divide by zero");
   }
   arr[4]=3;
  }
  catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("array index out of bound exception");
  }
}
}
Important points to Remember
1. If you do not explicitly use the try catch blocks in your program, java will provide a default exception handler, which will print the exception details on the terminal, whenever exception occurs.
2. Super class Throwable overrides toString() function, to display error message in form of string.
3. While using multiple catch block, always make sure that exception subclasses comes before any of their super classes. Else you will get compile time error.
4. In nested try catch, the inner try block, uses its own catch block as well as catch block of the outer try, if required.
5. Only the object of Throwable class or its subclasses can be thrown.
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not and appears at the end of try or catch block.
Example demonstrating finally Clause
Class ExceptionTest
{
public static void main(String[] args)
{
  int a[]= new int[2];
  System.out.println("out of try");
  try
  {
   System.out.println("Access invalid element"+ a[3]);
   /* the above statement will throw ArrayIndexOutOfBoundException */
  }
  finally
  {
   System.out.println("finally is always executed.");
  }
}
}
Output :
Out of try
finally is always executed.
Exception in thread main java.lang.ArrayIndexOutOfBoundException: 3
NOTE : For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).


Try with Resource Statement
JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management.
Syntax:
try ( resource-specification )
{
     //use the resource
} catch( ){
...
}
This try statement contains a paranthesis in which one or more resources is declare. Any object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed as a parameter to try statement. A resource is an object that is used in program and must be closed after the program is finished. The try-with-resources statement ensures that each resource is closed at the end of the statement, you do not have to explicitly close the resources.
Example without using try with Resource Statement.
import java.io.*;
class Test
{
    public static void main(String[] args)
    {
       try{
            String str;
            //opening file in read mode using BufferedReader stream
            BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt"));  
            while((str=br.readLine())!=null)
            {
                 System.out.println(str);
            }     
            br.close();//closing BufferedReader stream
          } catch(IOException ie){
               System.out.println("exception");
          }
    }
}
Example using try with Resource Statement.
import java.io.*;
class Test
{
    public static void main(String[] args)
    {
try(BufferedReader br=new BufferedReader(new FileReader("d:\\myfile.txt")))
{
    String str;
    while((str=br.readLine())!=null)
    {
       System.out.println(str);
    }
} catch(IOException ie){
   System.out.println("exception");
}
    }
}
NOTE: In the above example, we do not need to explicitly call close() method to close BufferedReader stream.



The Java throw keyword is used to explicitly throw an exception.Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.
Syntax:
throw ThrowableInstance
Creating Instance of Throwable class:
There are two possible ways to get an instance of class Throwable,
1. Using a parameter in catch block..
2. Creating instance with new operator.
5. Only the object of Throwable class or its subclasses can be thrown.
new NullPointerException("test");
Example demonstrating throw Keyword
class HelloWorld
{
static void validate(int age)
{
  if(age < 18)
  {
   try
   {
    throw new ArithmeticException("NOT Valid");
   }
   catch(ArithmeticException e)
   {
    System.out.println("Age Invalid Exception Caught");
   }
  }
  else
  {
   System.out.println("Welcome to vote");
  }
}
public static void main(String args[])
{
  validate(13);
}
}
Output : Age Invalid Exception Caught
In the above example the validate() method throw an instance of ArithmeticException, which is successfully handled using the catch statement.


Any method capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword.
Syntax :
return_type  method_name ( parameter_list ) throws exception_list
{
       //definition of method
}
NOTE : It is necessary for CheckedExceptions (Compile-time) and not necessary for RuntimeException (Run-time) and Error, or any of their subclass.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.
There are two cases:
1. Case 1 : You caught the exception i.e. handle the exception using try/catch.
2. Case 2 : You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
class test{ 
void method()throws IOException{ 
  throw new IOException("device error"); //checked exception


public class Testthrows{ 
   public static void main(String args[]){ 
    try{ 
     M m=new M(); 
     m.method(); 
    }catch(Exception e){System.out.println("Exception handled");}    
  } 

Output: Exception handled
Case2: You declare the exception
A) In case you declare the exception, if exception does not occur, the code will be executed fine.
B) In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the exception.
class test{ 
void method()throws IOException{ 
  System.out.println("Device Operation Performed"); 


class Testthrows{ 
   public static void main(String args[]) throws IOException{ //declare exception 
     M m=new M(); 
     m.method(); 
  } 
Output :
A) Device Operation Performed
B) Runtime Exception
NOTE : If you are calling a method that declares an exception, you must either caught or declare the exception.
Difference between throw and throws in Java:
throw throws
Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
Throw is followed by an instance.Throws is followed by class.
Throw is used within the method.Throws is used with the method signature.
You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

Abstract Class & Interface in Java

      Abstract Class & Interface in Java         Here is the most important topic on Java Abstract class and interface, Abstraction ...