Saturday, December 31, 2022

Java LinkedTransferQueue With Examples

LinkedTransferQueue is added in Java 7 and it is an implementation of TransferQueue interface.

TransferQueue interface in Java

It will be worthwhile to spend some time knowing the TransferQueue interface here.

TransferQueue interface, also added in Java 7, extends BlockingQueue interface. The extra functionality provided by TransferQueue interface is that it provides blocking method which will wait until other thread receives your element.

That's how it differs from BlockingQueue where you can only put element into queue or retrieve element from queue and block if queue is full (while you are putting elements) or block if queue is empty (while you are retrieving elements). So BlockingQueue won't block until consumer thread removes any particular element (Though SynchronousQueue provides that kind of functionality but more as one-to-one handoff, not as a queue.)

TransferQueue has a blocking method transfer(E e) which will ensure that the element is transferred to the consumer, it will wait if required to do so. More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in BlockingQueue.take() or timed poll), else waits until the element is received by a consumer.

TransferQueue also has put() method, just like BlockingQueue which will just enqueue the element without waiting for consumer to retrieve the element.

It also has non-blocking and time-out tryTransfer() method-

  • tryTransfer(E e)- Transfers the element to a waiting consumer immediately, if possible.
  • tryTransfer(E e, long timeout, TimeUnit unit)- Transfers the element to a consumer if it is possible to do so before the timeout elapses.

TransferQueue also has querying methods like getWaitingConsumerCount() and hasWaitingConsumer()

  • getWaitingConsumerCount()- Returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or timed poll.
  • hasWaitingConsumer()- Returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take() or timed poll.

Java LinkedTransferQueue

LinkedTransferQueue, as already mentioned is an implementation of the TransferQueue. LinkedTransferQueue in Java is an unbounded queue and stores elements as linked nodes.

LinkedTransferQueue orders elements FIFO (first-in-first-out) with respect to any given producer. The head of the queue is that element that has been on the queue the longest time for some producer. The tail of the queue is that element that has been on the queue the shortest time for some producer.

Java LinkedTransferQueue constructors

  • LinkedTransferQueue()- Creates an initially empty LinkedTransferQueue.
  • LinkedTransferQueue(Collection<? extends E> c)- Creates a LinkedTransferQueue initially containing the elements of the given collection, added in traversal order of the collection's iterator.

Producer Consumer Java example using LinkedTransferQueue

Let's create a producer consumer using LinkedTransferQueue. There is a producer thread which will put elements into the queue and a consumer thread which will retrieve elements from the queue. Also a shared class which will be used by both producer and consumer threads.

To show the functionality of transfer() method delay is induced in consumer thread, since elements are stored using transfer() method so the producer will wait unless until consumer thread retrieves the element. Producer won't keep on adding the element to the queue even if consumer thread is sleeping it gets blocked.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

public class LinkedTQDemo {
  public static void main(String[] args) {
    // buffer class used by both threads
    SharedTQ buffer = new SharedTQ();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    // Executing producer
    executor.execute(new TProd(buffer));
    // Executing consumer
    executor.execute(new TCon(buffer));
    executor.shutdown();
  }
}


/**
 * Producer class
 */
class TProd implements Runnable{
  SharedTQ buffer;
  TProd(SharedTQ buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      buffer.put(i);
    }
  }
}

/**
 * Consumer class
 */
class TCon implements Runnable{
  SharedTQ buffer;
  TCon(SharedTQ buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      try {
        // introducing some delay using sleep
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        System.out.println("Error while putting in the queue " + e.getMessage());
      }
      buffer.get();
    }
  }    
}

//Shared class used by threads
class SharedTQ{
  int i;
  // TransferQueue
  TransferQueue<Integer> ltQueue = new LinkedTransferQueue<Integer>();
  
  public void get(){
    try {
      // take method to get from TransferQueue
      System.out.println("Consumer recd - " + ltQueue.take());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  public void put(int i){
    this.i = i;
    try {
      System.out.println("Putting - " + i);
      // putting in TransferQueue
      ltQueue.transfer(i);        
    }
    catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Output

Putting - 0
Consumer recd - 0
Putting - 1
Consumer recd - 1
Putting - 2
Consumer recd - 2
Putting - 3
Consumer recd - 3
Putting - 4
Consumer recd - 4

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


Related Topics

  1. Java ArrayBlockingQueue With Examples
  2. Java SynchronousQueue With Examples
  3. Java BlockingDeque With Examples
  4. Java Semaphore With Examples
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. ConcurrentSkipListMap in Java With Examples
  2. Lambda Expressions in Java 8
  3. Volatile Keyword in Java With Examples
  4. Multi-Catch Statement in Java Exception Handling
  5. super Keyword in Java With Examples
  6. static Method Overloading or Overriding in Java
  7. Add Double Quotes to a String Java Program
  8. Spring Bean Life Cycle

Friday, December 30, 2022

Python Program to Check if Strings Anagram or Not

In this post we'll see a Python program to check if two strings are anagrams or not.

Anagram Strings

Two strings are called anagram if you can rearrange the letters of one string to produce the second string, using all the letters of the first string only once. While doing that, usually, you don't consider spaces and punctuation marks.

Some Examples- "keep" and "peek", "silent" and "listen", "School Master" and "The Classroom".

Strings Anagram or not Python program

Python program to check whether the given strings are anagrams or not can be written by using one of the following options.

  1. Sorting both the strings
  2. By iterating one of the string character by character and verifying that the second string has the same characters present.

1. By sorting string

If you are using sorting logic to find whether strings are anagram or not in Python, just sort both the strings and compare if content is equal that means strings are anagram.

You can use sorted() in built function in Python to sort which returns a new sorted list from the items in iterable. Before sorting the string you can also change the case of the strings and remove spaces from the string.

import re

def is_anagram(s1, s2):
  # change to Lower case and remove leading, trailing
  # and spaces in between
  temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
  temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
  print('s1 in lower case and no spaces-', temp1)
  print('s2 in lower case and no spaces-', temp2)

  if sorted(temp1) == sorted(temp2):
    print(s1, 'and', s2, 'are anagrams')
  else:
    print(s1, 'and', s2, 'are not anagrams')
        
is_anagram('silent', 'listen')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- silent
s2 in lower case and no spaces- listen
silent and listen are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

2. By Iteration

If you are using loop to find whether strings are anagram or not in Python, then iterate one string char by char and check whether that character exists in another string or not, for that you can use find() method.

If character exists in the second string then delete that occurrence of the character from the string too so that same character is not found again (if char occurs more than once).

import re

def is_anagram(s1, s2):
  # change to Lower case and remove leading, trailing
  # and spaces in between
  temp1 = re.sub("^\\s+|\\s+$|\\s+", "", s1.lower())
  temp2 = re.sub("^\\s+|\\s+$|\\s+", "", s2.lower())
  print('s1 in lower case and no spaces-', temp1)
  print('s2 in lower case and no spaces-', temp2)
  # if both strings are not of same length then not anagrams
  if len(temp1) != len(temp2):
    print(s1, 'and', s2, 'are not anagrams')

  for c in temp1:
    index = temp2.find(c);
    if index == -1:
      print(s1, 'and', s2, 'are not anagrams')
      break
    else:
      # delete the found character so that same character is
      # not found again
      temp2.replace(c, "", 1)
  else:
    print(s1, 'and', s2, 'are anagrams')

is_anagram('Hello', 'OHell')
is_anagram('School Master', 'The Classroom')
is_anagram('Peak', 'Keep')

Output

s1 in lower case and no spaces- hello
s2 in lower case and no spaces- ohell
Hello and OHell are anagrams
s1 in lower case and no spaces- schoolmaster
s2 in lower case and no spaces- theclassroom
School Master and The Classroom are anagrams
s1 in lower case and no spaces- peak
s2 in lower case and no spaces- keep
Peak and Keep are not anagrams

That's all for this topic Python Program to Check if Strings Anagram or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Armstrong Number
  2. Python Program to Check Whether String is Palindrome or Not
  3. Python Program to Check Prime Number
  4. Removing Spaces From String in Python
  5. Accessing Characters in Python String

You may also like-

  1. Python continue Statement With Examples
  2. Polymorphism in Python
  3. Functions in Python
  4. Constructor in Python - __init__() function
  5. Switch Case Statement in Java
  6. HashMap in Java With Examples
  7. Convert Numbers to Words Java Program
  8. Configuring DataSource in Spring Framework

Saturday, December 24, 2022

Difference Between HashMap And Hashtable in Java

Though both Hashtable and HashMap in Java have some similarities like storing elements as a (key, value) pair and using hashing technique to store elements. From Java V1.2, Hashtable class was also retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Still there are some differences in these two data structures. In this post we'll see those differences between HashMap and Hashtable in Java.

HashMap Vs Hashtable in Java

  • HashMap is not synchronized where as Hashtable is synchronized. Which essentially means that Hashtable is inherently thread safe where as HashMap is not. If we need to synchronize a HashMap then that has to be done explicitly by calling the following method.
    Map m = Collections.synchronizedMap(hashMap);
    
  • HashMap allows one null value as a key and any number of null values.
    Hashtable does not allow null values either as key or as value.
  • For traversing a HashMap an iterator can be used. That iterator is fail-fast and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method.
    For traversing a Hashtable either an iterator or Enumerator can be used. Here again the iterator is fail-fast where as Enumerator is fail-safe.
    public class HashTableDemo {
      public static void main(String[] args) {
        Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);
        // Using enumerator
        for (Enumeration<String> e = numbers.keys(); e.hasMoreElements();){
          System.out.println(e.nextElement());
          numbers.put("four", 4);
        }
    
        // Using iterator
        Iterator<String> itr =  numbers.keySet().iterator();
        while (itr.hasNext()){
          System.out.println(numbers.get(itr.next()));
          numbers.put("five", 5);
        }  
      }
    }
    

    Output

    two
    one
    three
    four
    2
    Exception in thread "main" java.util.ConcurrentModificationException
     at java.util.Hashtable$Enumerator.next(Unknown Source)
     at org.netjs.prog.HashTableDemo.main(HashTableDemo.java:22)
    

    Here it can be seen that while enumerating a Hashtable if a new value is added (i.e. Hashtable is structurally modified) that doesn't throw any exception. Whereas, if a new value is added, while iterating it throws a ConcurrentModificationException.

  • Performance wise HashMap is faster than the Hashtable reason being HashMap is not synchronized.

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


Related Topics

  1. How HashMap Works Internally in Java
  2. LinkedHashMap in Java With Examples
  3. TreeMap in Java With Examples
  4. Difference Between HashMap And ConcurrentHashMap in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. static Reference to The Non-static Method or Field Error
  2. Abstraction in Java
  3. ThreadLocal class in Java With Examples
  4. Setter-based dependency injection in Spring
  5. How to Remove Duplicate Elements From an ArrayList in Java
  6. EnumSet in Java With Examples
  7. Java BlockingQueue With Examples
  8. @FunctionalInterface Annotation in Java

Friday, December 23, 2022

Difference Between throw And throws in Java

In this post we'll see the difference between throw and throws keyword in Java which are used in Java exception handling. These two keywords, though look similar, are functionality wise very different

  • throw is used to throw an exception.
  • throws is used to declare an exception, that can be thrown from a method, in the method signature.

throw Vs throws in Java

  1. We can declare multiple exceptions as a comma separated list with throws statement.
    We can throw only one exception using throw keyword in Java.

    throws Example

    public void displayFile() throws IOException, ArithmeticException
    

    throw Example

    throw new NullPointerException();
    throw new FileNotFoundException();
    
  2. throw keyword in Java is followed by an object of the Exception class.
    throws is followed by exception class names themselves.

    throw Example

    catch(FileNotFoundException fExp){   
     // throwing fExp which is an object of FileNotFoundException type
     throw fExp;
    }
    
    // creating object and throwing
    throw new FileNotFoundException();
    

    throws Example

    public void displayFile() throws IOException, ArithmeticException
    

    It can be seen that Exception class name itself is in the declaration.

  3. throws clause in Java is used to declare an exception in the signature of the method where as throw keyword is used to throw an exception explicitly with in the code of the method or from a static block.

    throw from a static block

    static int i;
    static int b;
    static {
     System.out.println("in static block");
     try{
      i = 5;
      b = i * 5;
     }catch(Exception exp){
      System.out.println("Exception while initializing" + exp.getMessage());
      throw exp;
     }
     //System.out.println("Values " + i + " " +  b);
    }
    
  4. throws clause is used to declare that the method may throw the declared exceptions and calling method should provide the exception handling code.
    throw actually throws the exception and the run time system goes through the method hierarchy to search for a method that can handle the exception.

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


Related Topics

  1. throws Keyword in Java Exception Handling
  2. Java Exception Handling And Method Overriding
  3. Exception Propagation in Java Exception Handling
  4. Nested Try Statements in Java Exception Handling
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Encapsulation in Java
  2. Difference Between Abstract Class And Interface in Java
  3. Constructor overloading in Java
  4. static Import in Java With Examples
  5. How ArrayList Works Internally in Java
  6. Can we start the same thread twice in Java
  7. interface default methods in Java 8
  8. Method Reference in Java

Thursday, December 22, 2022

Python Program to Check Whether String is Palindrome or Not

This post is about writing a Python program to find whether a given string is a palindrome or not.

A String is a palindrome if reverse of the string is same as the original string. For example "madam" is a palindrome as reverse of the madam is again madam another example is "malayalam".

Logic for the palindrome program

  1. One way to find whether a given string is a palindrome or not is to reverse the given string. If reverse of the string and original string are equal that means string is a palindrome.
  2. Another way is to iterate string and compare characters at both ends (start and end) for equality. Any time if a character is found that is not equal before start > end then it is not a palindrome.

1. Reversing string and comparing

For reversing a string in Python best way is to use string slicing with a negative increment number to get the string backward. Once you have the reversed string compare it with original string to check if both are equal or not.

import re
def reverse_string(string):
  rstring = string[::-1]
  return rstring

def is_palindrome(s):
  rstring = reverse_string(s)
  return True if (rstring == s) else False

s = "madam"
# if more than one word remove spaces
# s = re.sub("^\\s+|\\s+$|\\s+", "", s)
# print(s)
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

madam is a palindrome

Note that if string has more than one word like “nurses run” then remove the spaces from the string before checking for palindrome string. You can uncomment the commented lines for that.

2. Comparing characters from start and end of the string

You can also compare characters from both ends of the string, if any time a character is found which is not equal then the passed string is not a palindrome. Python program to find whether given string is a palindrome or not using this logic can be written both as a recursive function and iterative function.

Recursive function is given first.

def is_palindrome(s):
  print(s)
  if len(s) == 0:
    return True
  else:
    if s[0] == s[-1]:
      # remove start and end characters
      return is_palindrome(s[1:len(s)-1])
    else:
      return False

s = "radar"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

radar
ada
d

radar is a palindrome

As an iterative function.

def is_palindrome(s):
  # last index
  end = len(s) - 1;
  for start in range(len(s)):
    # all the characters are compared and are equal
    if start > end:
      return True
    else:
      # compare characters at both ends
      if s[start] == s[end]:
        # move towards left
        end -= 1
      else:
        return False

s = "malayalam"
flag = is_palindrome(s)
if flag == 1:
  print(s, 'is a palindrome')
else:
  print(s, 'is not a palindrome')

Output

malayalam is a palindrome

That's all for this topic Python Program to Check Whether String is Palindrome or Not. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Reverse a String
  2. Python Program to Display Armstrong Numbers
  3. Getting Substring in Python String
  4. Python String isnumeric() Method
  5. Python Generator, Generator Expression, Yield Statement

You may also like-

  1. Ternary Operator in Python
  2. Operator Overloading in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Java CountDownLatch With Examples
  6. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  7. How to Write Excel File in Java Using Apache POI
  8. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

Wednesday, December 21, 2022

Python Program to Display Armstrong Numbers

In this post we'll see a Python program to display Armstrong numbers with in the given range.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Display Armstrong numbers Python program

In the program user is prompted to input lower and upper range for displaying Armstrong numbers. Then run a for loop for that range, checking in each iteration whether the number is an Armstrong number or not.

def display_armstrong(lower, upper):
  for num in range(lower, upper + 1):
    digitsum = 0
    temp = num
    # getting length of number
    no_of_digits = len(str(num))
    while temp != 0:
      digit = temp % 10
      # sum digit raise to the power of no of digits
      digitsum += (digit ** no_of_digits)
      temp = temp // 10
    # if sum and original number equal then Armstrong number
    if digitsum == num:
      print(num, end=' ')

def get_input():
  """Function to take user input for display range"""
  start = int(input('Enter start number for displaying Armstrong numbers:'))
  end = int(input('Enter end number for displaying Armstrong numbers:'))
  # call function to display Armstrong numbers
  display_armstrong(start, end)

# start program
get_input()

Output

Enter start number for displaying Armstrong numbers:10
Enter end number for displaying Armstrong numbers:10000
153 370 371 407 1634 8208 9474 

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

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Prime Numbers
  2. Convert String to float in Python
  3. Python Program to Count Number of Words in a String
  4. Check String Empty or Not in Python
  5. Comparing Two Strings in Python

You may also like-

  1. Ternary Operator in Python
  2. Polymorphism in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Difference Between Comparable and Comparator in Java
  6. Java Semaphore With Examples
  7. Converting Enum to String in Java
  8. Sending Email Using Spring Framework Example

Tuesday, December 20, 2022

React Virtual DOM

If you are using React you would have definitely heard that React uses virtual DOM which makes it faster. In this post we'll see what is virtual DOM in React and how does it speed up the React rendering.

Document Object Model

We'll start with a bit of understanding of DOM which makes it easier to understand Virtual DOM in turn and how these two compares.

If you have used JavaScript you would have probably used methods like document.getElementById() or document.getElementsByName(), these methods can access the element with the specific ID or the element with specific name because of the creation of Document Object Model (DOM).

When an HTML page is received by a browser, page is parsed and converted into a tree like structure of objects known as DOM. An object is created for each HTML element in the document which is represented by a tree node.

Document Object Model

All of the properties, methods, and events available for manipulating and creating web pages are organized into objects.

The DOM represents the document as nodes and objects. As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.

Because of the tree like structure accessing and updating node is fast but re-rendering is not efficient because for each update DOM is created and rendered again.

Virtual DOM - How it is fast

A Virtual DOM (VDOM) is a lightweight representation of the DOM which is kept in memory. Now you may think how it is faster as now you have two copies Virtual DOM and Browser DOM meaning more overhead.

It is actually the rendering process with React Virtual DOM which makes it faster while also confirming with the React declarative approach. In declarative approach you specify what state you want and React makes it happen.

React maintains two virtual DOMs in memory, when there is any change in the data, React creates a new Virtual DOM with the changes accommodated in it. So, there is a virtual DOM representing a new state and a virtual DOM with previous state.

Once there are two copies of VDOM two things happen-

  1. React has to know what has changed, that process is known as diffing. In the diffing process previous and current virtual DOMs are compared to find out the nodes with changes.
  2. Update only the changed node(s) in the “real” DOM. This process in React is called reconciliation and done by a library such as ReactDOM. Since the whole DOM (Browser or real DOM) is not re-created, only the modified nodes are updated and rendered on the browser the rendering process becomes faster and more efficient.
React virtual DOM

That's all for this topic React Virtual DOM. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JSX in React
  2. React HelloWorld App - First React App
  3. Controlled and Uncontrolled Components in React
  4. JavaScript filter Method

You may also like-

  1. ArrayList in Java With Examples
  2. static Reference to The Non-static Method or Field Error
  3. How to Create PDF in Java Using OpenPDF
  4. Dependency Injection in Spring Framework

Monday, December 19, 2022

Java Program to Display Prime Numbers

This post shows a Java program to display prime numbers.

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example- 2, 3, 5, 7, 11, 13, 17 ….

To check if a number is prime or not you need to run a loop starting from 2 till number/2 to check if number has any divisor.

For example, if number is 8 then you just need to check till 4 (8/2) to see if it divides by any number or not. Same way if you have a number 15 you just need to check till 7 to see if it divides completely by any number or not. We'll use the same logic to write our program to display prime numbers up to the given upper range.

Tuesday, December 13, 2022

JavaScript filter Method With Examples

The JavaScript Array filter() method is used to filter out the elements from the given array that doesn't pass the condition implemented by the provided function and return a new array with the remaining elements.

JavaScript filter method syntax

filter(callbackFunction(element, index, array), thisArg)

Parameters:

  1. callbackFunction- A function to execute for each element in the array. In this function you will write the condition that should return true to keep the element in the resulting array, false otherwise.
    The callback function is called with the following arguments:
    • element- The element in the array being processed currently.
    • index- The index of the current element being processed in the array.
    • array- The array filter() was called upon.
  2. thisArg- This parameter is optional. A value to be used as this when executing callbackFunction.

Filter method returns a new array consisting of the elements that pass the condition of the callback function.

JavaScript filter() examples

1. In an array of cities you want to get cities having length > 7.

const cities = ['Mumbai', 'Bengaluru', 'London', 'Beijing', 'Charlotte'];

function checkCity(city){
  return city.length > 7;
}
const newCities = cities.filter(checkCity);
console.log(newCities); //  ['Bengaluru', 'Charlotte']
Callback function can also be written as an arrow function to make code more concise and readable.
const cities = ['Mumbai', 'Bengaluru', 'London', 'Beijing', 'Charlotte'];
const newCities = cities.filter(city => city.length > 7);
console.log(newCities);

2. To get the even numbers in an array of numbers.

const numbers = [2, 5, 10, 13, 24, 56, 68, 75];
const evenNum = numbers.filter(num => num%2 == 0);
console.log(evenNum); // [2, 10, 24, 56, 68]

3. In an array of Person objects filter out all persons having age < 18

const persons = [{id:1, name:"Ajay", age:9}, 
                  {id:2, name:"Rajiv", age:22}, 
                  {id:3, name:"Bosco", age:25},
                  {id:4, name:"Albert", age:3}];

const personArr = persons.filter(p => p.age > 18);
console.log(personArr); 

//Output
{id: 2, name: 'Rajiv', age: 22}
{id: 3, name: 'Bosco', age: 25}

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


Related Topics

  1. JavaScript Array and Object Destructuring
  2. JavaScript Rest Parameter
  3. JavaScript Array slice() method With Examples
  4. React Declarative Approach

You may also like-

  1. BigInteger in Java With Examples
  2. What is Client Side Routing in Angular
  3. HashMap in Java With Examples
  4. Bean Definition Inheritance in Spring

Creating New Component in Angular

Components are the building block of any Angular application. A well designed UI should break its rendering into different components where each component renders the particular portion of the UI. That makes it more manageable and also the same components can be reused. In this article we’ll see how you can create a component in Angular.

Creating component in Angular

You can create a component using one of the following ways-

Creating component using Angular CLI

Navigate to the root folder of your Angular application and run the following command to create a new component.

ng generate component COMPONENT_NAME

OR

ng g c COMPONENT_NAME

If I want to create a component named hello-world then it can be done as given below-

F:\NETJS\Angular WS\hello-world-app>ng generate component hello-world

CREATE src/app/hello-world/hello-world.component.html (26 bytes)
CREATE src/app/hello-world/hello-world.component.spec.ts (657 bytes)
CREATE src/app/hello-world/hello-world.component.ts (294 bytes)
CREATE src/app/hello-world/hello-world.component.css (0 bytes)
UPDATE src/app/app.module.ts (576 bytes)

As you can see creation of component results in creation of 4 new files and also in automatic updation of app.module.ts. Created files have specific roles as given here-

  1. hello-world.component.ts- This is the class where code for the component is written in TypeScript.
  2. hello-world.component.html- The component template, written in HTML.
  3. hello-world.component.css- The component's private CSS styles.
  4. hello-world.component.spec.ts- Defines a unit test for the hello-world component.

The update in the app.module.ts is-

  • Inclusion of import statement to import the type script file of the newly created component.
  • Inclusion of newly created component in the declarations array with in the @NgModule decorator.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Changing HTML template

Let’s change the template src/app/hello-world/hello-world.component.html and add some code.

<!--Using Bootstrap for styling-->
<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <h1>Success Message</h1>
      <p class="text-succcess"><strong>Success!</strong> Able to create a component.</p>
    </div>
  </div>
</div>

Note that in the html, bootstrap is used. Refer How to Add Bootstrap to Angular Application to see how to add Bootstrap to angular.

Also add the <app-hello-world> tag in the app.component.html to render the view.

<app-hello-world></app-hello-world>

Now if you build the application using ng serve command and access the URL http://localhost:4200/ you should see the rendered template.

Creating component in Angular

Creating component manually

You can also create a component manually. Once you have the Angular project structure created using ng new command you can open it in the IDE you are using. I am using Visual Code here but the steps remain same.

Go the src-app folder with in your opened application right click – New Folder and create a new Folder for your component. I have named it “hello-world”.

Angular development using Visual code

Right click the newly created component folder and select new file and create the following two files for Type Script and Template.

  • hello-world.component.ts
  • hello-world.component.html

Open hello-world.component.ts and copy the following code.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hello-world',
  templateUrl: './hello-world.component.html'
})
export class HelloWorldComponent implements OnInit {

  constructor() { }

  ngOnInit(){
  }
}

Open hello-world.component.html and copy the following code.

<!--Using Bootstrap for styling-->
<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <h1>Success Message</h1>
      <p class="text-succcess"><strong>Success!</strong> Able to create a component.</p>
    </div>
  </div>
</div>

In the app.module.ts add the import statement for the new component as well as add it in declarations array too with in @NgModule decorator.

import { HelloWorldComponent } from './hello-world/hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent
  ],

Also add the <app-hello-world> tag in the app.component.html to render the view. Note that this tag should match the Selector attribute value of @Component decorator used in Component class.

<app-hello-world></app-hello-world>

With this, manually creating component in Angular is done, you can build the application using ng serve command and access the URL http://localhost:4200/

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

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular @Component Decorator
  2. How to Install Node.js and NPM in Windows
  3. How to Setup Angular
  4. Angular Project Structure With File Description
  5. Angular Application Bootstrap Process

You may also like-

  1. Angular First App - Hello world Example
  2. Angular ngFor Directive With Examples
  3. Angular Disable Button Example
  4. Python Exception Handling Tutorial
  5. Java Multithreading Interview Questions And Answers
  6. Spring Boot StandAlone (Console Based) Application Example
  7. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  8. Bounded Type Parameter in Java Generics

Monday, December 12, 2022

JavaScript Rest Parameter

The JavaScript rest parameter syntax allows a function to accept variable number of arguments (zero or more) as an array. It is similar to varargs in Java.

Rest parameter syntax

Rest parameter is specified using three dots (…)

function myFunc(a, b, ...restParam) {  
  // block of statements 
}  

If you have a rest parameter in your function along with other parameters then it has to be the last argument because it has to collect the remaining arguments into an array.

Rest parameter syntax (…) is similar to spread operator in JavaScript but they do opposite job. In case of spread operator array is expanded where as in case of rest parameter arguments are collected into an array.

Rest parameter JavaScript example

A typical example is to do any mathematical operation like sum. If you write a normal function with two parameters, it will add two parameters only.

function sum(a, b){
	return a + b;
}

console.log(sum(1, 2)); // 3	
console.log(sum(1, 2, 3, 4)); //No error, but function returns 3 

As you can see when the function is called with more parameters, it still takes the first 2 and returns the sum of those arguments. If you want your sum function to be more generic which can work with any number of parameters then rest parameter gives you that functionality.

function sum(...args) {
  var s = 0;
  for(let x of args){
    s += x;
  }
  return s
}
	
console.log(sum(1, 2)); // 3

console.log(sum(1, 2, 3, 4));  //10

Rest parameter with other parameters

You can have other parameters in your function along with rest parameter but in that case rest parameter should be the last one. For example, in the following function there are two parameters and then a rest parameter.

function myFunc(a, b, ...restParam)

Calling this function like this myFunc(1, 2, 3, 4, 5) maps the first two arguments to a and b and other three parameters are passed as any array to restParam.

function myFunc(a, b, ...restParam) {
  console.log("a ", a); //a  1
  console.log("b ", b); // b  2
  console.log("Rest of the params ", restParam); // Rest of the params  (3) [3, 4, 5]
}

myFunc(1, 2, 3, 4, 5);

Rules for using Rest parameter in JavaScript

  1. One of the rules as already showed is that rest parameter must be the last parameter of the function.
    function myFunc(...restParam, a, b) {} // Wrong function definition
    
  2. A function definition can only have one rest parameter.
    function myFunc(...firstParam, ...secondParam) {} // Wrong function definition
    

That's all for this topic JavaScript Rest Parameters. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Array and Object Destructuring
  2. JavaScript let and const With Examples
  3. JavaScript Arrow Function With Examples
  4. JSX in React

You may also like-

  1. First Java Program - Hello World Java Program
  2. Dependency Injection in Spring Framework
  3. HashMap in Java With Examples
  4. Format Date in Java Using SimpleDateFormat

Sunday, December 11, 2022

Lambda Expression Examples in Java

As we have already seen in the post about Java lambda expressions, they implement the abstract method of the functional interface. In that way lambda expressions can provide a compact and easy to read code which is not repetitive by using them in place of anonymous classes.

Using functional interfaces with anonymous inner classes is a common pattern in Java, from Java 8 lambda expressions provide a better alternative by implementing the abstract method of the functional interface.

In this post we'll see some examples of lambda expressions in Java like Runnable as lambda expression, Comparator as lambda expression, lambda expression implementation of Predicate functional interface.

Runnable as Lambda expression example

It is very common to implement the run() method of Runnable interface as an anonymous class, now same can be done with lambda expression in fewer lines increasing readability.

public class RunnableLambda {
  public static void main(String[] args) {
    // Runnable using anonymous class
    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("Runnable with anonymous");
      }
    }).start();
    
    // Runnable using lambda
    new Thread(()->System.out.println("Runnable Lambda")).start();
  }
}

It can be seen how concise the implementation becomes with lambda expression.

Comparator as Lambda expression example

In this example we'll have a list of Person object and they are sorted on first name using Comparator.

Person class

public class Person {
  private String firstName;
  private String lastName;
  private int age;
  private char gender;
  Person(String firstName, String lastName, int age, char gender){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.gender = gender;
  }
    
  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public int getAge() {
    return age;
  }
  public char getGender() {
    return gender;
  }
    
  public String toString(){
    StringBuffer sb = new StringBuffer();
    sb.append(getFirstName()).append(" ");
    sb.append(getLastName()).append(" ");
    sb.append(getAge()).append(" ");
    sb.append(getGender());
    return sb.toString();    
  }
}
// Functional interface
@FunctionalInterface
interface IMyInterface {
  Person getRef(String firstName, String lastName, int age, char gender);
}

public class LambdaExpressionDemo {
  public static void main(String[] args) {
    List<Person> personList = createList();
    
    // comparator implementation as anonymous class
    // and sorting the list element on the basis of first name
    Collections.sort(personList, new Comparator<Person>() {
      public int compare(Person a, Person b) {
        return a.getFirstName().compareTo(b.getFirstName());
      }
    });
        
    System.out.println("Sorted list with anonymous implementation");
    for(Person p : personList){
      System.out.print(p.getFirstName() + " ");
    }
        
    // creating the same list again to use with lambda expression
    personList = createList();
    // Providing the comparator functional interface compare
    /// method as lambda exression
    Collections.sort(personList, (Person a, Person b) -> 
        a.getFirstName().compareTo(b.getFirstName()));
    System.out.println("Sorted list with lambda implementation");
    // Using the new ForEach loop of Java 8 
    // used with lambda expression
    personList.forEach((per) -> System.out.print(per.getFirstName() + " "));
  }
    
  // Utitlity method to create list
  private static List<Person> createList(){
    List<Person> tempList = new ArrayList<Person>();
    IMyInterface createObj = Person::new;
    Person person = createObj.getRef("Ram","Tiwari", 50, 'M');
    tempList.add(person);
    person = createObj.getRef("Prem", "Chopra", 13, 'M');
    tempList.add(person);
    person = createObj.getRef("Tanuja", "Trivedi", 30, 'F');
    tempList.add(person);
    person = createObj.getRef("Manoj", "Sharma", 40, 'M');
    tempList.add(person);
    System.out.println("List elements are - ");
    System.out.println(tempList);
    return tempList;
  }
}

Output

List elements are - 
[Ram Tiwari 50 M, Prem Chopra 13 M, Tanuja Trivedi 30 F, Manoj Sharma 40 M]
Sorted list with anonymous implementation
Manoj Prem Ram Tanuja List elements are - 
[Ram Tiwari 50 M, Prem Chopra 13 M, Tanuja Trivedi 30 F, Manoj Sharma 40 M]
Sorted list with lambda implementation
Manoj Prem Ram Tanuja

Here I have used some of the features of Java 8 like Constructor reference using Double colon operator, which is this line IMyInterface createObj = Person::new;

Also used the new forEach statement in Java 8 with lambda expression, which is this line-

personList.forEach((per) -> System.out.print(per.getFirstName() + " "));

Same way lambda expression can be used with other functional interfaces like Callable, ActionListener etc.

Lambda expression with inbuilt functional interfaces

With Java 8 many new functional interfaces are being defined, in fact there is a whole new package java.util.function added with many functional interfaces. The interfaces in this package are general purpose functional interfaces used by the JDK, and are available to be used by user code as well.

The following are some of the examples of new functional interfaces in Java 8-

public interface Predicate<T> {
  boolean test(T t);
}
 
public interface Function<T,R> {
  R apply(T t);
}
 
public interface BinaryOperator<T> {
  T apply(T left, T right);
}
 
public interface Consumer<T> {
  void accept(T t);
}
 
public interface Supplier<T> {
  T get();
}

Starting with Java 8 these functional interfaces can be implemented by means of lambda expressions and method references.

We have already seen in the above examples how using lambda expressions we can solve the vertical problem associated with anonymous classes and make the code concise and more readable. Here let's see an example using one of the inbuilt functional interface.

Predicate functional interface as Lambda expression implementation

Supposing we want to use inbuilt functional interface named Predicate declared as follows:

public interface Predicate<T> {
  boolean test(T t);
}

We have a class person and using that person list we want to implement a search criteria where we want to search and print the following-

  1. List of drivers (age >= 16)
  2. List of voters (age >= 18)
  3. List of senior citizens (age >= 60)

We'll use the inbuilt functional interface Predicate to set up the search criteria. Note that we don’t need to explicitly write the Predicate interface as it is already available, we just need to import it from java.util.function package.

Person Class

public class Person {
  private String firstName;
  private String lastName;
  private int age;
  private char gender;
  public Person(String firstName, String lastName, int age, char gender){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.gender = gender;
  }
    
  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public int getAge() {
    return age;
  }
  public char getGender() {
    return gender;
  }
    
  public String toString(){
    StringBuffer sb = new StringBuffer();
    sb.append(getFirstName()).append(" ");
    sb.append(getLastName()).append(" ");
    sb.append(getAge()).append(" ");
    sb.append(getGender());
    return sb.toString();    
  }
}
@FunctionalInterface
interface IMyFunc {
  Person getRef(String firstName, String lastName, int age, char gender);
}

public class LambdaDemo {
    
  public static void main(String args[]){
    List<Person> personList = createList();
    ListPerson listPerson = new ListPerson();
    //Predicates
    // For age >= 16
    Predicate<Person> allDrivers = p -> p.getAge() >= 16;
    // For age >= 18
    Predicate<Person> allVoters = p -> p.getAge() >= 18;
    // For age >= 60
    Predicate<Person> allSeniorCitizens = p -> p.getAge() >= 60;
    // calling method to list drivers, passing predicate as arg
    listPerson.listDrivers(personList, allDrivers);
    
    // calling method to list voters, passing predicate as arg 
    listPerson.listVoters(personList, allVoters);
    
    // calling method to list senior citizens, passing predicate as arg 
    listPerson.listSeniorCitizens(personList, allSeniorCitizens);       
  }
    
  // Utitlity method to create list
  private static List<Person> createList(){
    List<Person> tempList = new ArrayList<Person>();
    // Constructor reference
    IMyFunc createObj = Person::new;
    Person person = createObj.getRef("Ram","Tiwari", 50, 'M');
    tempList.add(person);
    person = createObj.getRef("Prem", "Chopra", 13, 'M');
    tempList.add(person);
    person = createObj.getRef("Tanuja", "Trivedi", 30, 'F');
    tempList.add(person);
    person = createObj.getRef("Manoj", "Sharma", 40, 'M');
    tempList.add(person);
    person = createObj.getRef("John", "Trevor", 70, 'M');
    tempList.add(person);
    person = createObj.getRef("Alicia", "Sliver", 17, 'F');
    tempList.add(person);
    System.out.println("List elements are - ");
    System.out.println(tempList);
    return tempList;
  }
}

class ListPerson {
  // method to list drivers
  public void listDrivers(List<Person> personList, Predicate<Person> pred){
    List<Person> driverList = new ArrayList<Person>();
    for(Person person : personList){
      if (pred.test(person)){
        driverList.add(person);    
      }
    }
    System.out.println("List of drivers ");
    printList(driverList);
  }
    
  // method to list voters
  public void listVoters(List<Person> personList, Predicate<Person> pred){
    List<Person> voterList = new ArrayList<Person>();
    for(Person person : personList){
      if (pred.test(person)){
        voterList.add(person);    
      }
    }
    System.out.println("List of voters ");
    printList(voterList);
  }
    
  // method to list senior citizens
  public void listSeniorCitizens(List<Person> personList, Predicate<Person> pred){
    List<Person> seniorCitizenList = new ArrayList<Person>();
    for(Person person : personList){
      if (pred.test(person)){
        seniorCitizenList.add(person);    
      }
    }
    System.out.println("List of senior citizens ");
    printList(seniorCitizenList);
  }
 
  // Method used for printing the lists
  private void printList(List<Person> personList){
    personList.forEach((p) -> System.out.print(" FirstName - " + p.getFirstName()  
            + " LastName - " + p.getLastName() + " Age - " + p.getAge()));
    System.out.println("");
  }
}

It can be seen how concise and readable the code becomes and it is also non-repetitive, if we were using anonymous classes to write these search criteria we would have done the same chore of taking new instance of interface Predicate and overriding the test method for each search criteria. The anonymous class implementation for getting the list of drivers would have looked like this.

listPerson.listDrivers(personList, new Predicate<Person>(){
   @Override
   public boolean test(Person p){
       return p.getAge() >=16;
   }
});

So it can be seen how lambda expression can help with solving the vertical problem associated with anonymous class and provides a better alternative to provide implementation of functional interfaces.

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


Related Topics

  1. Functional Interface Annotation in Java
  2. Method Reference in Java
  3. How to Resolve Local Variable Defined in an Enclosing Scope Must be Final or Effectively Final Error
  4. Java Lambda Expression And Variable Scope
  5. Java Lambda Expressions Interview Questions And Answers

You may also like-

  1. How HashMap Works Internally in Java
  2. Executor And ExecutorService in Java With Examples
  3. final Vs finally Vs finalize in Java
  4. Difference Between throw And throws in Java
  5. static Method Overloading or Overriding in Java
  6. Covariant Return Type in Java
  7. Effectively Final in Java 8
  8. Interface Default Methods in Java 8

Saturday, December 10, 2022

Externalizable Interface in Java

Serialization in Java provides a pretty good default implementation for serializing and deserializing an object. All you need to do is to implement Serializable interface and the whole process is automatic for you.

But, what if you want to control the process of serialization, you have some fields in your object which hold confidential information and you don’t want to serialize those fields or a sub-object with in your object graph doesn’t need to be serialized. That’s when you can use Externalizable interface in Java for custom serialization and deserialization.


Externalizable interface in Java

Externalizable interface extends the Serializable interface (which is a marker interface) and adds two methods writeExternal() and readExternal().

When you use Externalizable for your serialization, you will implement Externalizable interface and implement writeExternal() and readExternal() methods. These two methods will be called while serializing and deserializing respectively.

General form of writeExternal() and readExternal()

  • readExternal(ObjectInput in)- The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
  • writeExternal(ObjectOutput out)- The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.

Refer Serialization in Java to see another way, using readObject and writeObject to control the process of serialization.

Serialization process when Externalizable interface is used

Each object to be stored is tested for the Externalizable interface. If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream.

When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor, then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.

Externalizable interface Java example

Let’s see an example where we have a class called User in which pwd field is there that you don’t want to convert into bytes. Though that can also be done by marking it as transient but here let us see how Externalizable can be used to control the serialization.

User class

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class User implements Externalizable {
 private String userName;
 private int id;
 private String pwd;
 
 // no-arg constructor **Required**
 public User(){
  System.out.println("In no-arg constructor");
 }
 
 public User(String userName, int id, String pwd){
  System.out.println("In constructor with args");
  this.userName = userName;
  this.id = id;
  this.pwd = pwd;
 }
 
 public String getUserName() {
  return userName;
 }

 public int getId() {
  return id;
 }

 public String getPwd() {
  return pwd;
 }

 @Override
 public void writeExternal(ObjectOutput out) throws IOException {
  System.out.println("In writeExternal method");
  out.writeObject(userName);
  out.writeInt(id);
 }

 @Override
 public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
  System.out.println("In readExternal method");
  userName = (String)in.readObject();
  id = in.readInt();
 
 }
}

ExternalizableDemo class

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ExternalizableDemo {

 public static void main(String[] args) {
  User user = new User("TestUser", 1, "pwd");
  try {
   ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser"));
   oos.writeObject(user);
   oos.close();
   
   ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));

   user = (User)ois.readObject();
   ois.close();
   System.out.println("UserName " + user.getUserName() + " id " 
      + user.getId() + " pwd " + user.getPwd());
   
  } catch (IOException | ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

In constructor with args
In writeExternal method
In no-arg constructor
In readExternal method
UserName TestUser id 1 pwd null

Here you can see that writeExternal() and readExternal() methods are called for serializing and deserializing the object. Now it is upto you to provide implementation for serialization in writeExternal() method where pwd field is excluded.

Points to note here are-

  1. A default no-arg constructor has to be there while using externalizable as object is created using no-arg constructor while deserializing and then the object is initialized using the logic in readExternal() method. Note that it is different from default serialization where object is reconstituted using the byte stream and constructor is not called.
  2. Order that is used in writeExternal() method for writing the fields should be maintained in readExternal() method.

Externalizable with inheritance

One scenario where Externalizable can be used quite effectively is in a parent-child relationship where parent class doesn’t implement the serializable interface but you want the fields that are there in the parent class to be serialized too.

In this case if you create an object of the child class and serialize it using default serialization. Then deserializing it won’t give you any value for the fields which child class object gets by virtue of extending parent class.

Let’s say we have a classA which is the super class and classB which extends classA.

ClassA

public class ClassA {
  private int deptId;
  private String deptName;
  public int getDeptId() {
   return deptId;
  }
  public void setDeptId(int deptId) {
   this.deptId = deptId;
  }
  public String getDeptName() {
   return deptName;
  }
  public void setDeptName(String deptName) {
   this.deptName = deptName;
  }
}

ClassB

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class ClassB extends ClassA implements Externalizable{
 private String empId;
 private String empName;
 public String getEmpId() {
   return empId;
 }
 public void setEmpId(String empId) {
   this.empId = empId;
 }
 public String getEmpName() {
   return empName;
 }
 public void setEmpName(String empName) {
   this.empName = empName;
 }
 @Override
 public void writeExternal(ObjectOutput out) throws IOException {
  System.out.println("In writeExternal method");
  //Writing parent class ClassA fields
  out.writeInt(getDeptId());
  out.writeObject(getDeptName());
  // Writing child class fields
  out.writeObject(getEmpId());
  out.writeObject(getEmpName());
  
 }

 @Override
 public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
  System.out.println("In readExternal method");
  // Setting parent class fields
  setDeptId(in.readInt());
  setDeptName((String)in.readObject());
  // Setting child class fields
  setEmpId((String)in.readObject());
  setEmpName((String)in.readObject());
 }

}

Test class

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ExternalizableDemo {

 public static void main(String[] args) {
    final String fileName = "D://test.ser";
    ClassB objb = new ClassB();
    objb.setDeptId(1);
    objb.setDeptName("Finance");
    objb.setEmpId("E001");
    objb.setEmpName("Ram");
  try {
   ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
   oos.writeObject(objb);
   oos.close();
   
   ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));

   objb = (ClassB)ois.readObject();
   ois.close();
   System.out.println("DeptId " + objb.getDeptId() + " DeptName " + objb.getDeptName() 
     + " EmpId " + objb.getEmpId() + " EmpName "+ objb.getEmpName());
   
  } catch (IOException | ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

In writeExternal method
In readExternal method
DeptId 1 DeptName Finance EmpId E001 EmpName Ram

Since you can control what is serialized and how, you can make sure that all the fields of super class ClassA are also serialized and deserialized in the writeExternal() and readExternal() methods.

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

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. SerialVersionUID And Versioning in Java Serialization
  2. Serialization Proxy Pattern in Java
  3. Marker Interface in Java
  4. Java Reflection API Tutorial
  5. Java Object Cloning - clone() Method

You may also like-

  1. How HashSet Works Internally in Java
  2. Java Collections Interview Questions And Answers
  3. Java Semaphore With Examples
  4. Java Concurrency Interview Questions And Answers
  5. Synchronization in Java - Synchronized Method And Block
  6. Bounded Type Parameter in Java Generics
  7. Java Variable Types With Examples
  8. Difference Between Checked And Unchecked Exceptions in Java

Friday, December 9, 2022

Python Program to Check Prime Number

In this post we'll see a Python program to check whether the passed number is a prime number or not. This program also shows a use case where for loop with else in Python can be used.

A number is a prime number if it can only be divided either by 1 or by the number itself. So the passed number has to be divided in a loop from 2 till number/2 to check if number is a prime number or not.

You need to start loop from 2 as every number will be divisible by 1.

You only need to run your loop till number/2, as no number is completely divisible by a number more than its half. Reducing the iteration to N/2 makes your program to display prime numbers more efficient.

Check prime number or not Python program

def check_prime(num):
  for i in range(2, num//2+1):
    # if number is completely divisible then it
    # it is not a prime number so break out of loop
    if num % i == 0:
      print(num, 'is not a prime number')
      break
  # if loop runs completely that means a prime number
  else:
    print(num, 'is a prime number')

check_prime(13)
check_prime(12)
check_prime(405)
check_prime(101)

Output

13 is a prime number
12 is not a prime number
405 is not a prime number
101 is a prime number

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

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Python Program to Display Fibonacci Series
  3. Python Program to Display Prime Numbers
  4. Python break Statement With Examples
  5. Changing String Case in Python

You may also like-

  1. Python Exception Handling - try,except,finally
  2. Getting Substring in Python String
  3. Constructor in Python - __init__() function
  4. Name Mangling in Python
  5. Java Stream API Tutorial
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Selection Sort Program in Java
  8. Spring Bean Life Cycle

Thursday, December 8, 2022

Python Program to Check Armstrong Number

In this post we'll see a Python program to check if a given number is an Armstrong number or not.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so-

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Check Armstrong number or not Python program

In the program user is prompted to input a number. Number of digits in that number is calculated using len() function that takes string as input that is why number is cast to str.

In the loop add each digit of the input number raised to the power of number of digits. After the control comes out of loop if sum and the input number are equal then it is an Armstrong number otherwise not.

def check_armstrong(num):
  digitsum = 0
  temp = num
  # getting length of number
  no_of_digits = len(str(num))
  while temp != 0:
    digit = temp % 10
    # sum digit raise to the power of no of digits
    digitsum += (digit ** no_of_digits)
    temp = temp // 10
  print('Sum of digits is',  digitsum)
  # if sum and original number equal then Armstrong number
  return True if (digitsum == num) else False

num = int(input('Enter a number: '))
flag = check_armstrong(num)
if flag:
  print(num, 'is an Armstrong number')
else:
  print(num, 'is not an Armstrong number')

Output

Enter a number: 371
Sum of digits is 371
371 is an Armstrong number

Enter a number: 12345
Sum of digits is 4425
12345 is not an Armstrong number

Enter a number: 54748
Sum of digits is 54748
54748 is an Armstrong number

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

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Prime Number
  2. Python Program to Display Fibonacci Series
  3. Python Program to Count Occurrences of Each Character in a String
  4. Python continue Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Name Mangling in Python
  2. Python Generator, Generator Expression, Yield Statement
  3. Constructor in Python - __init__() function
  4. Multiple Inheritance in Python
  5. ArrayList in Java With Examples
  6. Callable And Future in Java Concurrency
  7. Nested Class And Inner Class in Java
  8. Spring MessageSource Internationalization (i18n) Support