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

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

Friday, June 24, 2022

break Statement in Java With Examples

When you are working with loops where loop body is repeatedly executed, you may have a scenario where you want to skip the execution of statements inside the loop or you may want to terminate the loop altogether. To handle these two scenarios there are two control statements in Java- continue statement and break statement. In this tutorial you’ll learn about Java break statement along with usage examples.

Where do you use break statement in Java

break statement in Java can be used in following scenarios-

  1. For terminating a loop– If there is a break statement with in a for loop, while loop or do-while loop the loop is terminated and the control moves to the statement immediately following the loop.
  2. For terminating switch statement– In Java switch statement if a case is followed by a break statement then the switch statement is terminated. For usage of break statement with switch statement in Java refer this post- Switch-Case Statement in Java
  3. Using labeled break statement– You can use labeled break statement to exit out of a labelled block.

break statement Java examples

1- Using break statement to break out of a for loop. In the example a list of cities is iterated and searched for a specific city. If the city is found loop is terminated using a break statement.

public class BreakJava {
  public static void main(String[] args) {
    List<String> cities = Arrays.asList("Beijing", "London", "Santiago", "St. Petersburg", "Helsinki");
    for(String city : cities) {
      if(city.equals("Santiago")) {
        System.out.println("Found city - " + city);
        // terminate loop
        break;
      }                
    }
    System.out.println("Out of for loop");
  }
}

Output

Found city - Santiago
Out of for loop

2- Using break statement to terminate an infinite while loop.

public class BreakJava {
  public static void main(String[] args) {
    int i = 1;
    while(true){
      // terminate loop when i is greater than 5
      //display i's value otherwise
      if(i > 5)
        break;
      System.out.println("i- " + i);
      i++;
    }
  }
}

Output

i- 1
i- 2
i- 3
i- 4
i- 5

3- When break statement is used with nested loops, break statement terminates the innermost loop in whose scope break is used.

public class BreakJava {
  public static void main(String[] args) {
    for(int i = 1; i <= 3; i++){
      System.out.print(i + "- ");
      for(int j = 0; j < 10; j++){
        System.out.print("*");
        // terminate inner loop
        if(j == 6)
          break;
      }
      System.out.println();                   
    }        
    System.out.println("Out of loop");
  }
}

Output

1- *******
2- *******
3- *******
Out of loop

Here break statement is used in the scope of outer loop so outer for loop is terminated.

public class BreakJava {
  public static void main(String[] args) {
    for(int i = 1; i <= 6; i++){
      if(i == 4)
        break;
      System.out.print(i + "- ");
      for(int j = 0; j < 10; j++){
        System.out.print("*");
      }
      System.out.println();                   
    }        
    System.out.println("Out of loop");
  }
}

Output

1- **********
2- **********
3- **********
Out of loop

4- With unlabeled break statement you can come out of the innermost loop. If you want to come out of a deeply nested loop you can use labeled break statement which helps in coming out of more than one blocks of statements.

For example in the following code two for loops are there and labeled break statement helps in coming out of both the loops.

public class BreakJava {

  public static void main(String[] args) {
    int[][] array = { 
      {1, 2, 3 },
      {4, 5, 6 },
      {7, 8, 9 }
    };
    int searchedNum = 5;
    boolean flag = false;
    int i = 0, j = 0;
    // label
    outer:
    for (i = 0; i < array.length; i++) {
      for (j = 0; j < array[i].length; j++) {
        if (array[i][j] == searchedNum) {
          flag = true;
          // lebeled break
          break outer;
        }
      }
    }
    if(flag) {
      System.out.println("Found element " + searchedNum + " at index " + i + " and " + j );
    }else {
      System.out.println("Element " + searchedNum + " not found in the array" );
    }
  }
}

Output

Found element 5 at index 1 and 1

That's all for this topic break Statement 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. if else Statement in Java With Examples
  2. Arithmetic And Unary Operators in Java
  3. this Keyword in Java With Examples
  4. Constructor in Java
  5. Java Abstract Class and Abstract Method

You may also like-

  1. BigInteger in Java
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. Map.Entry Interface in Java
  4. Deadlock in Java Multi-Threading
  5. Selection Sort Program in Java
  6. How to Display Pyramid Patterns in Java - Part1
  7. Python First Program - Hello World
  8. How MapReduce Works in Hadoop

Thursday, June 23, 2022

How to Convert Date to String in Java

In most of the Java application it’s a very common requirement to print date in a required format. For that you do need to convert date to a String that is in the required format. In this post we’ll see options to convert java.util.Date to String in Java using both SimpleDateFormat class and using DateTimeFormatter class Java 8 onward.


Using SimpleDateFormat for conversion

Before Java 8, a tried and tested way to convert date to string in Java is to use SimpleDateFormat which also gives you an option to provide customized format.

SimpleDateFormat resides in java.text package and extends DateFormat class which is an abstract class. DateFormat class also provides predefined styles to format dates and times.

Here note that SimpleDateFormat is not thread safe so not safe to use in multi-threaded application with out proper synchronization. An alternative way is to use ThreadLocal class, see an example of how ThreadLocal can be used by storing separate instance of SimpleDateFormat for each thread here.

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time.

Let’s see an example to convert date to String using the given format.

In this example there is a method getFormattedDate() where pattern is passed as an argument. Date is converted to String using the passed pattern.

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {

 public static void main(String[] args) {
  FormatDate fd = new FormatDate();
  
  // For date in format Wed, Jun 8, '16
  fd.getFormattedDate("EEE, MMM d, ''yy");

  // For date in format Wednesday, June 08, 2016
  fd.getFormattedDate("EEEE, MMMM dd, yyyy");

  // For date in format 05/08/2016
  fd.getFormattedDate("MM/dd/yyyy");

  // For date in format 08/05/2016
  fd.getFormattedDate("dd/MM/yyyy");
  
  // Only time like 21:52:14:096 PM
  // in 24 hr format, with mili seconds and AM/PM marker
  fd.getFormattedDate("HH:mm:ss:SSS a");

 }
 
 public void getFormattedDate(String pattern){
  Date today;
  String result;
  SimpleDateFormat formatter;
  // Creating the date format using the given pattern
  formatter = new SimpleDateFormat(pattern);
  // Getting the date instance
  today = new Date();
  // formatting the date
  result = formatter.format(today);
  System.out.println("Pattern: " + pattern + 
    " Formatted Date - " + result);
 }
}

Output

Pattern: EEE, MMM d, ''yy Formatted Date - Sun, Aug 13, '17
Pattern: EEEE, MMMM dd, yyyy Formatted Date - Sunday, August 13, 2017
Pattern: MM/dd/yyyy Formatted Date - 08/13/2017
Pattern: dd/MM/yyyy Formatted Date - 13/08/2017
Pattern: HH:mm:ss:SSS a Formatted Date - 12:50:14:097 PM

Using DateTimeFormatter class in Java 8 for conversion

From Java 8 there is another option to convert date to a string in Java. If you have an object of type LocalDate, LocalTime or LocalDateTime you can format it using the DateTimeFormatter class. All these classes are part of new Date & Time API in Java and reside in java.time package.

All these classes LocalDate, LocalTime or LocalDateTime have format method that takes object of DateFormatter class as argument. Using that object of DateFormatter, format for conversion can be provided.

You can use static methods ofLocalizedDate(FormatStyle dateStyle), ofLocalizedTime(FormatStyle dateStyle) or ofLocalizedDateTime(FormatStyle dateStyle) based on the type of object you are using to provide the pattern for formatting. Here FormatStyle is an Enumeration with the following Enum constants. Note that these methods return a locale specific date-time formatter.
  • public static final FormatStyle FULL- Full text style, with the most detail. For example, the format might be 'Tuesday, April 12, 1952 AD' or '3:30:42pm PST'.
  • public static final FormatStyle LONG- Long text style, with lots of detail. For example, the format might be 'January 12, 1952'.
  • public static final FormatStyle MEDIUM- Medium text style, with some detail. For example, the format might ' be 'Jan 12, 1952'.
  • public static final FormatStyle SHORT- Short text style, typically numeric. For example, the format might be '12.13.52' or '3:30pm'.

DateTimeFormatter Java Example

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  String strDate =  getFormattedDate(curDateTime);
  System.out.println("Formatted date - " + strDate); 
 }
 
 private static String getFormattedDate(LocalDateTime dt){
  DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
  return dt.format(df1);
 }
}

Output for FULL

Date before formatting 2017-08-13T20:08:25.056
Formatted date - Sunday, 13 August, 2017

Output for LONG

Date before formatting 2017-08-13T20:08:54.921
Formatted date - 13 August, 2017

Output for MEDIUM

Date before formatting 2017-08-13T20:09:27.308
Formatted date - 13 Aug, 2017

Output for SHORT

Date before formatting 2017-08-13T20:09:53.465
Formatted date – 13/8/17

Using ofPattern() method

You can also use ofPattern() method of the DateTimeFormatter class to provide the pattern for formatting. Using this method you can provide custom format while converting date to String in Java.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  // Passing custom pattern
  getFormattedDate(curDateTime, "dd/MM/yyyy");
  //String strDate =  getFormattedDate(curDateTime);
  //System.out.println("Formatted date - " + strDate);
  
  getFormattedDate(curDateTime, "YYYY MMM dd");
  
  getFormattedDate(curDateTime, "MMMM dd yyyy hh:mm a");
 }

 private static void getFormattedDate(LocalDateTime dt, String pattern){
  DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
  System.out.println("Formatted date " + " For Pattern " + pattern + " is "+ dt.format(df));
 }
}

Output

Date before formatting 2017-08-13T20:20:07.979
Formatted date  For Pattern dd/MM/yyyy is 13/08/2017
Formatted date  For Pattern YYYY MMM dd is 2017 Aug 13
Formatted date  For Pattern MMMM dd yyyy hh:mm a is August 13 2017 08:20 PM

That's all for this topic How to convert Date to String 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 Convert String to Date in Java
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Format Date in Java Using SimpleDateFormat
  4. How to Display Time in AM-PM Format in Java
  5. How to Find Last Modified Date of a File in Java

You may also like-

  1. How to Run javap Programmatically From Java Program
  2. How to Untar a File in Java
  3. Invoking Getters And Setters Using Reflection in Java
  4. Bounded Type Parameter in Java Generics
  5. Functional Interfaces in Java
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. Difference Between equals() Method And equality Operator == in Java
  8. Interface Default Methods in Java

Python return Statement With Examples

In this tutorial you’ll learn about return statement in Python which is used to exit a function and return a value.

Note that returning a return result from a function is not mandatory, return is not required if a function does not return a value. If no explicit return statement is used in a function, return None is implicitly returned by the function.

A return statement may or may not return a value. If a return statement is followed by a value (or expression) that value or the value after evaluating the expression is returned. If return statement without any value is used then the execution of the function terminates even if there are more statements after the return statement.

Python return statement examples

Let’s try to understand usage of return statement with some examples.

1- Return value from a function using return statement.

def sum(num1, num2):
    print('in sum function')
    return num1+num2

result = sum(16, 5)
print('sum is', result)

Output

in sum function
sum is 21

In the function return statement is followed by an arithmetic expression num1+num2, that expression is evaluated and the value is returned from the function.

2- A function with no return statement. You may have a function that doesn’t return any value in that case you need not write the return statement. If there is no return statement Python implicitly returns None.

def sum(num1, num2):
    print('in sum function')
    print('sum is', num1+num2)

sum(16, 5)

Output

in sum function
sum is 21

3- Using Python return statement with no return value. In the function an array is iterated to find a passed value, as soon as that value is found come out of the function using return.

from array import *
def find_in_array(arr, value):
    for i in arr:
        if i == value:
            print(value, 'found in array')
            #come out of function as value is found
            return
        
a = array('i', [3,4,5,6,7])
find_value = 5
find_in_array(a, find_value)

Output

5 found in array

4- If there are statements after return in a function those are not executed because the execution of the function is terminated when the return statement is encountered.

def sum(num1, num2):
    sum = num1+num2
    return sum
    #not reachable
    print('in sum function after calculation')

result = sum(16, 5)
print('sum is', result)

5- In Python, return statement can return multiple values. Multiple values can be returned as a tuple, list or dictionary. When multiple values are returned as comma separated values from a function, actually a tuple is returned.

def sum(num1, num2):
    sum = num1+num2
    # returning multiple values
    return sum,num1,num2 # can also be written as (sum, num1, num2)


result, num1, num2 = sum(16, 5)
print('sum of %d and %d is %d' % (num1, num2, result))

Output

sum of 16 and 5 is 21

That's all for this topic Python return Statement 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 assert Statement
  2. pass Statement in Python
  3. Polymorphism in Python
  4. Class And Object in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Removing Spaces From String in Python
  2. Global Keyword in Python With Examples
  3. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  4. List Comprehension in Python With Examples
  5. First Java Program - Hello World Java Program
  6. instanceof Operator in Java With Examples
  7. Array Rotation Java Program
  8. Benefits, Disadvantages And Limitations of Autowiring in Spring

Python assert Statement

In this tutorial you’ll learn about assert statement in Python which is used to assert the trueness of a condition.

Assertion is a boolean expressions to check if the condition is true or false. In case it is true, the program does nothing and move to the next line of code. If the condition is false, the program stops and throws an error.

Python assert statement

In Python there is an assert statement to assert if a given condition is true or not. If the condition is false execution stops and AssertionError is raised.

Syntax of assert statement in Python-

assert expression, message

Here message is optional, if no message is passed then the program stops and raises AssertionError if the condition is false.

If message is passed along with the assert statement then the program stops and raises AssertionError + display error message, if the condition is false.

Assert statement example

1- Using assert statement without any message.

def divide(num1, num2):
    assert num2 != 0
    result = num1/num2
    print('Result-', result)

divide(16, 0)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 6, in <module>
    divide(16, 0)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2, in divide
    assert num2 != 0
AssertionError

In the example there is an assert statement with a condition that the second argument should not be zero. Since the assert condition returns false AssertionError is raised.

2- When the condition in assert statement is true.
def divide(num1, num2):
    assert num2 != 0
    result = num1/num2
    print('Result-', result)

divide(16, 2)

Output

Result- 8.0

3- Using assert statement with a message. If an optional message is passed then the message is also displayed if the condition is false.

def divide(num1, num2):
    assert num2 != 0, "Second argument can't be passed as zero"
    result = num1/num2
    print('Result-', result)

divide(16, 0)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 6, in <module>
    divide(16, 0)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 2, in divide
    assert num2 != 0, "Second argument can't be passed as zero"
AssertionError: Second argument can't be passed as zero

Using assert statement in Python

Assert statement is useful for debugging or quick sanity testing. It should not be used for data validation in the code.

By using PYTHONOPTIMIZE environment variable or by using -O or -OO assert statements can be disabled. In that case assert statements won’t be executed and using them for any critical data validation in your code may cause serious issues.

In Python internally any assert statement is equivalent to-

if __debug__:
    if not expression: raise AssertionError

The built-in variable __debug__ is False when optimization is requested (command line option -O) which means no assert statements are executed.

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

>>>Return to Python Tutorial Page


Related Topics

  1. Python continue Statement With Examples
  2. Python break Statement With Examples
  3. Operator Overloading in Python
  4. Global Keyword in Python With Examples
  5. Name Mangling in Python

You may also like-

  1. String Length in Python - len() Function
  2. Magic Methods in Python With Examples
  3. Python Program to Display Fibonacci Series
  4. Nested Try Statements in Java Exception Handling
  5. Race Condition in Java Multi-Threading
  6. Printing Numbers in Sequence Using Threads Java Program
  7. How to Read Properties File in Spring Framework
  8. What is Hadoop Distributed File System (HDFS)

Wednesday, June 22, 2022

Python continue Statement With Examples

In this tutorial you’ll learn about continue statement in Python which is used inside a for loop or while loop to go back to the beginning of the loop. When continue statement is encountered in a loop control transfers to the beginning of the loop, any subsequent statements with in the loop are not executed for that iteration.

Common use of continue statement is to use it along with if condition in the loop. When the condition is true the continue statement is executed resulting in next iteration of the loop.

continue statement Python examples

1- Using continue statement with for loop in Python. In the example a for loop in range 1..10 is executed and it prints only odd numbers.

for i in range(1, 10):
    # Completely divisble by 2 means even number
    # in that case continue with next iteration
    if i%2 == 0:
        continue
    print(i)

print('after loop')

Output

1
3
5
7
9
after loop

2- Using continue statement in Python with while loop. In the example while loop is iterated to print numbers 1..10 except numbers 5 and 6. In that case you can have an if condition to continue to next iteration when i is greater than 4 and less than 7.

i = 0
while i < 10:
    i += 1
    if i > 4 and i < 7:
        continue
    print(i)

Output

1
2
3
4
7
8
9
10

3- Here is another example of using continue statement with infinite while loop. In the example there is an infinite while loop that is used to prompt user for an input. Condition here is that entered number should be greater than 10, if entered number is not greater than 10 then continue the loop else break out of the loop.

while True:
    num = int(input("Enter a number greater than 10: "))
    # condition to continue loop
    if num < 10:
        print("Please enter a number greater than 10...")
        continue
    else:
        break

print("Entered number is", num)

Output

Enter a number greater than 10: 5
Please enter a number greater than 10...
Enter a number greater than 10: 16
Entered number is 16

That's all for this topic Python continue Statement 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 break Statement With Examples
  2. Python return Statement With Examples
  3. pass Statement in Python
  4. Encapsulation in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Strings in Python With Method Examples
  3. List in Python With Examples
  4. What Are JVM, JRE And JDK in Java
  5. Equality And Relational Operators in Java
  6. Lambda Expressions in Java 8
  7. What is Hadoop Distributed File System (HDFS)
  8. Circular Dependency in Spring Framework

Tuesday, June 21, 2022

Constructor in Java

In Java there is a special method provided to initialize objects when they are created. This special method which helps in automatic initialization is called Constructor in Java.

Java Constructor

Constructor in Java has the same name as the class in which it is created and defined just like a method, that is, constructor's syntax is similar to a method.

Constructor in Java is called automatically when the object is created using the new operator, before the new operator completes. Constructors don't have a return type, even void is not allowed. Constructors have an implicit return type which is the class type (current instance) itself.


Java Constructor Example

public class ConstrExample {
 int i;
 String name;
 // Constructor
 public ConstrExample() {
  System.out.println("Creating an object");
  System.out.println("i - " + i + " name - " + name);
 }

 public static void main(String[] args) {
  ConstrExample constrExample = new ConstrExample();
 }
}

Here Constructor is this part

public ConstrExample() {
 System.out.println("Creating an object");
 System.out.println("i - " + i + " name - " + name);
}

And executing this program will give the output as-

Creating an object 
i - 0 name - null

Note here that-

  • Constructor name is same as the class name.
  • In the above code constructor's access modifier is public, but constructor can have private, protected or default access modifier.
  • As already stated constructors in Java don't have a return type. If you give even void as a return type then compiler would not treat it as a constructor but as a regular method. In that case Java compiler will add a default constructor.
  • Constructor in Java can't be final.

Types of Constructors in Java

Java constructors can be classified into three types-

  1. Default constructor
  2. No-arg constructor
  3. Parameterized constructor

Default Constructor in Java

When a constructor is not explicitly defined in a class, then Java inserts a default no-arg constructor for a class. If a constructor is explicitly defined for a class, then the Java compiler will not insert the default no-argument constructor into the class.

Java Default Constructor example

In the constructor example shown above we used a no-arg constructor, if we don't write that no-arg constructor explicitly even then Java will insert a default no-arg constructor.

public class ConstrExample {
 int i;
 String name;
  
 public static void main(String[] args) {
  ConstrExample constrExample = new ConstrExample();  
 }
}

As you can see in the program there is no constructor. If you see the structure of the generated .class file using javap command then you can also see an entry for default constructor added by Java.

javap F:\Anshu\NetJs\NetJSExp\bin\org\netjs\examples\ConstrExample.class

Compiled from "ConstrExample.java"

public class org.netjs.examples.ConstrExample {
  int i;
  java.lang.String name;
  // Constructor
  public org.netjs.examples.ConstrExample();
  public static void main(java.lang.String[]);
}

No-arg Constructor in Java

Constructor with out any parameters is known as no-arg constructor. While default constructor is implicitly inserted and has no body, no-arg constructor is explicitly written in the class and it can have code too.

In your class if you do have any constructor then default constructor is not inserted automatically. In that case if you want to have an option to create object without passing any argument then you have to have a no-arg constructor in your class. See example for this scenario in Parameterized constructor section.

Java No-arg Constructor example

public class ConstrExample {
 int i;
 String name;
 public ConstrExample() {
  System.out.println("Creating an object");
  this.name = "Hello";
  this.i = 10;  
 }
  
 public static void main(String[] args) {
  ConstrExample constrExample = new ConstrExample();
  System.out.println("i = " + constrExample.i);
  System.out.println("name = " + constrExample.name);
 }
}

Output

Creating an object
i = 10
name = Hello

Parameterized Constructor in Java

If we want our object's fields to be initialized with specific values, we can do it by adding parameters to the constructor.
A class can have multiple constructors too as long as constructor signatures are different.

Java Parameterized Constructor Example

public class ConstrExample {
 int i;
 String year;
 // Parameterized Constructor
 ConstrExample(int i, String year) {
  System.out.println("Creating a parameterized object");
  this.i = i;
  this.year = year;
  System.out.println("i - " + i + " year - " + year);
 }
 //no-arg constructor
 ConstrExample() {
  System.out.println("Creating a object");  
  System.out.println("i - " + i + " year - " + year);
 }
  
 public static void main(String[] args) {
  ConstrExample constrExample1 = new ConstrExample(10, "2015");
  ConstrExample constrExample2 = new ConstrExample(); 
 }
}

And executing this program will give the output as-

Creating a parameterized object
i - 10 year - 2015
Creating a object
i - 0 year - null

Note here that-

  • There are 2 constructors here one with parameters another no-arg constructor, this is known as constructor overloading.
  • 2 Objects are created one with parameters which will invoke the parameterized constructor and another without any parameters which will invoke the no-arg contructor.

Constructor Chaining in Java

When you have a hierarchy of classes it is important to know what is the order in which the constructors for the classes are executed. That order is known as constructor chaining in Java.

As example- If class A is superclass and there is Class B which is subclass of A. What is the order in which constructors of Class A and Class B are executed?
Answer is, the order followed is from superclass to subclass.

Subclass can call a constructor in the superclass inside one of the subclass constructors using super(). In that case super() must be the first statement in a subclass constructor. If super() is not used then the default no-arg constructor of each superclass will be executed. Note that the order remains same (from superclass to subclass ) whether or not super() is used.

Java Constructor Chaining example

class A{
 A(){
  System.out.println("In class A's constructor");
 }
}

class B extends A{
 B(){
  System.out.println("In class B's constructor");
 }
}

class C extends B{
 C(){
  System.out.println("In class C's constructor");
 }
}

public class ConstrChaining {

public static void main(String[] args) {
  C c = new C();

 }
}

And executing this program will give the output as-

In class A's constructor
In class B's constructor
In class C's constructor

Points to note-

  • Constructor in Java has the same name as the class in which it is created.
  • Constructor is called automatically when the object is created, in order to initialize an object.
  • Constructors don't have a return type, even void is not allowed.
  • Constructor can have any access modifier public, private, protected or default.
  • When a constructor is not explicitly defined for a class, then Java creates a default no-arg constructor for a class, that is called default constructor in Java.
  • Within the same class there may be multiple constructors where the constructors differ in number and/or types of parameters, that process is known as Constructor overloading.
  • In case of inheritance, constructors are called in order of super class to sub class, that process is known as Constructor chaining.

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

>>>Return to Java Basics Tutorial Page


Related topics

  1. Constructor Chaining in Java
  2. Constructor Overloading in Java
  3. Initializer block in Java
  4. Object Creation Using new Operator in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Method Overloading in Java
  2. this in Java
  3. How to Read Input From Console in Java
  4. Java Pass by Value or Pass by Reference
  5. How to Iterate a HashMap of ArrayLists of String in Java
  6. Difference Between sleep And wait in Java Multi-Threading
  7. Java ReentrantLock With Examples
  8. Functional Interfaces in Java