Sunday, March 15, 2026

Python String join() Method

When working with text in Python, you’ll often need to combine multiple strings into one. The Python String join() method is the most efficient way to achieve this. It takes an iterable (like a list, tuple, set, dictionary, or even another string) and concatenates all its elements into a single string, inserting a specified separator between them

join() method syntax

str.join(iterable)

Here iterable is an object which can return its element one at a time like list, tuple, set, dictionary, string.

str represents a separator that is used between the elements of iterable while joining them.

All the values in iterable should be String, a TypeError will be raised if there are any non-string values in iterable.

Python join() method examples

1. join method with a tuple.

cities = ('Chicago','Los Angeles','Seattle','Austin')
separator = ':'
city_str = separator.join(cities)
print(city_str)

Output

Chicago:Los Angeles:Seattle:Austin

2. Python join() method with a list of strings.

cities = ['Chicago','Los Angeles','Seattle','Austin']
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

Chicago|Los Angeles|Seattle|Austin

3. TypeError if non-string instance is found.

cities = ['Chicago','Los Angeles','Seattle','Austin', 3]
separator = '|'
city_str = separator.join(cities)
print(city_str)

Output

    city_str = separator.join(cities)
TypeError: sequence item 4: expected str instance, int found

In the list there is an int value too apart from strings therefore TypeError is raised while attempting to join the elements of the list.

4. Python join() method with a Set. Since set is an unordered collection so sequence of elements may differ.

cities = {'Chicago','Los Angeles','Seattle','Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

Austin-Los Angeles-Chicago-Seattle

5. join() method with a Dictionary. In case of dictionary keys are joined not the values.

cities = {'1':'Chicago','2':'Los Angeles','3':'Seattle','4':'Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)

Output

1-2-3-4

That's all for this topic Python String join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python String split() Method
  2. Check if String Present in Another String in Python
  3. pass Statement in Python
  4. Namespace And Variable Scope in Python
  5. Interface in Python

You may also like-

  1. Python Installation on Windows
  2. Class And Object in Python
  3. Keyword Arguments in Python
  4. Bubble Sort Program in Python
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. final Keyword in Java With Examples
  7. BeanPostProcessor in Spring Framework
  8. How to Write a Map Only Job in Hadoop MapReduce

Check if String Present in Another String in Python

When working with text, you’ll often need to check if a string is present in another string in Python. Thankfully, Python provides multiple simple and efficient ways to perform this task:

  • Use Python membership operators 'in' and 'not in'. This is the most Pythonic way to check substring existence. See example.
  • Using find() method to check if string contains another string. See example.
  • Using index() method to get the index of the substring with in the String. See example.

Python membership operators - in and not in

To check if a string exists inside another string in Python or not, you can use 'in' and 'not in' membership operators.

  • 'in' operator- Returns true if the string is part of another string otherwise false.
  • 'not in' operator- Returns true if the string is not part of another string otherwise false.

Python in operator example

def check_membesrship(str1, str2):
  if str2 in str1:
    print(str2, 'found in String')
  else:
    print(str2, 'not found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String
That not found in String

Python not in operator example

def check_membesrship(str1, str2):
  if str2 not in str1:
    print(str2, 'not found in String')
  else:
    print(str2, 'found in String')

str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, 'That')
#another call
check_membesrship(str1, str2)

Output

That not found in String
Python found in String

Using find() method to check if substring exists in string

Using find() method in Python you can check if substring is part of the string or not. If found, this method returns the index of the first occurrence of the substring otherwise -1 is returned.

Python find() method example

def check_membesrship(str, substr):
  loc = str.find(substr)
  if loc == -1:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

Using index() method to check if substring exists in string

Using index() method in Python you can check if substring is part of the string or not. This method is similar to find() and returns the location of the first occurrence of the substring if found. If not found then index() method raises ‘ValueError’ exception that's where it differs from find().

Python index() method example

def check_membesrship(str, substr):
  # Catch ValueError exception
  try:
    loc = str.index(substr)
  except ValueError:
    print(substr, 'not found in String')
  else:
    print(substr, 'found in String at index', loc)


str1 = "This is Python"
str2 = "Python"
check_membesrship(str1, str2)
#another call
check_membesrship(str1, 'That')

Output

Python found in String at index 8
That not found in String

That's all for this topic Check if String Present in Another String in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. String Slicing in Python
  2. Accessing Characters in Python String
  3. Python String join() Method
  4. Magic Methods in Python With Examples
  5. Nonlocal Keyword in Python With Examples

You may also like-

  1. Name Mangling in Python
  2. Operator Overloading in Python
  3. Passing Object of The Class as Parameter in Python
  4. Difference Between Function and Method in Python
  5. instanceof Operator in Java
  6. Java Exception Handling Tutorial
  7. Checking Number Prime or Not Java Program
  8. Spring Setter Based Dependency Injection

Saturday, March 14, 2026

Java Map putIfAbsent() With Examples

Introduced in Java 8, the putIfAbsent() method is part of the java.util.Map interface and is widely used to simplify conditional insertions. It allows you to insert a new value for a given key only if that key is not already associated with a value or is currently mapped to null. This makes it a cleaner alternative to manually checking for key existence before updating a map.

The default implementation for putIfAbsent() is as given below. As you can see just by using single method putIfAbsent() you get the logic of checking whether the key is already present or not in the map and putting the value in case key is not there (or associated value is null).

 V v = map.get(key);
 if (v == null)
     v = map.put(key, value);
 return v;

Alongside putIfAbsent(), there is also a computeIfAbsent() method in Java, which also puts a value if specified key is not already associated with a value but with one key difference, instead of directly inserting a value, it computes the value using a provided mapping function if the key is not already present.

Syntax of the putIfAbsent () method is as given below.

V putIfAbsent(K key, V value)

Parameters are as-

  • key- key with which the specified value is to be associated
  • value- value to be associated with the specified key

Method returns the previous value if the specified key is already associated with the value.

Returns null if specified key is not already present in the Map, which actually means key is absent and the method is inserting the given key, value pair in the Map. It may also mean that the key is present but associated with null value.

putIfAbsent() Java examples

1. In the first example we'll have a map of cities and we'll try to insert a new city with a key which already exists in the HashMap.

import java.util.HashMap;
import java.util.Map;

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- Berlin
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}

Since key already exists and mapped with a value in the HashMap so putIfAbsent() method won't replace the previous value with new value for the same key. Also notice the return value of the method which is the value associated with the specified key.

2. In this example we'll try to insert a new city with a key which is not already there in the Map.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("5", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin, 5=London}

Since key is not there in the Map so a new entry is added to the HashMap. Also notice the return value of the putifAbsent() method which is null this time because there was no mapping for the key.

3. In this example we'll take the scenario when the key exists in the HashMap but mapped with null.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", null);
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=London}

Since the key is mapped to null so putIfAbsent() method associates the key with a new value.

That's all for this topic Java Map putIfAbsent() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map merge() With Examples
  2. Java Map getOrDefault() Method With Examples
  3. Map.Entry Interface in Java
  4. EnumSet in Java With Examples
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Java StampedLock With Examples
  2. CopyOnWriteArraySet in Java With Examples
  3. Garbage Collection in Java
  4. Difference Between Checked And Unchecked Exceptions in Java
  5. How to Read Excel File in Java Using Apache POI
  6. Spring Boot StandAlone (Console Based) Application Example
  7. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
  8. Angular @HostBinding Decorator With Examples

isAlive() And join() Methods in Java Multi-Threading

In this tutorial we'll see what are isAlive() and join() methods in Java, which give you precise control over thread lifecycle management, ensuring smoother synchronization and more predictable program behavior.

When working with multiple threads in Java, developers typically create threads and invoke the start() method to begin execution. Once started, the Java Virtual Machine (JVM) automatically calls the run() method when system resources and CPU are available. The thread then executes its task and eventually transitions to the terminated state.

But what if you need to trigger further processing only after a specific thread has finished? How can you reliably check whether a thread is still running or has ended?

This is where the isAlive() and join() methods in Java come into play. These two powerful methods in Java’s multithreading API allow you to:

  • isAlive()– Quickly verify if a thread is still active.
  • join()– Pause the execution of the current thread until the target thread completes.

isAlive() method in Java

isAlive() method is the member of the Thread class and its general form is–

public final boolean isAlive()

The isAlive() method in Java is used to check whether a thread is currently active. A thread is considered alive if it has been started using the start() method and has not yet reached the terminated state. When you call isAlive() on a thread object, it returns:

  • true- if the thread is still running or in a runnable state.
  • false- if the thread has finished execution or has not been started

This makes the isAlive() method a simple yet powerful way to monitor thread lifecycle and ensure that your program executes tasks in the correct order. By combining isAlive() with other multithreading techniques, developers can build more predictable and synchronized applications.

join() method in Java

Join() method is used when you want to wait for the thread to finish. Its general form is–

public final void join() throws InterruptedException

This method waits until the thread on which it is called terminates. There are three overloaded join functions.

  • public final void join()- Waits indefinitely for this thread to die.
  • public final void join(long millis)-Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
  • public final void join(long millis, int nanos)- Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

Java Example code using join and isAlive()

Imagine a situation where your application spawns multiple threads to perform heavy computations. You want the user to see the message "Processing is done" only after all threads have completed their tasks.

In such cases, the join() method in Java is the ideal solution. By calling join() on a thread, the current thread (often the main thread) pauses execution until the specified thread finishes. This ensures that your program doesn’t move forward prematurely and that the final message is displayed only after all computations are complete

Now first let’s try to do something like this without using join() method.

class MyRunnableClass implements Runnable{
  @Override
  public void run() {
    for(int i = 0; i < 5 ; i++){
      System.out.println(Thread.currentThread().getName() + " i - " + i);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }    
}
public class JoinExample {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnableClass(), "t1");
    Thread t2 = new Thread(new MyRunnableClass(), "t2");
    Thread t3 = new Thread(new MyRunnableClass(), "t3");
     
    t1.start();
    t2.start();
    t3.start();
        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
        
    /*try {
        t1.join();        
        t2.join();
        t3.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());*/        
    System.out.println("Processing finished");
  }
}

Output

t1 Alive - true
t2 Alive - true
t3 Alive - true
Processing finished
t3 i - 0
t1 i - 0
t2 i - 0
t3 i - 1
t1 i - 1
t2 i - 1
t2 i - 2
t1 i - 2
t3 i - 2
t3 i - 3
t1 i - 3
t2 i - 3
t3 i - 4
t1 i - 4
t2 i – 4

Here it can be seen that the message is displayed much before the actual processing has finished.

Now let’s uncomment the code related to join and run the program again.

class MyRunnableClass implements Runnable{
  @Override
  public void run() {
    for(int i = 0; i < 5 ; i++){
      System.out.println(Thread.currentThread().getName() + " i - " + i);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
}
public class JoinExample {
  public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnableClass(), "t1");
    Thread t2 = new Thread(new MyRunnableClass(), "t2");
    Thread t3 = new Thread(new MyRunnableClass(), "t3");
     
    t1.start();
    t2.start();
    t3.start();
    
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
        
    try {
      t1.join();        
      t2.join();
      t3.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
        
    System.out.println("t1 Alive - " + t1.isAlive());
    System.out.println("t2 Alive - " + t2.isAlive());
    System.out.println("t3 Alive - " + t3.isAlive());
    
    System.out.println("Processing finished");
  }
}

Output

t1 Alive - true
t2 Alive - true
t3 Alive - true
t2 i - 0
t3 i - 0
t1 i - 0
t1 i - 1
t2 i - 1
t3 i - 1
t3 i - 2
t1 i - 2
t2 i - 2
t1 i - 3
t2 i - 3
t3 i - 3
t2 i - 4
t3 i - 4
t1 i - 4
t1 Alive - false
t2 Alive - false
t3 Alive - false
Processing finished

Now see how message is displayed only when the processing is actually finished and all the threads are terminated. The second print statements using isAlive() method confirms that the threads are not running any more.

That's all for this topic isAlive() And join() Methods in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between sleep And wait in Java Multi-Threading
  2. Creating a Thread in Java
  3. Synchronization in Java - Synchronized Method And Block
  4. Race Condition in Java Multi-Threading
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Creating Custom Exception Class in Java
  2. Interface Static Methods in Java
  3. Fail-Fast Vs Fail-Safe Iterator in Java
  4. Java Lambda Expression And Variable Scope
  5. Find All Permutations of a Given String Java Program
  6. Abstraction in Java
  7. Java ReentrantReadWriteLock With Examples
  8. Bean Scopes in Spring With Examples

Friday, March 13, 2026

static Method Overloading or Overriding in Java

One of the most frequently asked interview questions in Java is: Can we overload static methods in Java? Can we override static methods in Java? These questions often confuse developers, yet understanding them is essential for mastering object-oriented programming concepts.

In this tutorial, we’ll explore the rules and limitations of static method overloading and static method overriding in Java. To set the stage, we’ll first revisit the basics of method overloading and method overriding in Java, and then dive into how these concepts apply specifically to static methods.

  • Method Overloading- When two or more methods with in the same class or with in the parent-child relationship classes have the same name, but the parameters are different in types or number the methods are said to be overloaded.
    Refer Method overloading in Java for better understanding.
  • Method Overriding- In a parent-child relation between classes, if a method in subclass has the same signature as the parent class method then the method is said to be overridden by the subclass and this process is called method overriding.
    Refer Method overriding in Java for better understanding.

Static method overloading in Java

In Java, static methods can be overloaded just like instance methods. This means you can define two or more static methods with the same name, as long as their parameter lists differ in type or number. Overloading static methods works exactly the same way as overloading non-static methods, and it is resolved at compile time.

Fail-Fast Vs Fail-Safe Iterator in Java

Understanding the difference between fail fast and fail safe iterator in Java is not only a popular Java Collections interview question but also a crucial concept for every developer. The collections which are there from Java 1.2 (or even legacy) like ArrayList, Vector, HashSet all have fail-fast iterator whereas Concurrent collections added in Java 1.5 like ConcurrrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet have fail-safe iterator.

In this guide, we’ll break down the key differences between fail-fast and fail-safe iterator in Java, highlight their behavior with practical examples, and then walk through Java programs that demonstrate how each type of iterator works in real-world scenarios.

Thursday, March 12, 2026

Interface in Java With Examples

In this tutorial, you’ll dive deep into the concept of Interface in Java, a powerful feature that enables developers to achieve complete abstraction in Java. An interface defines what a class must do, but leaves the details of how it should be done to the implementing class. This makes interfaces a cornerstone of clean, modular, and flexible Java programming


How does Interface differ from a class

Although an Interface in Java looks syntactically similar to a class, it differs in several important ways:

  • Interfaces cannot have instance variables, meaning they don’t maintain state.
  • Methods inside an interface are declared without a body and end with a semicolon.
  • An interface cannot be instantiated, so constructors are not allowed.
  • A class implements an interface rather than extending it.
  • An interface itself can extend multiple interfaces, supporting multiple inheritance in Java.

Please note that, Java 8 onward, it is possible to add a default implementation to a method in an interface as well as interface static methods and even Private Methods in Java Interface Java 9 onward, here we'll discuss interfaces in its normal form.

General form of interface in Java

access_modifier interface name {
 type final_var1 = value;
 type final_var2 = value;
 ----
 ----
 return_type method_name1(param_list);
 return_type method_name2(param_list);
 ----
 ----
}

When no access modifier is specified, an Interface in Java has default access, meaning it is visible only to other members within the same package. However, when an interface is declared as public, it becomes universally accessible and can be used by any program across different packages.

For top level interfaces only these two access modifiers (default and public) are permitted, there are nested interfaces which can be declared as public, private or protected. We'll discuss nested interfaces later in the post.

All variables declared inside an Interface in Java are implicitly public, static, and final. This means they act as constants: they must be initialized at the time of declaration and cannot be modified by the implementing class. Such behavior ensures consistency and prevents accidental changes across different implementations.

Similarly, all methods within an Interface in Java are implicitly abstract and public. These methods define the contract that any implementing class must fulfill, but they do not provide the actual implementation. By enforcing this rule, interfaces promote clean design, flexibility, and a clear separation of responsibilities in Java applications

Note that Java 9 onward you can also add private methods to a Java interface. Please refer Private Methods in Java Interface to know more about adding private methods in a Java interface.

Java Interface example

public interface MyInterface {
 int i = 10;
 Number method1();
 void method2(String Id);
}

Here is an interface MyInterface which has one variable i, which is public static final implicitly. There are 2 methods, one has no return type, one returns Number.

Implementing an Interface in Java

In Java, class uses implements keyword to implement an interface.

public class MyClass implements MyInterface { 
 public Integer method1() {
  System.out.println("in method 1" + i);  
  return null;
 }

 public void method2(String Id) {
  System.out.println("in method 2");  
 }
 public static void main(String[] args) {
  
 }
}

When implementing methods defined in interfaces there are several important points-

  • A class can implement more than one interface, in that case interfaces are separated with a comma.
     class class_name implements interface 1, interface 2{
     }
     
  • The methods of an interface that are implemented by a class must be declared public i.e. visibility can't be reduced.
  • The signature of the interface method must remain same while implementing it. In case of return type subclass of the return type as defined in interface can also be used. As in the above program method1 has the return type Number where as in the implemented method in the class has the return type Integer. It is permissible as Integer is the sub-class of Number.
  • The initialized variable in the interface is constant and it is not allowed to change that value in the implementing class. For example in the above program there is a variable i with value 10 if we try to change that value to 20 in the implementing class it will throw compiler error "The final field MyInterface.i cannot be assigned".
  • Any number of classes can implement an interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.
  • A class can extend only one class, but a class can implement many interfaces. Which means multiple inheritance is not allowed in Java
  • An interface can extend another interface, similar to the way that a class can extend another class.

Extending an interface in Java

Just like class, if an interface in Java is inheriting from another interface it uses extends keyword.
An interface, unlike class, can extend more than one interface. If a class implements an interface that inherits another interface, it must provide implementation for all the methods that are there in the inheritance chain of interface.

Extending an interface Java Example

// Interface
public interface MyInterface {
 int i = 10;
 Number method1();
 void method2(String Id);
}
// extending interface
interface B extends MyInterface{
 void method3();
}

// class implements all methods of MyInterface and B
public class MyClass implements B {
 
 public Integer method1() {
  System.out.println("in method 1" + i);  
  return null;
 }

 public void method2(String Id) {
  System.out.println("in method 2");  
 }

 public void method3() {
  System.out.println("in method 3");  
 }
 public static void main(String[] args) {
  
 }
}

It can be seen that the class Myclass has to implement all the methods in the inheritance chain of the interface.

Partial implementation of interface by a class

If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.

public interface MyInterface {
 void method1();
 String method2(String Id);
}
implemnting java interface methods

Compiler error that class must implement methods declared in MyInterface interface.

But we can declare the class as abstract in that case

public abstract class AbstractClassDemo implements MyInterface {
 public static void main(String[] args) {
  System.out.println();
 }
}

Nested Interfaces in Java

An interface or a class can have another interface. Such an interface is known as nested interface or a member interface in Java.
A nested interface can be declared as public, private or protected. When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.

Java nested interface Example

// Class with nested interface
class A{
 public interface TestInterface{
  void displayValue(String value);
 }
}

// class implementing the nested interface
class B implements A.TestInterface{
 public void displayValue(String value) {
  System.out.println("Value is " + value);
 }
}

public class MyClass{ 
 public static void main(String[] args) {
  // reference of class B assigned to nested interface
  A.TestInterface obRef = new B();
  obRef.displayValue("hello");
 }
}

Output

Value is hello

Interface and run time polymorphism

As we already know that there can't be an object of an interface, but interface can be used to create object references. As run time polymorphism in Java is implemented through the use of super class reference thus interface can be used to provide super class reference which holds references of sub-classes at run time and provide the appropriate functionality.

Run time polymorphism using interface Java Example

Let's assume that in an application there is a need to handle payment done through several modes like; cash, cheque, credit card etc. and based on the mode of the payment the functionality may be different.
This can be achieved through an interface where the interface defines a method payment and then several classes implement that interface and provide the functionality for the payment method according to the business needs. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.

public interface PaymentInt {
 public void payment(double amount);
}
// Cash Payment implementation of Payment interface
class CashPayment implements PaymentInt{
 // method implementation according to cash payment functionality
 public void payment(double amount) {
  System.out.println("Cash Payment of amount " + amount);
 }
}

//Cheque Payment implementation of Payment interface
class ChequePayment implements PaymentInt{
 // method implementation according to cheque payment functionality
 public void payment(double amount) {
  System.out.println("Cheque Payment of amount " + amount);  
 }
}

//CreditCard Payment implementation of Payment interface
class CreditCardPayment implements PaymentInt{
 // method implementation according to credit card payment functionality
 public void payment(double amount) {
  System.out.println("CreditCard Payment of amount " + amount);
 }
}

public class PaymentDemo {
 public static void main(String[] args) {
  // Payment interface reference holding the CashPayment obj
  PaymentInt paymentInt = new CashPayment();
  paymentInt.payment(134.67);
  // Payment interface reference holding the CreditCardPayment obj
  paymentInt = new CreditCardPayment();
  paymentInt.payment(2347.89);
  // Payment interface reference holding the ChequePayment obj
  paymentInt = new ChequePayment();
  paymentInt.payment(1567.45);
 }
}

Output

Cash Payment of amount 134.67
CreditCard Payment of amount 2347.89
Cheque Payment of amount 1567.45

It can be seen how at run time reference is changed and the appropriate payment method is called.

Points to note-

  • Interfaces help in achieving full abstraction in Java.
  • For top level interfaces only default and public access modifiers are permitted.
  • All the variables in interface are implicitly public, static and final.
  • All the methods in an interface are implicitly public and abstract.
  • The methods of an interface that are implemented by a class must be declared public.
  • If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.
  • A class can extend only one class, but implement many interfaces.
  • An interface, unlike class, can extend more than one interface.
  • An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.
  • Any number of classes can implement an interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.
  • With Java 8, it is possible to add a default implementation to a method in an interface.

That's all for this topic Interface in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. Interface Default Methods in Java 8
  4. Interface Static Methods in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Polymorphism in Java
  2. final Keyword in Java With Examples
  3. Java Abstract Class and Abstract Method
  4. covariant return type in Java
  5. Varargs (Variable-length Arguments) in Java
  6. Difference between HashMap and ConcurrentHashMap in Java
  7. How to Loop Through a Map in Java
  8. Java Lambda Expression And Variable Scope