Friday, July 1, 2022

How to Join Lists in Java

Sometimes we do have a need to join the lists constructed through different queries or received through different sources. This post shows different ways to join lists in Java which are as given below.

  1. Joining two lists in Java without using any API
  2. Joining lists in Java using addAll() method
  3. Joining lists using Apache Commons Collections

Joining two lists in Java without using any API

First thing that comes to mind in this scenario is loop the second list, retrieve the elements from the second list and add them to the first list thus creating a merged list. Some thing like this-

List<String> cityList = new ArrayList<String>();
cityList.add("Delhi");
cityList.add("Mumbai");
cityList.add("Kolkata");
List<String> anotherCityList = new ArrayList<String>();
anotherCityList.add("Hyderabad");
anotherCityList.add("Bangalore");
anotherCityList.add("Mumbai");    
for(int i = 0; i < anotherCityList.size() ; i++){
  cityList.add(anotherCityList.get(i));
}
for(String cityName : cityList){
  System.out.println("City Name " + cityName);
}

But why even write a loop and add elements one by one when there are better options to join lists in Java.

  • Using addAll() method provided by List interface.
  • Using ListUtils.union() method provided by Apache Commons Collections.

Joining lists in Java using addAll() method

You can use addAll() method to merge multiple lists. You can pass the list as an argument to the method to join it at the end of another list.

addAll​(Collection<? extends E> c)- addAll method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

public class JoinListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    List<String> anotherCityList = new ArrayList<String>();
    anotherCityList.add("Hyderabad");
    anotherCityList.add("Bangalore");
    anotherCityList.add("Mumbai");
    
    // Using addAll method, here adding with in the first list
    // we can create a new list and use addAll method to 
    // add both lists to the new List
    cityList.addAll(anotherCityList);
    System.out.println("--Merged List--");
    for(String cityName : cityList){
      System.out.println("City Name " + cityName);
    }
  }
}

Output

--Merged List--
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

Here addAll method is used to append second list to the first list, if there is a requirement that original lists should not be altered then you can create a new list and use addAll method to add both the lists to a new list.

Joining lists using Apache Commons Collections

Another way to join lists in Java is using ListUtils class in Apache Commons Collections. Only thing you need is to add commons-collections jar to your project. ListUtils class has a static method union to merge two lists.

According to the description of this method -

Returns a new list containing the second list appended to the first list. The List.addAll(Collection) operation is used to append the two given lists into a new list.

General form of union method

public static java.util.List union(java.util.List list1, java.util.List list2)

Though the name "union" may suggest otherwise please note that it will retain the duplicate elements in both the lists.

Let's see example code using this option to merge two (or more) lists in Java-

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.ListUtils;

public class JoinListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<String>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Kolkata");
    List<String> anotherCityList = new ArrayList<String>();
    anotherCityList.add("Hyderabad");
    anotherCityList.add("Bangalore");
    anotherCityList.add("Mumbai");
    
    // Using ListUtils.union
    List<String> newCityList = ListUtils.union(cityList, anotherCityList);
    System.out.println("--Merged List--");
    for(String cityName : newCityList){
      System.out.println("City Name " + cityName);
    }
  }
}

Output

--Merged List--
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

You can see that duplicates are retained when the union method is used. Name of the method union is a bit misleading as generally it suggests that duplicates will be counted once.

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


Related Topics

  1. How ArrayList Works Internally in Java
  2. How LinkedList Class Works Internally in Java
  3. How and Why to Synchronize ArrayList in Java
  4. How to Remove Duplicate Elements From an ArrayList in Java
  5. How to Sort ArrayList in Java

You may also like-

  1. How HashMap Works Internally in Java
  2. How HashSet Works Internally in Java
  3. Covariant Return Type in Java
  4. Association, Aggregation And Composition in Java
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Deadlock in Java Multi-Threading
  7. Synchronization in Java - Synchronized Method And Block
  8. Interface Default Methods in Java

Thursday, June 30, 2022

Abstraction in Python

Abstraction is one of the four fundamental OOPS concepts. The other three being-

What is Abstraction

Abstraction means hiding the complexity and only showing the essential features of the object. So in a way, Abstraction means hiding the real implementation and we, as a user, knowing only how to use it.

Real world example would be a vehicle which we drive with out caring or knowing what all is going underneath.

A TV set where we enjoy programs with out knowing the inner details of how TV works.

Abstraction in Python

Abstraction in Python is achieved by using abstract classes and interfaces.

An abstract class is a class that generally provides incomplete functionality and contains one or more abstract methods. Abstract methods are the methods that generally don’t have any implementation, it is left to the sub classes to provide implementation for the abstract methods.

Refer this post Abstract Class in Python to know more about abstract class in Python.

An interface should just provide the method names without method bodies. Subclasses should provide implementation for all the methods defined in an interface. Note that in Python there is no support for creating interfaces explicitly, you will have to use abstract class. In Python you can create an interface using abstract class. If you create an abstract class which contains only abstract methods that acts as an interface in Python.

Python abstraction example using abstract class

In the example there is an abstract class Payment that has an abstract method payment(). There are two child classes CreditCardPayment and MobileWalletPayment derived from Payment that implement the abstract method payment() as per their functionality.

As a user we are abstracted from that implementation when an object of CreditCardPayment is created and payment() method is invoked using that object, payment method of CreditCardPayment class is invoked. When an object of MobileWalletPayment is created and payment() method is invoked using that object, payment method of MobileWalletPayment class is invoked.

from abc import ABC, abstractmethod
class Payment(ABC):
  def print_slip(self, amount):
    print('Purchase of amount- ', amount)
  @abstractmethod
  def payment(self, amount):
    pass

class CreditCardPayment(Payment):
  def payment(self, amount):
    print('Credit card payment of- ', amount)

class MobileWalletPayment(Payment):
  def payment(self, amount):
    print('Mobile wallet payment of- ', amount)

obj = CreditCardPayment()
obj.payment(100)
obj.print_slip(100)
print(isinstance(obj, Payment))
obj = MobileWalletPayment()
obj.payment(200)
obj.print_slip(200)
print(isinstance(obj, Payment))

Output

Credit card payment of-  100
Purchase of amount-  100
True
Mobile wallet payment of-  200
Purchase of amount-  200
True

Recommendations for learning (Udemy Courses)

  1. Complete Python Bootcamp Course
  2. The Complete Python Course-Learn Python by Doing
  3. Python and Django Full Stack Web Developer Bootcamp
  4. Python for Data Science and Machine Learning
  5. Java Programming Masterclass Course

That's all for this topic Abstraction 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. Method Overriding in Python
  2. Multiple Inheritance in Python
  3. Local, Nonlocal And Global Variables in Python
  4. pass Statement in Python
  5. Check if String Present in Another String in Python

You may also like-

  1. Name Mangling in Python
  2. Magic Methods in Python With Examples
  3. User-defined Exceptions in Python
  4. Convert String to int in Python
  5. Difference Between Encapsulation And Abstraction in Java
  6. Object Creation Using new Operator in Java
  7. Spring MVC Form Example With Bean Validation
  8. Uber Mode in Hadoop

Wednesday, June 29, 2022

Python Conditional Statement - if, elif, else Statements

Conditional statement is used to execute a set of statements based on whether the condition is true or not. For conditional execution of statements if statement is used in Python. You can also have conditional branching using if-else and if-elif-else statements in Python.

Python if-elif-else statement syntax

General syntax for if-elif-else statement in Python is as follows-

if boolean_expression1:
 suite1
elif boolean_expression2:
 suite2
...
elif boolean_expressionN:
 suiteN
else:
 else-suite

Note that there can be zero or more elif statements, even else clause is optional. So we’ll start with if statement examples and move towards full conditional branching using if-elif-else statement in Python.


if statement in Python

if statement is used to execute the body of code when the condition evaluates to true. If it is false then the indented statements (if suite) is not executed.

Python if statement syntax

if condition:
 if-suite

Here condition is a boolean expression that evaluates to either true or false. If it evaluates to true if-suite is executed, if expression evaluates to false then the suite if not executed.

Python if statement example

def myfunction():
    x = 10
    y = 12
    if x < y:
        print('x is less than y')
    print('After executing if statement')

myfunction()

Output

x is less than y
After executing if statement

Indentation for grouping statements in Python

To understand conditional statements and loops in Python better you should also have an understanding of how Python used indentation for grouping statements.

Indentation refers to the white spaces at the beginning of the statement. In Python statements that are indented to the same level are part of the same group known as suite.

By default Python uses 4 spaces for indentation which is configurable.

Indentation in the context of if statement can be explained as given below-

Python if else statement

if-else statement in Python

Moving on from a simple if statement towards conditional branching there is if-else statement in Python. In if-else statement if-suite is executed if the condition evaluates to true otherwise else-suite is executed.

Python if-else statement syntax

if condition:
 if-suite
else
 else-suite

Python if-else statement example

def myfunction():
    x = 15
    y = 12
    if x < y:
        diff = y - x
        print('In if difference is-', diff)
    else:
        diff = x - y
        print('In else difference is-', diff)

    print('After executing if-else statement')

myfunction()

Output

In else difference is- 3
After executing if-else statement

Condition (x < y) evaluates to false therefore else statement is executed.

if-elif-else statement in Python

If you have conditional branching based on multiple conditions then you can use if-elif-else statement in Python.

Python if-elif-else statement syntax

if condition1:
 if-suite-1
elif condition2:
 elif-suite-2
elif condition3:
 elif-suite-3
.....
.....
elif conditionN:
 elif-suite-N
else:
 else-suite

Initially condition1 is evaluated if it is true then if-suite is executed, if condition1 is false then condition2 is evaluated if that is true then elif-suite-2 is executed. If condition 2 is false then condition 3 is evaluated and so on. If none of the condition is true then else-suite is executed.

Python if-elif-else statement example

def myfunction():
    invoice_amount = 2000
    tarrif = 0
    if invoice_amount > 2500 and zone == "Americas":
        tarrif = 100
    elif invoice_amount > 2500 and zone == "EU":
        tarrif = 150
    elif invoice_amount > 2500 and zone == "APAC":
        tarrif = 200
    else:
        tarrif = 250
    print('Tarrif is', tarrif)

myfunction()

Output

Tarrif is 250

Nested if statement in Python

You can have nested if-elif-else statement with in if statement upto any depth, only thing is that each nested if statement has to be indented properly.

Nested if statement Python example

def myfunction():
    x = 65
    if x >= 50:
        # nested if statement
        if x > 75 and x <= 99:
            print('x is greater than 75 but less than 100')
        elif x >= 50 and x <= 75:
             print('x is greater than or equal to 50 but less than or equal to 75')
        else:
            print('x is greater than 100')
    else:
        print('x is less than 50')

myfunction()

Output

x is greater than or equal to 50 but less than or equal to 75

That's all for this topic Python Conditional Statement - if, elif, else Statements. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python while Loop With Examples
  2. Ternary Operator in Python
  3. Abstraction in Python
  4. Magic Methods in Python With Examples
  5. Python Functions : Returning Multiple Values

You may also like-

  1. Abstract Class in Python
  2. Python String join() Method
  3. Python Program to Check Armstrong Number
  4. Automatic Numeric Type Promotion in Java
  5. Java join() Method - Joining Strings
  6. equals() And hashCode() Methods in Java
  7. Spring depends-on Attribute and @DependsOn With Examples
  8. Angular First App - Hello world Example

Tuesday, June 28, 2022

Remove Duplicate Elements From an Array in Java

Write a Java program to remove duplicate elements from an array is a frequently asked interview question and you may be asked to do it without using any of the collection data structure like List or Set or you may be asked to do it using Collection API classes first and then without using any of those classes.

In this post we’ll see Java programs for removal of duplicate elements in an array using Collection API classes, without Collection API and using Java Stream API.


Using Collection API

One way to remove duplicate elements from an array in Java is to copy your array elements to a HashSet. As you know HashSet only stores unique elements so any repetition of an element will be discarded. Using this property of HashSet once you copy all the array elements to a HashSet you’ll have a Set with only unique elements. Now you can again copy the elements from your Set to create an array which will be your array with duplicate elements removed.

Remove Duplicate Elements From an Array using HashSet

 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

  public static void main(String[] args) {
    int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
    int[] outArr = removeDuplicatesUsingSet(intArr);
    System.out.println("Original array");
    for(int i : intArr){
      System.out.print(i+" ");
    }
    System.out.println("");
    System.out.println("after removal");
    for(int i : outArr){
      System.out.print(i+" ");
    }
  }
    
  /**
  * @param input
  * @return
  */
  public static int[] removeDuplicatesUsingSet(int[] input){
    // Adding array elements to a list
    List<Integer> tempList = new ArrayList<Integer>();
    for(int i : input){
      tempList.add(i);
    }
    // creating a set using list     
    Set<Integer> set = new HashSet<Integer>(tempList);
    Integer[] output = new Integer[set.size()];
    int[] arrOut = new int[output.length];
    set.toArray(output);
    int j =0;
    for(Integer i : output){
      arrOut[j++] = i;
    }
    return arrOut;
  }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 3 5 6 7 8 12 

Few things to note here are-

  1. If you are using Set then ordering with in the array doesn’t matter i.e. Array doesn’t have to be sorted.
  2. Ordering of the original array will not be retained once elements are stored in the Set.
  3. In the above code I have used int[] array (array of primitives) that’s why there are some extra steps like creating Array of Integer[] (Integer objects) as toArray() method of the Set works only with objects. If you have an array of objects then you don’t need these extra steps.

Remove Duplicate Elements From an Array using LinkedHashSet

In the above Java code to delete element from an array using HashSet, ordering of the array elements is not retained, if you want ordering to be retained then use LinkedHashSet instead.

 
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

  public static void main(String[] args) {
    int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
    int[] outArr = removeDuplicatesUsingSet(intArr);
    System.out.println("Original array");
    for(int i : intArr){
      System.out.print(i+" ");
    }
    System.out.println("");
    System.out.println("after removal");
    for(int i : outArr){
      System.out.print(i+" ");
    }
  }
    
  /** 
   * @param input
   * @return
   */
   public static int[] removeDuplicatesUsingSet(int[] input){
    // Adding array elements to a list
    List<Integer> tempList = new ArrayList<Integer>();
    for(int i : input){
      tempList.add(i);
    }
    // creating a set using list     
    Set<Integer> set = new LinkedHashSet<Integer>(tempList);
    Integer[] output = new Integer[set.size()];
    int[] arrOut = new int[output.length];
    set.toArray(output);
    int j =0;
    for(Integer i : output){
      arrOut[j++] = i;
    }
    return arrOut;
  }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 5 6 12 7 3 8 

Now you can see ordering of the array elements is retained. For duplicate elements first occurrence of the element is retained.

Java Example without using Collection

If you have to remove duplicate elements of the array without using any of the Collection API classes then you can use the following code.

In the program input array is sorted first so that all the duplicate elements are adjacent to each other. By doing that you need only a single loop for comparison.
For removing duplicate elements you need to shift all the elements after the duplicate to the left. Another thing to note here is that array size is fixed once defined, when duplicate element is removed and you shift element after the duplicate to the left that creates space on the right side of the array. To remove that space you need to truncate the array by using copyOf() method of the Arrays utility class.

public class DuplicateRemoval1 {
  /** 
   * @param input
   * @return
  */
  public static int[] removeDuplicates(int[] intArr){
    int i = 1;
    int j = 0;
    Arrays.sort(intArr);
    System.out.println("Sorted array");
    for(int x : intArr){
      System.out.print(x+" ");
    }
    while(i < intArr.length){
      if(intArr[i] == intArr[j]){
        i++;
      }else{
        intArr[++j] = intArr[i++];
      }   
    }
    // This is required to truncate the size of the array
    // otherwise array will retain its original size
    int[] output = Arrays.copyOf(intArr, j+1);
    return output;
  }

  public static void main(String[] args) {
    int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
    int[] outArr = removeDuplicates(intArr);
    System.out.println("");
    System.out.println("after removal");
    for(int i : outArr){
      System.out.print(i+" ");
    }
  }
}

Output

Sorted array
1 1 2 2 3 5 6 7 8 12 12 12 
after removal
1 2 3 5 6 7 8 12 

Time and space complexity

As per the description of the Arrays.sort() method its time complexity is O(n*logn). Then array is traversed in the while loop which takes O(n) time thus the time complexity of the above code is O(n*logn+n).

Using Java Stream to remove duplicates from array

Java Stream API (From Java 8) also provides an option to remove duplicate elements from an array. You can use distinct() method in Java Stream to remove duplicate elements.

int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
int tempArr[] = Arrays.stream(intArr).distinct().toArray();
       
System.out.println("");
System.out.println("after removal");
for(int i : tempArr){
 System.out.print(i+" ");
}

Output

after removal
1 2 5 6 12 7 3 8

That's all for this topic Remove Duplicate Elements From an Array in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Remove Duplicate Elements From an ArrayList in Java
  2. Matrix Multiplication Java Program
  3. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  4. How to Find Common Elements Between Two Arrays Java Program
  5. Array in Java

You may also like-

  1. Split a String Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. How to Read File From The Last Line in Java
  4. Unzip File in Java
  5. Difference Between Comparable and Comparator in Java
  6. How HashMap Works Internally in Java
  7. Map Operation in Java Stream API
  8. Java Concurrency Interview Questions And Answers

Monday, June 27, 2022

Java Exception Handling And Method Overriding

OOPS concepts like inheritance are an integral part of Java as it is an obejct oriented language. When a class extends a super class it can also override methods of the super class.

But what about the exceptions thrown by a super class method? Should the overridden method in the child class also need to throw the same exceptions or it can change it. To address these scenarios there are some rules laid out. In this post Exception Handling and Method Overriding in Java we'll talk about those restrictions.

Broadly there are two rules for exception handling with method overriding in Java-

  • If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception with the throws clause.
  • If superclass method has declared an exception using throws clause then subclass overridden method can do one of the three things.
    1. sub-class can declare the same exception as declared in the super-class method.
    2. subclass can declare the subtype exception of the exception declared in the superclass method. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    3. subclass method can choose not to declare any exception at all.

Examples of Exception handling and method overriding in Java

Let's see examples of the scenarios listed above to make it clear.

If superclass method has not declared any exception

If superclass method has not declared any exception using throws clause then subclass overridden method can't declare any checked exception though it can declare unchecked exception.

Java Exception handing and method overriding

It can be noted here that parent class' displayMsg() method deosn't have any throws clause whereas overridden method in the subclass declares IOException in its throws clause which is a checked exception. That's why the compile time error.

If we change the throws clause in subclass method to any unchecked exception then it won't result in compiler error.

public void displayMsg() throws ArrayIndexOutOfBoundsException{
}

If superclass method has declared an exception

  1. If superclass method has declared an exception then sub class can declare the same exception as declared in the superclass method.
    class Parent{
      public void displayMsg() throws IOException{
        System.out.println("In Parent displayMsg()");
      }
    }
    public class ExceptionOverrideDemo extends Parent{
      public void displayMsg() throws IOException{  
        System.out.println("In ExceptionOverrideDemo displayMsg()"); 
      }  
    }  
    
  2. subclass can declare the subtype exception of the exception declared in the superclass method.
    class Parent{
     public void displayMsg() throws IOException{
      System.out.println("In Parent displayMsg()");
     }
    }
    public class ExceptionOverrideDemo extends Parent{
     public void displayMsg() throws FileNotFoundException{  
      System.out.println("In ExceptionOverrideDemo displayMsg()"); 
     }  
    }
    

    Here in super class displayMsg() method throws IOException where as in subclass overridden displayMsg() method throws FileNotFoundException. Since FileNotFoundException is the subtype (Child class) of IOException so no problem here.

  3. But subclass method can not declare any exception that is up in the hierarchy than the exception declared in the super class method.
    Exception & method overriding in Java
    Here parent class method is throwing IOException whereas in the subclass overridden method is throwing Exception, it will result in compiler error as IOException is the child class of Exception class, thus Exception is up in the hierarchy.
  4. Subclass overridden method declares no exception. Subclass overridden method can choose to not throw any exception at all even if super class method throws an exception.
    class Parent{
      public void displayMsg() throws IOException{
        System.out.println("In Parent displayMsg()");
      }
    }
    public class ExceptionOverrideDemo extends Parent{
      public void displayMsg(){  
        System.out.println("In ExceptionOverrideDemo displayMsg()"); 
      }  
    }
    

That's all for this topic Java Exception Handling And Method Overriding. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Method Overriding in Java
  2. throw Statement in Java Exception Handling
  3. Multi-Catch Statement in Java Exception Handling
  4. Exception Propagation in Java Exception Handling
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Difference Between Abstract Class And Interface in Java
  2. strictfp in Java
  3. Marker Interface in Java
  4. ConcurrentHashMap in Java With Examples
  5. How HashMap Works Internally in Java
  6. Fail-Fast Vs Fail-Safe Iterator in Java
  7. Inter-thread Communication Using wait(), notify() And notifyAll() in Java
  8. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class

Sunday, June 26, 2022

Python while Loop With Examples

In Python programming language there are two loops for..in loop and while loop. In this tutorial you’ll learn about while loop in Python which is used to repeatedly execute the loop body while the given condition evaluates to true.


Syntax of Python while loop

Full syntax of while loop in Python is as given below.

while condition:
 while_suite
else:
 else_suite

Here condition is a boolean expression that evaluates to either true or false. Initially condition is checked and if it evaluates to true the statements making up the while_suite are executed. Control then goes back to the start of the loop and condition is checked again if it evaluates to true the statements making up the while_suite are executed again. Same process is followed repeatedly while the condition evaluates to true. When the condition evaluates to false control comes out of the while loop.

The else statement in the while loop is optional. The else_suite is executed if the while loop terminates normally and if the optional else statement is present.

while loop flow

Python while Loop

Python while loop examples

1- To display numbers 1..10 using while loop in Python.

i = 1
while i <= 10:
    print(i)
    i+=1

print('Out of while loop')

Output

1
2
3
4
5
6
7
8
9
10
Out of while loop

In the example i <= 10 is the condition for the while loop. While this condition is true loop body which are the following two indented statements are executed.

    print(i)
    i+=1

When value of i becomes greater than 10 control comes out of while loop.

2- Displaying table of 5 using while loop in Python.

i = 1
while i <= 10:
    print(5, 'X', i, '=', (i*5))
    i+=1

Output

5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

Python while loop with else statement

In Python, while loop has an optional else statement too. If the while loop runs till completion and terminates the else-suite is executed.

If while loop doesn’t run completely because of any of the following reason, else statement is not executed.

  • while loop is terminated abruptly due to a break statement
  • while loop is terminated abruptly due to a return statement
  • if an exception is raised

In the following example else_suite is executed as the while loop completes normally.

i = 1
while i <= 10:
    print(i)
    i+=1
else:
    print('in else block')

Output

1
2
3
4
5
6
7
8
9
10
in else block

Now, if we break the while loop abruptly, else-suite won’t be executed.

i = 1
while i <= 10:
    print(i)
    i+=1
    if i > 5:
        break
else:
    print('in else block')

Output

1
2
3
4
5

Nested while loop in Python

while loop can be nested which means you can have one while loop inside another (or even for loop inside while loop). In the nested loops for each iteration of the outer while loop, inner while loop is iterated while the condition of inner while loop evaluates to true.

Python Nested while loop example

Suppose you want to print inverted right triangle using asterisk (*) symbol, following example shows one way to do it using nested while loops in Python.

rows = 6
while rows > 0:
    j = 1
    # inner while
    while j <= rows:
        # end='' to ensure print remains on the same line
        print('* ', end='')
        j += 1
    # for outer while
    rows = rows - 1
    print()

Output

* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

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

>>>Return to Python Tutorial Page


Related Topics

  1. Python Conditional Statement - if, elif, else Statements
  2. Python continue Statement With Examples
  3. Python First Program - Hello World
  4. Ternary Operator in Python
  5. Polymorphism in Python

You may also like-

  1. Local, Nonlocal And Global Variables in Python
  2. List Comprehension in Python With Examples
  3. Python Program to Check Whether String is Palindrome or Not
  4. Constructor Overloading in Java
  5. Private Methods in Java Interface
  6. Matrix Multiplication Java Program
  7. How to Sort an ArrayList in Descending Order in Java
  8. Sending Email Using Spring Framework Example

Saturday, June 25, 2022

Matrix Subtraction Java Program

When you subtract two matrices subtraction is done index wise. You subtract the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

For example if you are subtracting two matrices of order 3X3-

matrix subtraction in Java

Which results in-

Also remember these points when subtracting one matrix with another-

  1. Both of the matrix have to be of same size.
  2. Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix minus (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

Matrix subtraction Java program

 
import java.util.Scanner;

public class MatrixSubtraction {

  public static void main(String[] args) {
    int rowM, colM;
    Scanner in = new Scanner(System.in);
    
    System.out.print("Enter Number of Rows and Columns of Matrix : ");
    rowM = in.nextInt();
    colM = in.nextInt();
        
    int M1[][] = new int[rowM][colM];
    int M2[][] = new int[rowM][colM];
    int resMatrix[][] = new int[rowM][colM];
    
    System.out.print("Enter elements of First Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M1[i][j] = in.nextInt();
      }
    }
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M1[i][j]+"\t");
      }
      System.out.println();
    }
        
    System.out.print("Enter elements of Second Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M2[i][j] = in.nextInt();
      }
    }
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M2[i][j] + "\t");
      }
      System.out.println();
    }
        
    // Subtraction logic 
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        resMatrix[i][j] = M1[i][j] - M2[i][j];
      }
    }
        
    // Printing the result matrix 
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
}

Output

 
Enter Number of Rows and Columns of Matrix : 3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1
 
Result Matrix : 
 -1  -4  3 
  2   1  0 
 -5  -5  1 

That's all for this topic Matrix Subtraction Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Matrix Multiplication Java Program
  2. Matrix Addition Java Program
  3. Remove Duplicate Elements From an Array in Java
  4. Factorial Program in Java
  5. Fibonacci Series Program in Java

You may also like-

  1. How to Display Pyramid Patterns in Java - Part2
  2. Zipping Files And Folders in Java
  3. How to Read File From The Last Line in Java
  4. How to Run a Shell Script From Java Program
  5. Object class in Java
  6. Type Wrapper Classes in Java
  7. Lock Striping in Java Concurrency
  8. How ArrayList Works Internally in Java