Wednesday, 10 January 2018

Default Array Values in Java

In Java, If we try to access the simple variable without assign any value to it then compiler will produce error. But if we don't assign the values to an array elements then compiler will assign a value to them which are not garbage.

Here are the default assigned values of arrays:

int: 0
double: 0.0
short: 0
String: null
boolean: false

EXAMPLE:

import java.util.*;

class array_default_values{
 
      public static void main(String args[]){

          System.out.print("\n\n");

            int[] arr_int=new int[6];
            System.out.println("The default values of integer array is: ");
            for(int i=0;i<arr_int.length;i++){
                 System.out.print(arr_int[i]+" ");
            }

            System.out.print("\n\n");

            boolean[] arr_bool=new boolean[6];
            System.out.println("The default values of boolean array is: ");
            for(int i=0;i<arr_bool.length;i++){
                  System.out.print(arr_bool[i]+" ");
            }

            System.out.print("\n\n");

            double[] arr_double=new double[6];
            System.out.println("The default values of double array is: ");
            for(int i=0;i<arr_double.length;i++){
                  System.out.print(arr_double[i]+" ");
            }

            System.out.print("\n\n");

            String[] arr_string=new String[6];
            System.out.println("The default values of string array is: ");
            for(int i=0;i<arr_string.length;i++){
                  System.out.print(arr_string[i]+" ");
            }

            System.out.print("\n\n");

            short[] arr_short=new short[6];
            System.out.println("The default values of short array is: ");
            for(int i=0;i<arr_short.length;i++){
                  System.out.print(arr_short[i]+" ");
            }


            System.out.print("\n\n");

            byte[] arr_byte=new byte[6];
            System.out.println("The default values of byte array is: ");
            for(int i=0;i<arr_byte.length;i++){
                  System.out.print(arr_byte[i]+" ");
            }


            System.out.print("\n\n");




      }
}

OUTPUT:


Copy Constructor in Java


Unlike C++, Java doesn't support default copy constructor, But you can write your own copy constructor in Java. Java program to explain the copy constructor is given below.

Example:

import java.util.*;
import java.lang.*;

class employee{
 
      private int salary;
      private String post;

      public employee(int salary,String post){

         this.salary=salary;
         this.post=post;

      }

      public employee(employee emp){
         this.salary=emp.salary;
         this.post=emp.post;
      }

      
      public String print(){

          return salary+" "+post;
      }

}
public class copyconstructor{

   public static void main(String args[]){

       Scanner in=new Scanner(System.in);
       System.out.println("\nEnter the salary of the employee: \n");
       int salary=in.nextInt();
       System.out.println("\nEnter the post of the employee: \n");
       String post=in.next();

       employee emp1=new employee(salary,post);

       //calling the copy constructor
       employee emp2=new employee(emp1);

       System.out.println("\n\nDetails of the employee 1: "+emp1.print());
       System.out.println("\n\nDetails of the employee 2: "+emp2.print());
   }
}


Output:


Tuesday, 9 January 2018

Different ways to Print Exception Messages | Java

There are three methods available in Java to print the exception messages. Those three methods are the member of Throwable class. These three methods can be used to print the exception message for any exception object because Throwable class is the base class for all exceptions.


Method 1:


java.lang.Throwable.printStackTrace(): This method is used to get the exception name (e.g. java.lang.Arithmetic Exception), description(e.g  / by zero) separated by colon as well as stack trace (where in the code exception has occurred) on new line.

Example:

import java.lang.*;
import java.util.*;

class exception_message{
 

    public static void main(String args[]){

             Scanner in=new Scanner(System.in);
             int a,b;

             System.out.println("\nEnter the value of a: \n");
             a=in.nextInt();

             System.out.println("\nEnter the value of b:\n");
             b=in.nextInt();

             try{
                    int c=a/b;
             }
             catch(Exception e){

                       System.out.print("\n");
                       //It will print the line number and call stack
                    e.printStackTrace();

                       //This function will print the thrown exception
                    System.out.print("\n"+e);
             }



    }
}

Output:



Method 2:

java.lang.Throwable.toString(): This method returns the "exception name + description"  as a string separated by colon. Unlike printStackTrace() this method to not return the stack trace of the exception occurred in the code.

Example:

import java.lang.*;
import java.util.*;

class exception_message{
 

    public static void main(String args[]){

             Scanner in=new Scanner(System.in);
             int a,b;

             System.out.println("\nEnter the value of a: \n");
             a=in.nextInt();

             System.out.println("\nEnter the value of b:\n");
             b=in.nextInt();

             try{
                    int c=a/b;
             }
             catch(Exception e){
                       
                        System.out.print("\n"+e.toString());
             }



    }
}


Output:



Method 3:

java.lang.Throwable.getMessage(): This method is used to get only description of the exception.

Example:

import java.lang.*;
import java.util.*;

class exception_message{
 

    public static void main(String args[]){

             Scanner in=new Scanner(System.in);
             int a,b;

             System.out.println("\nEnter the value of a: \n");
             a=in.nextInt();

             System.out.println("\nEnter the value of b:\n");
             b=in.nextInt();

             try{
                    int c=a/b;
             }
             catch(Exception e){
                       
                        System.out.print("\n"+e.getMessage());
             }



    }
}

Output:



Saturday, 6 January 2018

String in Switch Case in Java

String literal/constant can be used to control the switch statement in Java, which is not possible in  C/C++. Using a string-based switch is an improvement over using the equivalent sequence of  if/else statements. String literal/constant was included in JDK7.

Important Points:

1. Expensive Operation: Switching string can be more expensive in term of execution rather than switching on primitive data types. Therefore, it is best to switch on strings only in cases in which data is controlled in string form.

2. String should not be NULL:  Remember that expression in any switch statement should not be NULL to avoid NullPointerException from being thrown at run-time.

3. Case Sensitive Comparison: case comparison is case sensitive.

4. Better than If-else: The byte code which java compiler generates from using switch statement that use String object is more efficient than if-else statements.

PROGRAM:

import java.util.Scanner;

public class stringSwitch{

        public static void main(String args[]){

            Scanner in=new Scanner(System.in);

            String str;
            System.out.print("\n\nEnter any of the following: \n\n");
            System.out.print("Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n\n\n");



            str=in.next();

            switch(str){

                case "Monday": System.out.println("You have entered Monday");
                               break;
                case "Tuesday": System.out.println("You have entered Tuesday");
                               break;
                case "Wednesday": System.out.println("You have entered Wednesday");
                               break;
                case "Thursday": System.out.println("You have entered Thursday");
                               break;
                case "Friday": System.out.println("You have entered Friday");
                               break;
                case "Saturday": System.out.println("You have entered Saturday");
                               break;
                case "Sunday": System.out.println("You have entered Sunday");
                               break;
                default:       System.out.println("You have selected wrong choice");

            }
        }
}


OUTPUT:


Friday, 5 January 2018

Example of For-each loop in Java

For-each loop is also array traversing technique like the do-while loop, for loop, while loop. It is commonly used to iterate over an array of Collections such as ArrayList and the LinkedList.

Syntax:

for (type variable : array_name) 
{ 
    statements using the variable;
}

This loop starts with the keyword for as a normal for loop start. But instead of declaring and initializing the counter variable of loop, we declare a variable whose data type is same as the base data type of array and then a semi colon which is followed by the array name. In the statements inside the for loop you can use directly loop variable you created rather than using an indexed array element.

For-each has some limitations due to which it is not best to use during the normal array traversal, which are given below:

Limitations:

1. For-each loop are not appropriate when you want to modify the array.
    Example: num=num*2; will change the num variable instead of modifying it in array.
2. This loop do not track the index of the array. Therefore, array index can not be obtained.
3. It iterates only in forward direction.
4. For-each loop is unable to process tow decision making statements at once such as checking if two numbers are equal or not.


PROGRAM:

import java.util.Scanner;

public class for_each{

        public static void main(String args[]){

               int[] runs_scored={59,90,45,356};

               System.out.print("\nTraversal using for-each loop: \n");
               for(int variable: runs_scored){

                     
                     variable++;     //update the variable
                     System.out.println(variable);
               }

                System.out.print("\nTraversal using normal for loop: \n");

                for(int i=0;i<runs_scored.length;i++){

                       //You can see in output that array is not modified
                       System.out.println(runs_scored[i]);
                }
        }
}

OUTPUT:



ListIterator in Java

This Iterator is only applicable for the List collection implemented classes like arraylist, linkedlist etc. This Iterator has bi-directional functionality. We use ListIterator to enumerate the elements of the List. ListIterator is bi-directional, whether Universal Iterator can be used only in the forward direction.

Syntax:


ListIterator ltr = l.listIterator();
ListIterator Object can be called using listIterator() method present in the List interface. Basically, this ListIterator extends Iterator interface with the addition of six more methods which are given below.

1. public boolean hasNext(): This method is same as in the universal Iterator. it returns True if there are more element present in the List collection object.

2. public Object next(): It is also same as the next() method in the Universal Iterator. it returns the next element.

3. public int nextIndex(): This method returns the index of the next element present in the List collection object.

4. public void hasPrevious(): It returns true if there are more elements present while traversing backwards.

5. public Object previous(): This method will be return the previous element. But if ListIterator is at the beginning then it will return -1.

6. public int previousIndex(): This method will return the index of the previous element.

7. public void remove(): It is also same as in the universal Iterator. This method is used  to remove the element from the List collection object. This method can be used only next to the previous() or next() method.

8. public void set(Object obj): This method is used to replace the last element returned by the next() or previous() method.

9. public void add(Object obj): It inserts the specified element into the list at position before the element that would be returned by the next() method.

public void set(Object obj) can throw the following exceptions:

1. IllegalArgumentException: If specified element is prevented from being added to the list.
2. IllegalStateException: If set() method is being used without the use or next() or previous() method or remove or add have been called prior calling set() method.
3. UnsupportedOperationException: If the set operation is not supported by the ListIterator.

public void add(Object obj) can throw the following exception:
1. UnsupportedOperationException: If the add operation is not supported.
2. IllegalStateException: same as the given above.
3. IllegalArgumentException: same as the given above.


PROGRAM:


import java.util.ListIterator;
import java.util.ArrayList;
import java.util.Scanner;


public class ListIteratorExample{
   
   public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        ArrayList<Integer> li=new ArrayList<Integer>();

        for(int i=0;i<6;i++){
              li.add(i);   
        }

        ListIterator<Integer> it= li.listIterator();

        while(it.hasNext()){

               int element=(Integer)it.next();
               System.out.println(element);

               if(element%2==0){

                     it.remove();
               }
        }

           System.out.print("\nAfter remove operation: \n");

        it=li.listIterator();
        while(it.hasNext()){

              int element=(Integer)it.next();
              if(element==1){
                  element++;
                    it.set(element);
                    it.add(element);

              }
              System.out.println(element);

        }
   }
}

OUTPUT:



Read More:
Enumeration Iterator in Java
Read More:  Universal Iterator in Java

Universal Iterator in Java

This Iterator can be applied to any collection object. Thus, it is known as Universal Iterator. Universal Iterator can perform both read and remove operations It is an improved version of the Enumeration Iterator with the added functionality of the remove operations.

Universal Iterator must be used to enumerate the elements of the all collection framework implemented interfaces such as Linked Lists, Queue, Stack, Dequeue as well as in implemented class of Map interface. Universal Iterator is the only cursor available for the entire collection framework.

Iterator itr = c.iterator();

Here, c refers to the collection object.

Iterator Interface has three defined methods:

1. public boolean hasNext(): This method returns true if there are more elements in the collection object and it will throw NoSuchElementException if there is no more element present.

2. public Object next(): It will return the next element of the collection object.

3. public void remove(): It will remove the next element of the object, It can be called only once per call to the next() method. It will throw IllegalStateException if the next() method has not been called yet or if remove() is already called to last next() method. It will also throw the UnsupportedOperationException if the remove method is not supported by the collection object.

Limitations of the Universal Iterator:
1. Only forward iteration is possible.
2. Replacement and addition of new element is not supported.

PROGRAM:


import java.util.*;

public class UniversalIterator{

    public static void main(String args[]){

           Scanner in=new Scanner(System.in);

              List<Integer> list=new ArrayList<Integer>();

              for(int i=0;i<10;i++){
                   list.add(i);
              }

              Iterator it=list.iterator();

              while(it.hasNext()){

                    int element=(Integer)it.next();
                    System.out.println(element);

                    if(element==5){
                       it.remove();
                    }
              }

              System.out.print("\n\nAfter performing removing operation:\n");

              it=list.iterator();
              while(it.hasNext()){

                    int element=(Integer)it.next();
                    System.out.println(element);
              }
    }
}


OUTPUT:




Thursday, 4 January 2018

Enumeration Iterator in Java

Enumeration Iterator is the first iterator present from JDK 1.0 and the rest of the iterators are included after the JDK 1.0 with additional functionalities. Enumeration Iterator is an interface used to get elements of legacy containers such as Hashtable and Vector.

Syntax:


Enumeration enumerate = vect.elements();
Here vect is the vector class object and enumerate is the type of Enumeration interface which refers to collection class object.

Methods available in Enumeration interface:

There are two methods present in the Enumeration Interface:
1. public boolean hasMoreElements(): This method is used to check if this enumeration has more elements.
2. public Object nextElement(): This method is used to retrieve the next element present in the collection.


If no more elements are present in the container then it will throw the NoSuchElementException.

Limitations of Enumeration Iterator:
1. Enumeration is only for legacy containers (Hashtable and Vector).
2. Enumeration iterator can't perform remove operations.
3. Only forward iteration is possible

EXAMPLE:

import java.util.*;

public class EnumerationIterator{

    public static void main(String args[]){

           Scanner in=new Scanner(System.in);

           Vector<String> vect=new Vector<String>();

           vect.addElement("Guru");
           vect.addElement("Tegh");
           vect.addElement("Bahadur");
           vect.addElement("Institute");
           vect.addElement("Of");
           vect.addElement("Technology");

           Enumeration enumerate=vect.elements();

           System.out.print("\n");

           while(enumerate.hasMoreElements()){

                 String s=(String)enumerate.nextElement();
                 System.out.println(s);
           }

           System.out.print("\n");
    }
}


OUTPUT:




strpos() and stripos() function | PHP

strpos() helps us to find out the first occurrence of a substring in a string. This function returns an integer value of the position of the first occurrence of the string. Both the strpos() and stripos() function servers the same purpose. The main difference between both function is case-sensitivity.

strpos() is case-sensitive but stripos() is not case-sensitive.


strpos(original_str, search_str, start_pos)

Parameters Used:
Two parameters are mandatory for the both functions whether third parameter is optional. 

Parameter 1: This parameter refers to the original string. This parameter is mandatory.
Parameter 2: This parameter refers to the substring, occurrence of which we have to find. This parameter is also mandatory.
Parameter 3: Refers to the position of the string from where you want to search the substring. This string is optional.

Example of strpos():

<?php


function use_of_strpos($original_string,$sub_string){
     
      $position=strpos($original_string,$sub_string);
      return $position;
     
}

//Driver code

$original_string="Guru Tegh Bahadur Institue of technology";
$sub_string="Bahadur";

$result=use_of_strpos($original_string,$sub_string);
if($result){
     
     echo nl2br("\r\n");
     echo ("Substring is present at position: ").$result;
     echo nl2br("\r\n");
}
else{
  
     echo nl2br("\r\n");
     echo nl2br("\r\nSubstring is not present in the original string\r\n");
}

$sub_string="bahadur";
$result=use_of_strpos($original_string,$sub_string);
if($result){
     
     echo nl2br("\r\n");
     echo ("Substring is present at position: ").$result;
     echo nl2br("\r\n");
}
else{
  
     echo nl2br("\r\n");
     echo nl2br("\r\nSubstring is not present in the original string\r\n");
}



?>


OUTPUT:



Example of stripos():

<?php

function use_of_stripos($original_string,$sub_string){
     
      $position=stripos($original_string,$sub_string);
      return $position;
     
}

//Driver code

$original_string="Guru Tegh Bahadur Institue of technology";
$sub_string="bahadur";

$result=use_of_stripos($original_string,$sub_string);
if($result){
     
     echo nl2br("\r\n");
     echo ("Substring is present at position: ").$result;
     echo nl2br("\r\n");
}
else{
  
     echo nl2br("\r\n");
     echo nl2br("\r\nSubstring is not present in the original string\r\n");
}


?>


OUTPUT:




Check If a number is prime or not | PHP

We will discuss a solution here with time complexity O(sqrt(n)) where n is the number which we have to check whether it is prime or not.  In this example, instead of check till n we will check till sqrt(n) because a larger factor of n will be a multiple of smaller factor which is already checked.
Therefore, we will check from (2,sqrt(n)). PHP program along with output is given below.




PROGRAM

<?php


function check_prime($number){
     
    if($number==1)
          {
            
            return 0;
    }
    
  for($i=2;$i<=sqrt($number);$i++){
         
      if($number%$i==0)
              return 0;
  }
  return 1;
     
}

//Driver code
$array=array(33,45,19,67,11);

for($i=0;$i<5;$i++){
    
  if(check_prime($array[$i])){
        echo $array[$i]." is a prime number";
       
  }
  else{
        echo $array[$i]." is not a prime number";
       
  }
 
}


?>


OUTPUT:




array_sum() function | PHP

The array_sum() function is an inbuilt function in PHP. This function is used to calculate the sum of the elements of an array.

Example:
array_sum($array)

$array : An array whose sum of values to be found.

This function takes an array as parameter and return the sum of the elements of the array.

PROGRAM:

<?php


$array1=array(23,45,66,54,67,345);
echo nl2br("rn The elements of the array is given below: rn rn");
print_r($array1);

$sum=array_sum($array1);

echo nl2br("rn rn The sum of the elements of arrays is: rn rn");
echo $sum;

?>


OUTPUT:



array_combine() Function | PHP

This inbuilt function of PHP  is used to combine two array. array_combine() function combine two arrays and create a new array by using one array for key and another array for value. It means all the elements of first array will be keys and all the elements of the second array will be value of those respective keys. PHP program to explain the use of array_combine() function is given below.

EXAMPLE:

Input: $array1=("Sachin","Rahane","Virat");
            $array2=("80","70","90");

Output:  Array ( [Sachin]=>80 [Rahane]=>70 ["Virat"]=>90)

Syntax:
array_combine ($keys, $values)

This function takes two parameters and both the parameters are mandatory and this function only accepts arrays.

1. Parameter 1: The first parameter will be an array of keys. If values passed are illegal then it will be converted to a string.
2. Parameter 2: The second parameter will be an array of values for the keys passed in the parameter 1.

PROGRAM:


<?php


function combine_two_arrays($array1,$array2){
  
       return(array_combine($array1,$array2));
  
}


//Driver code of the program

$array1=array("Sachin","Rahane","Virat");


echo nl2br("The elements of first array are given below: \r\n");
print_r($array1);

$array2=array(50,90,80);

echo nl2br("\r\n \r\n The elements of second array are given below: \r\n");
print_r($array2);

echo nl2br("\r\n \r\n The comined array is given below: \r\n");
print_r(combine_two_arrays($array1,$array2));

?>

OUTPUT:




Wednesday, 3 January 2018

PHP program to calculate frequency | array_count_values() function

array_count_values function is an inbuilt function of PHP. This function is use to calculate the frequency of the elements of array. This function takes a single parameter i.e an array. This function returns an associative array with key value pairs, where key are the elements of array and value is their respective frequency in the array.

array_count_values($array)

PHP program to calculate the frequency of an array elements using array_count_values is given below.

PROGRAM

<?php

//function to count the frequency of the array
function Counting_frequency($array){
    return(array_count_values($array));
}
 
// Driver Code
$array = array(1,1,1,12,23,23,3,12);
print_r(Counting_frequency($array));
$new_array=array("plexinfo","is","among",
                 "the","top","websites","of","the","world");

echo nl2br("\r\n");
echo nl2br("\r\n");

print_r(Counting_frequency($new_array));

?>


OUTPUT:



C++ Program for Three Way Partitioning - O(n) solution

Three way partitioning refers to divide an array in three parts such as:
1. All the elements smaller than given lower_value should appear first.
2. All the elements between given lower_value and higher_value should come next.
3. All the elements greater than given higher_value should appear in the end.

C++ Program for the three way partitioning of the array is given below. The time and space complexity of the given solution is O(n) and O(1) respectively.

PROGRAM:



#include <bits/stdc++.h>
using namespace std;


void threeWayPartition(vector<int> &A,int lowVal,int highVal)
{
     //Your code here
     
     int start=0,end=A.size()-1;
     for(int i=0;i<=end;){
         
            if(A[i]<lowVal){
                  
                  int temp=A[start];
                  A[start]=A[i];
                  A[i]=temp;
                  i++;
                  start++;
            }
            
            else if(A[i]>highVal){
                  
                  int temp=A[end];
                  A[end]=A[i];
                  A[i]=temp;
                  end--;
            }
            else
            {
                i++;
            }
            
           
     }
     
}

int main(){
    
    
      int n;

      cout<<"\nEnter the total number of elements: \n";
      cin>>n;

      cout<<"\nEnter the elements:\n";
      int num;

      std::vector<int> A;

      for(int i=0;i<n;i++){
           cin>>num;
           A.push_back(num);
      }
     
      int lowVal,highVal;

      cout<<"\nEnter the lowVal and highVal respectively: ";
      cin>>lowVal>>highVal;

      cout<<"\n";

      threeWayPartition(A,lowVal,highVal);
      cout<<"\nThe container after three way partitioned: \n";
      for(int i=0;i<A.size();i++) {
           cout<<A[i]<<" ";
      }
      cout<<"\n";
      return 0;
}


OUTPUT:




Tuesday, 2 January 2018

C++ Program to Find Longest Increasing Subsequence

LIS (Longest Increasing Subsequence) problem is used to find the longest subsequence of array which is in sorted order. C++ Program for finding the longest increasing subsequence is given below.

Example:

Let A[]= {10, 22, 9, 33, 21, 50, 41, 60, 80} 

Length of Longest Increase subsequence is 6 and LIS is {10, 22, 33, 50, 60, 80}.

PROGRAM:


#include <bits/stdc++.h>
using namespace std;

int calculate(const vector<int> &A)
{
      if(A.size()==0) return 0;
      
      int n=A.size();
      
      int list[n];
      for(int i=0;i<n;i++) list[i]=1;
      for(int i=1;i<n;i++){
            for(int j=0;j<i;j++){
                  if(A[j]<A[i]){
                        list[i]=max(list[i],list[j]+1);
                  }
            }
      }
      
      int result=0;
      for(int i=0;i<n;i++){
           if(result<list[i]){
                result=list[i];
           }
      }
      return result;

}
int main(){
    
    
      int n;

      cout<<"\nEnter the total number of elements: \n";
      cin>>n;

      cout<<"\nEnter the elements of array:\n";
      int num;

      std::vector<int> A;

      for(int i=0;i<n;i++){
           cin>>num;
           A.push_back(num);
      }
     
      int result=calculate(A);
      cout<<"\nThe length of longest increasing subsequence is: "<<result<<"\n";
      return 0;
}

OUTPUT: