Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Monday 31 July 2017

Interface Programs In Java

Java Interface

implements in java

Java interface is a blueprint of a class and all the data members of an interface are public, static, and final by default and all the methods are public and abstract by default.

It is used to achieve fully abstraction and multiple inheritance in java.

We cannot create an object of an interface just like an abstract class but there are many differences between abstract class and interface in java.

So let's start with simple interface program in java with the output.


Java Interface Example

interface Teacher
{
void show();//compiler will add public abstract internally
}
class Student implements Teacher
{
public void show()
{
System.out.println("Teacher teach all the students");
}
public static void main(String args[])
{
Student s = new Student();
s.show();
}
}

Output : Teacher teach all the students


Java Interface Example 2

By this example, we can achieve multiple inheritance through the interface. The specific implementation of run() and laugh() method is provided by it child class i.e ThirdPerson class. And work() is a personal method of child class i.e ThirdPerson class. 

interface FirstPerson
{
void run();
}
interface SecondPerson
{
void laugh();
}
class ThirdPerson implements FirstPerson,SecondPerson
{
public void run()
{
System.out.println("Person first is running");
}
public void laugh()
{
System.out.println("Person second is laughing");
}
void work()
{
System.out.println("Person third doing hard work");
}
public static void main(String args[])
{
ThirdPerson t = new ThirdPerson();
t.run();
t.laugh();
t.work();
}
}

Output : Person first is running
              Person second is laughing
              Person third doing hard work

So the main use of interface in java is to achieve fully abstraction and multiple inheritance easily.


Java Interface Example - With Default Method

The default method is the new feature of java 8 version. By the help of this default method, we can keep method with body i.e non-abstract method in an interface.

interface Employee
{
public default void work()
{
System.out.println("Employee work as software developer");
}
void manage();//abstract method
}
class Employee1 implements Employee
{
public void manage()
{
System.out.println("Employee manage other departments also");
}
public static void main(String args[])
{
Employee1 e = new Employee1();
e.work();
e.manage();
}
}

Output : Employee work as software developer
              Employee manage other departments also


Java Interface Example - One interface extends another Interface

interface First
{
void show();
}
interface Second extends First
{
void display();
}
class Test implements Second
{
public void show()
{
System.out.println("hello, how are you");
}
public void display()
{
System.out.println("hello, i am fine");
}
public static void main(String... s)
{
Test t = new Test();
t.show();
t.display();
}
}

Output : hello, how are you
              hello, i am fine

Java Interface Example - With Abstract Class

interface First
{
void show();
void display();
void get();
}
abstract class Simple implements First
{
abstract void run();
public void show()
{
System.out.println("hi show");
}
public void display()
{
System.out.println("hi display");
}
}
class Test extends Simple
{
public void get()
{
System.out.println("hi get");
}
void run()
{
System.out.println("hi run");
}
public static void main(String args[])
{
Test t = new Test();
t.show();
t.display();
t.get();
t.run();
}
}

Output : hi show
              hi display
              hi get
              hi run

Share:

Sunday 30 July 2017

Difference Between Abstract Class and Interface In Java

Java Abstract Class vs Interface

Java Abstract Class vs Interface

Now, Here we will learn what is the difference between abstract class and interface. This topic is very important for java interview point of view.

So let's starts.

Abstract Class

  • An abstract keyword is used to declare the abstract class.
  • An abstract class can extend only one class or one abstract class at a time.
  • An abstract class can extend from a class or from an abstract class.
  • It can contain abstract method (without body) and non-abstract method(with a body).
  • It doesn't support multiple inheritance.
  • It can have static or non-static variables and final or non-final variables and static final variables.


  • It can provide the implementation of an interface.
  • By the help of the abstract class, we cannot achieve full abstraction.
  • We can declare a constructor inside the abstract class.
  • In an abstract class, the data members are not public, static and final by default.
  • In an abstract class, the method is not public and abstract by default.
  • We can use public, private and protected access modifiers with the abstract class method.


Syntax :

(1) How to declare an abstract class?

abstract class Test
{
-----
-----
}

(2) How to declare an abstract method(without body) or non-abstract method(with a body) in the abstract class.

abstract class Test
{
abstract void show();//abstract method
void show()
{
-----
-----
}
}



Java Abstract Class Example

In this example, we are going to use one abstract method and non-abstract method in an abstract class.

abstract class Tiger
{
abstract void eat();//abstract method
void run()
{
System.out.println("Lion run fast");
}
}
class Dog extends Tiger
{
void eat()//provide impelementation of Tiger eat() method
{
System.out.println("Dog eat cat");
}
public static void main(String args[])
{
Dog d = new Dog();
d.eat();
d.run();
}
}

Output : Dog eat cat
              Lion run fast


Java Interface

  • The interface keyword is used to declare the interface.
  • An interface can extend more than one interface at the same time.
  • An interface can extend only from an interface i.e a class implements interface but an interface extends another interface not implement.
  • An interface can have the only abstract method but since java 8  it can have default and static method also.
  • By using interface, we can achieve multiple inheritance.
  • In an interface, all the data members or variables are by default public static and final.
  • An interface cannot provide the implementation of the abstract class.
  • By using the interface, we can easily achieve the full abstraction.
  • We can't declare the constructor inside the interface.
  • In an interface, all the data members are by default public static and final.
  • In an interface, all the method are public abstract by default.
  • But here we cannot use private, protected access modifiers with interface method because interface method is by default public.

Java Interface Example

interface Parent
{
void task();//by default public and abstract
public default void drink()
{
System.out.println("Parent drink water");
}
}
class Child implements Parent
{
public void task()
{
System.out.println("Parent handle child");
}
public static void main(String args[])
{
Child c = new Child();
c.task();
c.drink();
}
}

Output : Parent drink water
Share:

Thursday 27 July 2017

Static Import In Java

Java Static Import

Static Import In Java

The java static import feature is introduced in Java 5 and by using static import feature of java 5, the java programmer can access any static member i.e static field or a static method of a class directly. And there is no need to class name to call any method or field of a class.


When to Use Static Imports?

Now there is a question that when to use static import? Suppose you are going to use static variables or methods a lot so for you, it will be better
to use the static import. For example, if you are going to write a code for mathematical calculation then here you should use static import in java.

Advantage of Static Import In Java

  1. The first advantage of java static import is that it reduces the code length.
  2. The static import saves time because it reduces the length of the code. 


Drawbacks of Static Import In Java

  • The static import feature reduces the readability of java program.
  • If you use java static import much time, it makes a program unreadable and unmaintainable.
Let's understand with examples, I am sure you will be better understood with an example.

Java Simple Example - Without Static Import

public class Simple
{
public static void main(String args[])
{
double d1 = Math.sqrt(6.0);//Using class name Math
double d2 = Math.tan(50);//Using class name Math
System.out.println("Square of 6 is : "+d1);
System.out.println("Tan of 50 is : "+d2);
}
}

Output: Square of 6 is : 2.449489742783178
              Tan of 50 is : -0.27190061199763077

In the above example, There we did not use any static import therefore we have to use the class name as I mention above e.g Math.




Java Static Import Example

In this example, we will import Math class i.e static import.

import static java.lang.Math.*;
public class Demo
{
public static void main(String args[])
{
double d1 = sqrt(6.0);//Using static method without Math class
double d2 = tan(50);//Using static method without Math class
System.out.println("Square of 6 is : "+d1);
System.out.println("Tan of 50 is : "+d2);
}
}

Output: Square of 6 is : 2.449489742783178
              Tan of 50 is : -0.27190061199763077

In the above example, here we import i.e static import of a Math, therefore, we did not use Math class here.


Java Static Import Example 1

This is another example of java static import, here in this example we will import static import of a System class.

import static java.lang.System.*;
public class SystemExample
{
public static void main(String args[])
{
out.println("Hello java ");//There is no need of System class
out.println("I love java ");
out.println("Wow javaaaa ");
}
}

Output: Hello java 
              I love java 
              Wow javaaaa

In the above example, We did not use System class in System.out.println() statement because of static import of System class. So there is no need to use System class to call any method or variable.

Now we have learned so many things about "static" like static keyword in java(static variable, static method and static class), static import in java, etc. 

Share:

Wednesday 26 July 2017

Thread Pool In Java

Java Thread Pool

Java Thread Pool

Thread pool in java manages the pool of worker thread i.e Thread pool represents a group of worker threads that are waiting for the job and reuse many times.

Most of the executor implementations in java.util.concurrent use thread pool which consists of worker thread.

In thread pool environment, a group of fixed size thread are created.

This type of pool always has a specified numbers of thread running, if a thread is somehow terminated while it is still in use, it is automatically replaced with new thread.

Thread pool contains a queue that keeps tasks waiting to get executed and here to create a new thread pool in java we can use ThreaPoolExecutor. 

This kind of thread exists separately from the Runnable and Callable tasks it executes and it is used to execute multiple tasks.

 In java, Using worker threads minimizes the overhead due to thread creation. Here Thread object use a significant amount of memory, and in a large scale application and allocating and deallocating many thread objects creates a significant memory management overhead.


Advantage of Java Thread Pool

  • It saves time because there is no need to create a new thread.

Usage of Thread Pool In Java

  • Java Thread pool mostly used in Servlet and JSP where container creates a Thread pool.

Java Thread Pool Example

Let's take look of simple example of java thread pool by using ExecutorService and Executors.

//WorkerThread.java

public class WorkerThread implements Runnable
{
private String command;
public WorkerThread(String s)
{
this.command = s;
}
public void run()
{
System.out.println(Thread.currentThread().getName()+"start.command = "+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End. ");
}
private void processCommand()
{
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}

public String toString()
{
return this.command;
}
}




Java ExecutorService Example

This is the test program class ThreadPoolExample.java where we are creating fixed thread pool from Executors Framework.

//ThreadPoolExample.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample
{
public static void main(String args[])
{
ExecutorService executor = Executors.newFixedThreadPool(5);
for(int i = 0; i<10; i++)
{
Runnable worker = new WorkerThread("" +i);
executor.execute(worker);
}
executor.shutdown();
while(!executor.isTerminated())
{
}
System.out.println("finished all thread");
}
}

output : pool 1 -1- thread-1 start.command = 0
              pool 1 -1- thread-2 start.command = 1
              pool 1 -1- thread-5 start.command = 4
              pool 1 -1- thread-4 start.command = 3
              pool 1 -1- thread-3 start.command = 2
              pool 1 -1- thread-1 End.
              pool 1 -1- thread-2 End.
              pool 1 -1- thread-2 start.command = 1
              pool 1 -1- thread-5 start.command = 6
              pool 1 -1- thread-5 End.
              pool 1 -1- thread-4 End.
              pool 1 -1- thread-5 start.command = 7
              pool 1 -1- thread-4 start.command = 8
              pool 1 -1- thread-3 End.
              pool 1 -1- thread-3 start.command = 9
              pool 1 -1- thread-2 End.
              pool 1 -1- thread-1 End.
              pool 1 -1- thread-5 End.
              pool 1 -1- thread-4 End.
              pool 1 -1- thread-3 End.
              finished all thread

In the above example, There are fixed size thread pool of 5 workers threads and then we submitting 10 jobs to this pool. Since the thread pool size is 5, it will start working on 5 jobs and other jobs will be in the wait state and as soon as one of the jobs is finished, another job from the wait queue will be picked up by the worker thread and get's executed.

Share:

Difference Between Constructor and Method In Java

Java Constructor vs Method

Difference Between Constructor and Method In Java

Now here we will discuss some differences between Constructor and Method in java programming language. This is the very important question for interview point of view. So let's starts....

First we discuss about java constructor.


Constructor

  • Java constructor basically used to initialize the state of an object i.e putting a value into the data member of a class.
  • Java constructor name must be same as the class name.
  • Java constructor should not have any return type(even void).
  • Constructor will be called automatically whenever object is created.
  • The java compiler provides a default constructor if we do not have any constructor in a java program.
  • Java constructor cannot be a final, abstract, static and synchronized.


Java Constructor Example

In this example, we are going to use default constructor and parameterized constructor. Both constructor will be called automatically when object is created.

public class Student
{
int rollno;//data member
String name;//data member
Student()
{
System.out.println(" this is a default constructor ");
}
Student(int rollno, String name)
{
System.out.println(" this is a parameterized constructor ");

this.rollno = rollno;
this.name = name;
System.out.println(rollno+ " "+name);
}
public static void main(String args[])
{
Student s = new Student();//default constructor will be call
Student s1 = new Student(101, " raghu");//parameterized constructor will be called
}
}

output : this is a default constructor
              this is a parameterized constructor
              101 raghu


Method

  • Method is used to expose behavior of an object i.e action or task or operation.
  • Method name may or may not be same as class name.
  • Method must have return type.
  • Method should be called explicitly either with class reference or object reference.
  • The java compiler does not provide any default or parameterized method in java.
  • Method can be final, abstract, static and synchronized.



Java Method Example

In this example, we will define a class in which we take some methods to perform some specific task or action or operation.

public class Employee
{
static void work()//static method
{
System.out.println("Employee work as a senior java developer");
}
void manage()
{
System.out.println("Employee manage all junior java developer");
}
public static void main(String args[])
{
Employee.work();//static method can be access by using class name
Employee e = new Employee();
e.manage();//need object reference to call method
}
}

output : Employee work as a senior java developer
              Employee manage all junior java developer

Q. When use default constructor and when use paremeterized constructor in java.

Ans. When we want to provide the default value or same value to each object then we use default constructor in java and when we want to provide different-different values to each object then we use parameterized constructor in java.

Q. Can we make any constructor as private constructor ?.

Ans. Yes, we can make any constructor as private constructor in java but if we make any constructor as private then we cannot create an object of that class to outside of a class.

Q. Can we override main method in java ?.

Ans. No, We cannot override main method in java.

Share:

Monday 24 July 2017

Inheritance Programs In Java

Java Inheritance

Inheritance Programs in Java

Java inheritance means re-usability. In java inheritance, child class inherits parent class so that child class can use the data member and member function of its parent class.

Child class can reuse the properties and behavior of parent class and child class can also add a personal methods.

In java Basically java inheritance represents Is-a relationship i.e parent child relationship.

Java inheritance basically used to achieve method overriding or dynamic binding in java and it is also used for code re-usability.

There are 5 types of inheritance in java, These are

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

In java there are five types of inheritance but through a class there are 3 types of inheritance is supported which is single level, multilevel and hierarchical inheritance.

Java doesn't support multiple inheritance through class but multiple inheritance can be achieved through interface in java.

So here we will discuss only 3 types of inheritance which can be achieved through class.

So let's starts.

(1) Single Level Inheritance

In single level inheritance, When a class inherit another class class is known as single level inheritance e.g class B extends class A.

Java Single Level Inheritance Example

class Vehicle
{
void speed()
{
System.out.println("Vehicle's average speed is 40");
}
}
class Honda extends Vehicle
{
void run()
{
System.out.println("Honda run fast");
}
public static void main(String args[])
{
Honda h = new Honda();//creating Honda's object
h.speed();//calling Vehicle's method 
h.run();
}
}

output : Vehicle's average speed is 40
              Honda run fast

In the above example, Honda class inherit the Vehicle class and by using object of Honda class we can access the methods of Vehicle class because Honda class inherit the Vehicle class.


(2) Multilevel Inheritance

Java multilevel inheritance means when class C extends class b and class B extends class A i.e class C extends B extends A.

Java Multilevel Inheritance Example

class Principal
{
void manageTeachers()
{
System.out.println("Principal manage teachers");
}
}
class Teacher extends Principal 
{
void manageStudents()
{
System.out.println("Teacher manage students");
}
}
class Student extends Teacher
{
void read()
{
System.out.println("Students reads book");
}
public static void main(String args[])
{
Student s = new Student();
s.manageTeachers();
s.manageStudents();
s.read();
}
}

output : Principal manage teachers
              Teacher manage students
               Students reads book


(3) Java Hierarchical Inheritance

In java hierarchical inheritance 2 different class extends same class i.e class C extends class A and class B extends class A.

Java Hierarchical Inheritance Example

class Principal
{
void manageAll()
{
System.out.println("Principal manage all");
}
}
class Teacher extends Principal 
{
void manageStudents()
{
System.out.println("Teacher manage students");
}
}
class Student extends Principal
{
void read()
{
System.out.println("Students reads book");
}
public static void main(String args[])
{
Student s = new Student();
s.manageAll();
s.manageStudents();
s.read();
}
}

output :  Principal manage all
               Teacher manage students
               Students reads book

Q. Can we achieve multiple inheritance through class in java ?

Ans. No, we cannot achieve multiple inheritance through class in java but it is possible through interface.

Q. Can we inherit final class in java ?

Ans. No, we cannot inherit final class in java.

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate