Difference – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 04 Jul 2023 17:39:51 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Difference – Programmerbay https://programmerbay.com 32 32 Difference between Comparable and Comperator in Java in Tabular Form https://programmerbay.com/difference-between-comparable-and-comperator-in-java-in-tabular-form/ https://programmerbay.com/difference-between-comparable-and-comperator-in-java-in-tabular-form/#respond Tue, 04 Jul 2023 17:39:51 +0000 https://programmerbay.com/?p=9279 In Java, there are two interfaces that provides a way to sort and compare objects, namely Comparable and Comparator. Both interfaces play significant roles in sorting and ordering elements, but they differ in when it comes to identify ordering of elements.

The classes that implements Comparable interface support default natural sorting, if one needs to implement a customized sorting order then Comperator comes into picture. Further, the classes which doesn’t implement Comparable interface and required a need to support for sorting, then Comparator can also be used in such case.

For user-defined classes, Comparator can be used for sorting objects based on some values as a base for determining order of elements.

Point to Remember:

1. Comparable is for default natural sorting, on other hand, Comparator is for custom sorting

2. Comparable resides in java.lang package, whereas, Comparator comes under java.util package

3. Comparable interface consists only single method, named compareTo(), while Comparator contains 2 method, named equals() and compare()
4. All wrapper classess & String implements Comparable interface, whereas, Collator or RuleBaseCollator are two classes that directly implement Comparator .

Comparable 

Comparable is an interface that empowers natural sorting of elements. A class that implements the Comparable interface defines compareTo() method, which takes class type object and returns an integer indicating the relative order of the elements.

Comparator

Comparator, on the other hand, is an interface that empowers custom sorting of elements. Unlike Comparable, which only supports natural order of elements. A  Comparator can be defined and used independently with class. It can also be passed as a parameter to a Collections.sort() method or used to sort elements stored in a collection that implements the SortedSet or SortedMap interfaces.

Difference between Comparable and Comperator in Java In Tabular Form

BasisComparableComparator
DefinitionIt defines the natural sorting order of elements in a classIt provides a way to define a custom sorting order for elements in a class
MethodIt provides compareTo() method that is required to implemented by a classIt provides compare() method that is required to implemented by a class
Object TypeCan only be used with objects of the same type and comparable Using Comparator, we can use non comparable objects in a class
Sorting OrderSorting order is determined by the class's implementation of the
compareTo() method
Sorting order is determined by the implementation of the compare() method in the Comparator implementation
Collections.sort()Collections.sort(list) can be used to sort a collection of objects that implement ComparableCollections.sort(list,comparatorObj) can be used to sort a collection of objects by passing a Comparator object as a parameter
OrderingOnly one ordering can be defined for a classMultiple orderings can be defined for a class by creating multiple Comparator objects
PackageIt resides in java.lang packageIt resides in java.util package

]]>
https://programmerbay.com/difference-between-comparable-and-comperator-in-java-in-tabular-form/feed/ 0
Difference Between Collection And Collections in Java With Tabular Form https://programmerbay.com/difference-between-collection-and-collections-in-java-with-tabular-form/ https://programmerbay.com/difference-between-collection-and-collections-in-java-with-tabular-form/#respond Tue, 04 Jul 2023 13:08:37 +0000 https://programmerbay.com/?p=9327 Both Collection and Collections reside in java.util.package. The main difference between them is, Collection is an interface for specifying methods that needs to be implemented by all the collection class whereas Collections is a class that offers utility methods to work with collections.

Difference between Collection and Collections in Java

BasisCollection Collections
DefinitionIn Collection hierarchy, it is the root interface that represents a group of objects, termed as elementsIt is a class that provides utility methods which operates on collection objects.
RepresentsClassInterface
PurposeIt specifies group of objects as single entity and supports various method that can be applied on collection objects
It specifies predefined utility methods which are used for operations i.e searching, sorting for collection objects
MethodsIt consists static, abstract and default methodsIt consists only static methods

Collection

The collection is an interface that represents a group of individual objects as a single entity. It is the root interface of the collection framework that specifies several methods which are applied to all collections.

The collection interface is inherited by List, Set and Queue interfaces and its implementing classes are ranging from ArrayList to TreeSet.

Syntax :

public interface Collection<T> extends Iterable<T>

contains(), add(), isEmpty(), remove() and clear() are some of the important methods

Collections

Collections is a utility class that consists of static methods which operate on collections. It provides handy methods that can be used directly on collection objects such as searching and sorting purposes.

Syntax:

public class Collections extends Object

Java program to demonstrate the working of Collections in Java

Program:

public class CollectionExample {

    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Sandeep");   // add() method is a method of collection interface
        names.add("Vinay");
        names.add("Kui");
        names.add("Sachin");
        System.out.println("Before sorting :: "+ names);
        Collections.sort(names);  // sort() would sort  a list in natural order
        System.out.println("After sorting :: "+ names);

    }
}

Output:

Before sorting :: [Sandeep, Vinay, Kui, Sachin]
After sorting :: [Kui, Sachin, Sandeep, Vinay]

 

]]>
https://programmerbay.com/difference-between-collection-and-collections-in-java-with-tabular-form/feed/ 0
Distinguish between single and multiple fault assumption https://programmerbay.com/distinguish-between-single-and-multiple-fault-assumption/ https://programmerbay.com/distinguish-between-single-and-multiple-fault-assumption/#respond Wed, 14 Sep 2022 05:48:12 +0000 https://programmerbay.com/?p=5525 Here’s the difference between single and multiple fault assumption.

 

Single fault assumptionmultiple fault assumption
Single fault assumption describes that two or more simultaneous faults are hardly responsible for the failureMultiple fault assumption defines two or more simultaneous faults can be the reason for failure
In this, only single variable is set to its extreme value and letting others to their nominal valuesIn this, more than one variable is assigned with extreme values
For example, Normal Boundary Value testingFor example, Worst-Case Boundary Value Testing

What is Boundary Value testing:

It is a functional testing technique. In this, we choose boundary values or conditions where the chances of getting errors are high, These boundary values are the input values which can be:

  • minimum ( lying on the boundary)
  • maximum (lying on the boundary)
  • Just below from maximum ( below the boundary)
  • Just above to minimum (above the boundary)
  • At nominal

]]>
https://programmerbay.com/distinguish-between-single-and-multiple-fault-assumption/feed/ 0
Difference Between Delete and free() in C++ https://programmerbay.com/free-vs-delete-in-c/ https://programmerbay.com/free-vs-delete-in-c/#respond Sun, 04 Sep 2022 07:50:46 +0000 https://programmerbay.com/?p=7848 In this article, we’ll be discussing the meaning of the delete operator and free() function in C++ and the differences between them.

Both delete and free() are used for releasing the memory allocated at runtime. The main difference between them is, the delete operator deallocates memory for objects which are dynamically allocated through new keyword, whereas, the free() function deallocates memory that is dynamically allocated through malloc, calloc or realloc function.

Difference Between Delete and free() in C++

Basisfreedelete
Refers to A Library functionAn operator
Ideal forDeallocating memory occupied using malloc,calloc and realloc functionReleasing memory which is allocated using new keyword
OverridingNot PossiblePossible
Execution speedslowfast

free() function in C++ :

The main job of the free function is to release the memory which is allocated at the runtime. The free() function can be used in both C as well as C++ programming language.

It releases dynamically allocated memory created by calloc,realloc and calloc functions and provides extra reusable heap memory that can be used later. It takes pointer whose memory to be released as an argument.

void free(void *ptr)

delete operator in C++

The delete operator also has the same job like free function, that is, to release the memory which is allotted at the runtime. The delete operator is most commonly used in C++ programming.

It can defined as an operator which is used to release the memory allocated by new keyword such as objects and arrays. In C++, when delete is used with an object, it first calls the destructor of that particular object and then after deallocates the memory occupied by it. However, in the case of free(), no destructor is called of the respective object.

delete obj;

Key Differences between Delete and free() in C++

  1. The free function is basically a library function which resides in the stdlib.h header file, while delete, on the other hand, is an operator which is most commonly used in C++ programming.
  2. In the free() function, there is no call made to the destructor after the release of the runtime allocated memory. On the other hand, in case of delete operator, there is a call made to the destructor before the release of the allocated memory.
  3. In case of the free() function, as we all know that this is a function and thus it requires to get its declaration from the header file which makes it slower. In case of delete operator, as it is an operator and we all know that an operator is faster paced than a function.

 

]]>
https://programmerbay.com/free-vs-delete-in-c/feed/ 0
Difference Between Entry Controlled Loop and Exit Controlled Loop https://programmerbay.com/difference-between-entry-controlled-loop-and-exit-controlled-loop/ https://programmerbay.com/difference-between-entry-controlled-loop-and-exit-controlled-loop/#respond Sun, 24 Jul 2022 08:47:42 +0000 https://www.programmerbay.com/?p=2229 In this article, we’ll be discussing the meaning of loop and also see the difference between Entry Controlled Loop and Exit Controlled Loop with program example.

Entry vs exit controlled loop

What is a Loop?

A loop empowers repetitive execution of a certain piece of code until a given condition turns out to be false.

In simple terms, it enables us to run a particular sequence of statements repeatedly based on a certain condition.

Generally a looping process involves:

  • Control variable initialization
  • Condition Evaluation
  • Loop body execution
  • Control Variable Updation

There are mainly three types of loops:

1) While Loop : loops through a piece of code as long as a specified expression is evaluated as true
2) Do While Loop : similar to while loop, except Do-While loop is guaranteed to execute at least one time
3) For Loop : executes loop body for specific number of times ( allows control over number of iterations)

In programming, these are considered as controlled statements that can regulate the flow of the program execution.

They use a conditional expression in order to decide to what extent a particular block should be repeated.

Every loop consists of two sections, loop body and control statement.

A control statement is a condition that dictates how long a loop would be iterated and the loop body is a block that contains the intended iterative statements.

In case of While Loop :

while(condition)    // Control Statement
  {
   // Loop Body
  }

In case of Do-While Loop :

do{
   // Loop Body      
  }while(condition);   // Control Statement

In case of For Loop :

for(controlVariableInitialization ;condition; increment/decrement)   // Control Statement
    {
     // Loop Body
    }

 

Based on the position of these two sections, loop execution can be handled in two ways that are at the entry-level and exit level.

So, loops can be categorized into two types:

Entry controlled loop: When a condition is evaluated at the beginning of the loop.
Exit controlled loop: When a condition is evaluated at the end of the loop.

Also Read: Difference between While and Do-While Loop

Entry Controlled Loop

An entry control loop checks condition at entry level (at beginning ), that’s why it is termed as entry control loop.

It is a type of loop in which the condition is checked first and then after the loop body executed. For loop and While loop fall in this category.

If the test condition is true, the loop body would be executed otherwise, the loop would be terminated.

 

Entry control loop flow chart

 

Execution Flow of Entry Control Loop

  1. The control variable is initialized first and acts as a base for comparison
  2. This variable is then evaluated with a conditional statement.
  3. If the condition is evaluated as false, the loop would be terminated, otherwise
  4. The loop body would be executed and go to the next iteration, where the variable would get updated with new incremented/ decremented value
  5. Repeat 2nd to 4th steps until the condition is said to be false.

Program to show the working of entry controlled loop:

#include<stdio.h>
void main()
{
int i=10;
while(i<10)
{
printf("I will not be executed as it is entry controlled loop");
i++;
}
getch();
}

Explanation:

In the above code, No output would be displayed as the condition is false. We used ‘i’ as a counter variable and assigned it 10.  Loop condition ‘i<10 ‘got evaluated as false . As a result, the compiler transferred the control to the next statement after the loop.

Exit Controlled Loop

An exit control loop checks condition at exit level (in the end ), that’s why it is termed as exit control loop. Oppose to Entry controlled loop, it is a loop in which condition is checked after the execution of the loop body. Do-While loop is the example.
The loop body would be executed at least once, no matter if the test condition is true or false.

Exit control loop flow chart

 

Execution Flow of Exit Control Loop

  1. The control variable is initialized first and acts as a base for comparison
  2. Then, the loop body is executed and the variable would get also updated with new incremented/ decremented value
  3. This variable is then evaluated with a conditional statement.
  4. If the condition is evaluated as false, the loop would be terminated, otherwise
  5. It repeats, 2nd to 4th steps until the condition is said to be false.

Program to show the working of exit controlled loop:

#include<stdio.h>
void main()
{
  int i=10;
  do
  {
  printf("I will be executed at once as it is exit controlled loop");
  i++;
  }while(i<10);
  getch();
}

Explanation:

In the above code, print statement would be executed at least once even though condition is false.

We used ‘i’ as counter variable and assigned it 10. In this, loop body got executed first as a result a message got printed on screen. After that, condition was checked which evaluated as false, this terminated the loop.

Difference between entry controlled loop and exit controlled loop in Tabular form ?

BasisENTRY CONTROLLED LOOPEXIT CONTROLLED LOOP
Execution FlowA loop in which the given condition is checked first, before entering the loop bodyA loop in which the loop body is executed first and then after the given condition is checked
Condition EvaluationThe loop body would be executed, only if the given condition is trueThe loop body would be executed at least once, even if the given condition is evaluated as false
ExampleFor Loop and While Loop are examples of this type of loopDo While Loop is an example of exit controlled loop
UseIt is used when condition evaluation is mandatory before executing loop bodyIt is used when one requires to iterate through loop body at least once before condition evaluation

Key Differences

  1. Exit control loop always executes at least once, regardless of condition. But, the entry control loop only executes if and only if the condition is evaluated as true.
  2. In this type of loop, body execution comes first, whereas in, entry control loop condition expression always comes first.
  3. Do-While falls under the exit control loop, whereas For loop and While loop falls under entry control loop
]]>
https://programmerbay.com/difference-between-entry-controlled-loop-and-exit-controlled-loop/feed/ 0
Difference Between Primary Key and Secondary Key https://programmerbay.com/difference-between-primary-key-and-secondary-key/ https://programmerbay.com/difference-between-primary-key-and-secondary-key/#respond Tue, 19 Jul 2022 06:25:00 +0000 https://www.programmerbay.com/difference-between-primary-key-and-secondary-key/

PRIMARY KEY

A primary key is a field that identifies each record in a database table admitting that the primary key must contain its UNIQUE values.

The primary key column cannot have NULL values.

A table can have only one primary key constraint which may consist of single and multiple fields.
When multiple keys are used in a single primary key, these fields are called a composite key.

When we specify the primary key constraint for a table, the database engine executes the data uniqueness by automatically creating an index. this index permits fast access to data when the primary key is used.

Primary Key can be specified either when the table is created using CREATE table or by changing the existing table structure using ALTER.

CREATE TABLE Customer
(SID integer,
Last_Name Varchar(20)
First_Name Varchar(20)
PRIMARY KEY (SID)
ALTER TABLE Customer ADD PRIMARY KEY (SID)

SECONDARY KEY

A secondary key shows the secondary value that is unique for each record. It can be used to identify the record and it is usually indexed. It is also termed as Alternate key.

A table may have a primary key that is system generated and a secondary key that comes from the sources and other processes. that is the secondary key. it is made on a field to be indexed for faster searches. A table can have more than one secondary key.

Difference between Primary key and Secondary key ?

The main difference between primary key and secondary key is, a key that is selected for identifying each tuple in a table uniquely is termed as primary key, whereas,  a key that is not selected for identifying rows, even though it is capable of determining tuples uniquely in the table are termed as the secondary key.

BasisPrimary keySecondary key / Alternate key
DefinitionA key that is selected for identifying each record in a database table uniquelyA key that is not selected as primary key but capable of identifying each records uniquely
NULL ValuesNot AllowedAllowed
Number of KeysA table can have only one primary keyA table can have any number of secondary or alternate keys

 

For Example ,

Primary vs Secondary key

In the above table, we can identify candidate keys which are :

user_id, account_number and email 

Now from them, we can select only one primary key, in this case, we selected user_id as the primary key. Other remaining keys such as account_number and email as Secondary or Alternate key.

Summary :

A Candidate Key can be defined as an individual column or combination of columns that are used to uniquely identify rows in a table. Both the Primary Key and Secondary key are Candidate Keys. They are capable of determining each and every tuple.

Difference between primary key and secondary key

Frequently Asked Questions:

What is an alternate key ?

An alternate key can be defined as the candidate key that satisfies all the requirements to become a primary key. It’s also termed as secondary key

Is alternate key same as secondary key?

Yes, both are used interchangeably.

 

]]>
https://programmerbay.com/difference-between-primary-key-and-secondary-key/feed/ 0
Difference Between Call By Value and Call by Reference in Tabular Form https://programmerbay.com/difference-between-call-by-value-and-call-by-reference-in-tabular-form/ https://programmerbay.com/difference-between-call-by-value-and-call-by-reference-in-tabular-form/#respond Sun, 10 Jul 2022 17:45:13 +0000 https://www.programmerbay.com/?p=4216 In programming, a function is a set of statements that carries out a specific task. It increases the code readability and reusability.
In order to use a function, one requires to invoke it by using its name and parameters.
A function can be called by using two ways :
  1. Call by reference
  2. Call by value

Call by value :  Where a copy of the original value is created and passed in the formal parameters of a method. In this, if any changes are made to formal arguments within the local method would not be reflected in the original data.

Call by Value

Call by reference :  Where a copy of the address is passed to formal argument which points to the address of the original value .

As a result, if any change is made through that copied reference variable would directly reflect on actual data.

call by reference

Difference between call by value and call by reference in Java in tabular form

CALL BY VALUECALL BY REFERENCE
In this, a value of a variable is passed as an argument to a function's formal parametersIn this, an address of a variable is passed as an argument to a function's formal parameters
A separate memory is allocated to a new variable holding copied value in the stack memoryA separate memory is allocated to a new variable pointing to the address of another variable
Changes made to the cloned value within the local function is not reflected outside the methodChanges made to reference variable within the local function is reflected outside the method
Value of a variable is passed to the argumentPointer variable that is used to store the address, is passed to the formal argument
Original value doesn't get changedOriginal value gets changed

Call by Value

In this, a copy of the actual value is generated and passed in the formal parameter of a method. Any change made in those copied value would not affect the original one because both copied and original values are stored in different location.

Original values are copied from the actual parameter to the formal parameter of a function, meaning, variables in both parameters point to different memory spaces. Therefore, if one changes the value of a variable passed to the formal parameter, then it would not be reflected outside the function.

C program to show the working of Call by Value

#include <stdio.h>

void sum (int x);

int main ()
{
  int a = 10;
  printf ("before sum function called : %d \n", a);
  sum (a);
  printf ("After sum function called : %d \n", a);
  return 0;
}

void sum (int x)
{
  x = x + 20;
  printf ("sum : %d \n", x);
}

Output:

before sum function called : 10 
sum : 30 
After sum function called : 10

Call by reference

In this, a copy of the reference variable is generated and passed in the formal parameter of a method. Any change made through that particular copied variable would affect the actual data because both copied and original reference variable are pointing to same memory location where data is located.

An address is passed from the actual parameter to the formal parameter of a function, meaning, variables in both parameters point to the same memory space. Therefore, if one changes the value of a variable passed in a formal parameter would be reflected outside the function.

#include <stdio.h>

void sum (int *x);

int main ()
{
  int a = 10;
  printf ("before sum function called : %d \n", a);
  sum (&a);
  printf ("After sum function called : %d \n", a);
  return 0;
}

void sum (int *x)
{
  (*x) = (*x) + 20;
  printf ("sum : %d \n", (*x));
}

Output:

before sum function called : 10 
sum : 30 
After sum function called : 30

Call by reference and Call by value in Java

In C++, Call by reference can be achieved using pointers that can be defined as a variable that is capable of storing an address of other variables.

Unlike C++, Java doesn’t support pointers due to security reasons. likewise, call-by-reference is not possible in Java.

Java only supports “call by value”, in the case of objects, it acts differently.

In Java, there are two types of arguments.

  1. Primitive data type : In this, a primitive datatype is passed as an argument to a method’s formal parameters
  2. Object reference type: In this, a reference type is passed as an argument to a method’s formal parameters

Object reference :

An object reference can be defined as memory location which refers to the actual object’s information i.e methods, and variables. The variable that holds it is termed an object reference variable.

In Java, a copy of an object reference is passed from the actual parameter to the formal parameter where both variables passed in the arguments are pointing to the same object. As a result, changes made on the passed variable inside the method is reflected in an actual variable.

In Java, Call by value works by copying the value of an actual parameter to the formal parameter of a method. In this, the value of an actual argument is copied to a different memory space and assigned to the formal argument of a method.

In call by value, any operation performed on the received value, which is a copy, inside a method would not impact the original value residing in the caller method. This is also termed “pass by value”.

Java program to demonstrate how call by value and call by reference works?

Program:

public class callme{int x;
callme(){

x=20;
}
void callByValue(int x)
{
x=x+10; // try to make changes
}
void callByReference( callme obj)
{
obj.x = obj.x + 10; // try to make changes
}

public static void main(String[] args) {
callme o = new callme(); // to demonstrate how call by reference works
int data=10; // to demonstrate how call by value works
System.out.println("Actual Value of 'data' variable before passing it as a parameter = "+data);
System.out.println("Actual Value of object that 'o' reference variable pointing to before passing it as a parameter = "+o.x);
o.callByValue(data); // passing permitive type
o.callByReference(o); // getting reference type

System.out.println("Actual Value of 'data' variable after changes = "+data);
System.out.println("Actual Value of object that 'o' reference variable pointing to after passing it as a parameter = "+o.x);

}

}

Output:

Actual Value of 'data' variable before passing it as a parameter = 10
Actual Value of object that 'o' reference variable pointing to before passing it as a

parameter = 20

Actual Value of 'data' variable after changes = 10
Actual Value of object that 'o' reference variable pointing to after passing it as a

parameter = 30

]]>
https://programmerbay.com/difference-between-call-by-value-and-call-by-reference-in-tabular-form/feed/ 0
Difference Between Break and Continue in Java in Tabular Form https://programmerbay.com/difference-between-break-and-continue-java/ https://programmerbay.com/difference-between-break-and-continue-java/#respond Tue, 21 Jun 2022 17:28:38 +0000 https://www.programmerbay.com/?p=3042 Both Break and Continue are jump statements in Java. These statements shift control from one part to another part of a program.

The break statement is mainly used to terminate the currently executing loop or block in which it’s encountered and move to next immediate program statement. On other hand, Continue statement only terminates the current iteration of the loop and hops to next iteration, without processing statements that come after it within the loop body. Sometimes, it requires  If – condition to avoid Java’s unreachable statement error.

 

Difference between Break and Continue statement in Java in Tabular form

BasisBREAK STATEMENTCONTINUE STATEMENT
DefinitionIt is used to terminate the execution of the loop and shift the control over very next statement after the loop. It also terminates the sequence of cases of the switch statementIt is used to terminate the execution of the current iteration and jumps to the next iteration of the loop
ControlIt transfers control to the very first statement after the loopIt transfers control to the conditional expression of the loop. In other words, it goes back to the entry point of the loop and begins next iteration
TerminationIt causes termination of the loopIt causes termination of the current iteration of the loop, without processing other statements that come after it within the loop body
Used withIt can be used with loops, switch statements and labelsIt can only be used with loops
KeywordBreak keyword is used for break statement in JavaContinue keyword is used for continue statement in Java

Break Statement

Break statement is a jump statement that terminates a loop or a case sequence of switch statement in which it’s encountered.Therefore, it breaks the flow of a program.

It can be used to achieve the following functionality :
1) Escape from currently executing loop
2) Break the frequent execution of cases in Switch Statement
3) It can be used as Go-to Statement

Break Statement
Figure : Working of Break Statement in Loop

Java program to show working of break statement in a loop 

public class BreakWithLoop
{
  public static void main (String[]args)
  {
    for (int i = 1; i < 10; i++)
      {
  if (i == 5)
    {
      System.out.
        println
        ("Break Encountered ! \n ************* Terminating the loop ! ");
      break;
    }
  System.out.println ("Executing " + i + " times. ");
      }
  }
}

Output:

Executing 1 times. 
Executing 2 times. 
Executing 3 times. 
Executing 4 times.
 Break Encountered ! ************* Terminating the loop !

 

  • When break statement occurs in a loop, it forces immediate termination of that particular executing loop in which it’s encountered
  • It skips all the remaining iteration and immediately moves control to next statement in the program
  • In case of nested loop, if it is occurred in innermost loop, then it would be responsible for terminating inner loop only
  • It is used in such situations when number of iterations are uncertain and therefore, it is companion with if statement

Java program to show working of break statement in Switch statement 

public class BreakWithSwitch
{
  public static void main (String[]args)
  {
    switch (2)
      {
      case 1:
  System.out.println ("case 1 :");
  break;
  case 2:System.out.println ("case 2 :");
  break;
  case 3:System.out.println ("case 3 :");
  break;
  default:System.out.println ("nothing matched! :");



      }
  }

Output:

case 3

When break statement triggers in a switch case, it terminates that case body in order to prevent from execution of later cases. In Switch statement, usually each and every case ends with a break statement to stop subsequent execution of cases.

Java program to show working of break statement with label 

public class BreakWithLabel
{
  public static void main (String[]args)
  {
        dog :{
            
            cat :{
                
                rat :{
                    
                    System.out.println("Rat killed !");
                    break rat;
                }
                System.out.println("Cat killed !");
                break cat;
                
            }
                System.out.println("Dog killed !");
                break dog;
        }

      }
  }

Output:

Rat killed ! 
Cat killed ! 
Dog killed !

Java uses label and break statement in order to get some sort of functionality of go-to statement. In this, label works as a target point and break statement considers the label to jump out of that particular target point.

Continue Statement

It only terminates the current iteration of the loop and starts next iteration again, without processing statements that come after it within the enclosing loop body. It is used with looping statements only.

Continue Statement
Figure : Working of Continue Statement in Loop

 

Java program to show working of continue statement in a loop 

public class ContinueWithLoop
{
  public static void main (String[]args)
  {
    for (int i = 1; i < 10; i++)
      {
  if (i <= 5)
    {
      continue;
    }
  System.out.println ("Executing " + i + " times. ");
      }
  }
}

Output:

Executing 6 times. 
Executing 7 times. 
Executing 8 times. 
Executing 9 times.

When continue statement occurs in a loop, it forces immediate termination of the current iteration and jump back to beginning of the loop for next iteration. It skips only the current iteration and immediately moves control to next iteration in the loop.

It is important to have If – condition to avoid Java’s unreachable statement error.

]]>
https://programmerbay.com/difference-between-break-and-continue-java/feed/ 0
Difference between Top-down and Bottom-up Parsing https://programmerbay.com/difference-between-top-down-and-bottom-up-parsing/ https://programmerbay.com/difference-between-top-down-and-bottom-up-parsing/#respond Thu, 20 May 2021 05:53:15 +0000 https://www.programmerbay.com/?p=4547 In this article, we’re going to understand what “Parsing” is and also the key differences between Top-down and Bottom-up parsing in detail.

Let’s start by discussing “Parsing” thoroughly:

Parsing can be defined as the process or technique of converting one type/ form of data into another type/form of data.

All this is done immediately after the lexical analysis phase of the compilation. For the record, the lexical analysis phase is the one in which the source code (containing various lines of code) is broken down into series of tokens, the comments are removed along with the white spaces.

How to explain parsing in simple terms?

In layman’s terms, parsing can be defined as the mechanism which changes the program data to another form so that it is more understandable from the machine’s point of view.

Technically speaking, Parsing can be defined as the phenomenon which changes the program data to another form so that it is more understandable from the machine point of view.

There are basically two types of Parsing methods, namely:

  • Top-down Parsing
  • Bottom-up Parsing

 

Top-down Parsing

The top-down parsing can be defined as the parsing method in which there is a parse tree generated from top to bottom. Or in other words, we can say that the parse tree is generated from root to the leaves. This method derives the leftmost string and when it so happens that the string matches the requirement, it is then terminated.

  • The top-down parsing is also called as “Predictive parsing” or “Recursive parsing”.
  • The parsing starts from the root of the derivation tree and then fills in.

 

Bottom-up Parsing

The bottom-up parsing can be defined as the inverse of the top-down parsing, which means that the parse tree is generated from bottom to top. In this method firstly, the input string is taken and then using the grammar the string is reduced.

  • The bottom-up parsing is also called as “Shift-reduce parsing”.
  • The parsing starts from the leaves and then fills in.

The differences between Top-down and Bottom-up Parsing are as follows:

  • Initiated From

When it comes to the top-down parsing then this parsing method is always initiated from the Root; whereas; when it comes to the Bottom-up parsing then this parsing method is always initiated from the Leaves.

  • Working Mechanism

In the case of the top-down parsing, it so happens that the production is dedicated to derive and find out the similarity in the string; whereas; In the case of the bottom-up parsing, it so happens that the process starts from token and then it proceeds towards the start symbol.

  • Method Uses

When it comes to the top-down parsing then this parsing method is most often used for Backtracking; whereas; when it comes to the bottom-up parsing then this parsing method is most often used for handling and managing the code.

  • Derivation Type

In the case of the top-down parsing, it so happens that this parsing method always follows the leftmost derivation; whereas; in the case of the bottom-up parsing, it so happens that this parsing method always follows the rightmost derivation.

Key Differences

Top-down ParsingBottom-up Parsing
"Root" initiation in case of Top-down parsing"Leave" initiation in case of Bottom-up
It is quite often used for "Backtracking"It is used for managing & handling code
"Leftmost derivation" is followed in Top-down parsing"Rightmost derivation" is followed in Bottom-up parsing

]]>
https://programmerbay.com/difference-between-top-down-and-bottom-up-parsing/feed/ 0
Difference between Compiler and Interpreter in Tabular Form https://programmerbay.com/difference-between-compiler-and-interpreter/ https://programmerbay.com/difference-between-compiler-and-interpreter/#respond Thu, 13 May 2021 17:05:50 +0000 https://programmerbay.com/?p=6271 A translator is used to translate a source code written in high level language to machine code, so, that computer can process and execute the converted code and provide the desired output. A compiler and interpreter are examples of such translators.

Compiler and interpreter are itself programs that are responsible for turning a source code to machine code.

Back in the days, people used to code in low level languages which could be directly processed in machine code. More or less, it was a set of instructions that was easy to process and understand by system.

A low level language is difficult to write, understand and debug. This is the reason, people start moving towards high level languages. Such as C++, Java and Python. As these languages were closer to natural language that a human can understand and easy to debug.

But the drawback was, these high level languages were not readable and understandable to computer system. Therefore, compilers and interpreter are used as code translators.

Difference between Interpreter and Compiler in Tabular form

CompilerInterpreter
It reads entire source code and translate it to machine codeIt reads, translates and executes each and every statement of a source code line by line
It produces intermediate code which can be executed afterwardsTranslation and execution of a source code take place together
It doesn't provide platform independent code. In other words, a executable produced on Window might not be run on Mac OSIt provides platform independent code
It generates an object code or executable
As it scans, translates and executes code on the fly, therefore, no intermediate code is generated
Java,Scala and C++ are some examplesJavaScript, Python and PHP are some examples
The object code can't be debuggedSince, the source code is visible. One can use and debug the source code
An object code runs faster and performs better as compared to InterpreterDue to line by line execution of a code, it serves slower code execution
Since, it is not platform independent. Therefore, it is not portableIt is portable
The source code doesn't need to be shared with others, instead an object code can be used directly on other systemsThe source code required to be shared, so that, interpreter can do its task

What is Compiler ?

compiler

A compiler reads entire source code first and translate it to machine code.

It produces an object code that can be executed later in single run.

However, it takes some time to scan, analyse and translate the provided code before producing executable.

Brief working of Compiler

compiler details

Lexer : it splits the code in tokens
Parser: It identifies grammar of the language and create a parse tree and then to syntax tree
Generator: converts the syntax tree to the desired language

What is Interpreter?

interperter

An interpreter reads a source code line by line and immediately executes it.

It doesn’t produce any executable, instead, it scans,translates and executes source code line-wise simultaneously.

In other words, it runs a code on fly. It does its work much faster, but it slows down the code execution speed and performance.

But behind the scenes, it scans a line from the source code, translate it and then execute it one by one until the interpreter scans last line of the code.

]]>
https://programmerbay.com/difference-between-compiler-and-interpreter/feed/ 0