Roman to integer java – Java program to Convert Roman Number to an Integer Number

Java program to convert Roman number to an integer number

Roman to integer java: In the previous article, we have seen Java Program to Reverse an Integer Number

In this article we will see how we can convert Roman numbers to an integer number by using Java programming language.

Java program to Convert Roman Number to an Integer Number

Approach:

  1. Create scanner class object.
  2. Take user input for the roman string.
  3. Initialize three variables result, prev and curr to 0.
  4. Scan the the string from end to start.
  5. Get the corresponding integer value from the user-defined method getValue() and check if it’s value is less than previous scanned roman character then subtract current value from the result else add it.
  6. Return the result.

Program:

import java.util.Scanner;

public class Main 
{

    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user
        System.out.print("Enter a roman number: ");
        String roman = sc.nextLine();
        // convert roman to integer
        int result = romanToInt(roman);
        // print result
        System.out.println("Integer value: " + result);

    }

    //romanToInt() user defined method to convert roman number to integer
    private static int romanToInt(String roman) 
     {
        // declare variables
        int result = 0;
        int prev = 0;
        int curr = 0;
        // convert roman to integer
        for (int i = roman.length() - 1; i >= 0; i--) 
        {
            // get current and previous character
            curr = getValue(roman.charAt(i));
            if (curr < prev) 
            {
                result -= curr;
            } 
            else 
            {
                result += curr;
            }
            prev = curr;
        }
        return result;
    }

    private static int getValue(char charAt) 
    {
        switch (charAt) 
        {
            case 'I':
            case 'i':
                return 1;
            case 'V':
            case 'v':
                return 5;
            case 'X':
            case 'x':
                return 10;
            case 'L':
            case 'l':
                return 50;
            case 'C':
            case 'c':
                return 100;
            case 'D':
            case 'd':
                return 500;
            case 'M':
            case 'm':
                return 1000;
            default:
                return 0;
        }
    }
}
Output:

Case-1
Enter a roman number: II
Integer value: 2

Case-2
Enter a roman number: XI
Integer value: 11

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs:

Ensurecapacity method in java – Java ArrayList ensureCapacity() Method with Example

Java ArrayList ensureCapacity() Method with Example

Ensurecapacity method in java: In the previous article, we have discussed about Java ArrayList lastIndexOf() Method with Example

In this article we are going to see the use of Java ArrayList ensureCapacity() method along with suitable examples.

Java ArrayList ensureCapacity() Method with Example

ensureCapacity():

This java.util.ArrayList.ensureCapacity() method is used to set the size of the ArrayList. It means the arraylist can hold minimum that specified number of elements.

The important point is after ensuring arraylist cacapcity why it holds minimum that number of elements rather it should be maximum that number of elements. As you know ArrayList is resizable in nature hence the arraylist can be dynamically resized if more elements will be added than specified capacity.

Then the question comes to mind if we can add more elements than the specified capacity then what is the need of ensureCapacity() method. Actually to avoid multiple times of resize of the arraylist in case of huge number of add() operations are performed, in this case the arraysize will be resized at once only.

Syntax:

arrayListName.ensureCapacity(int minimumCapcity)

Where,

  • arrayListName refers to the name of your ArrayList.
  • minimumCapacity refers to minimum size of ArrayList.

Let’s see different examples to understand it more clearly.

Method-1: Java ArrayList ensureCapacity() Method – Example with String Type ArrayList

Approach:

  • Create a new ArrayList of type String.
  • Set the capacity of the arrayList using ensureCapasity() method
  • Add string elements into the ArrayList using the add() method.
  • Display the ArrayList elements

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create a ArrayList of string datatype
        ArrayList<String> arr = new ArrayList<String>();
        // set the capacity of the arraylist
        arr.ensureCapacity(3);
        // Adding 3 string elements to the ArrayList as specified capacity
        arr.add("Bhubaneswar");
        arr.add("Hyderabad");
        arr.add("Kolkatta");
        
        //even we can add more elements also as it is dynamically resizable
        arr.add("Chennai");
        arr.add("Bhopal");
        
        // Prints the ArrayList elements
        System.out.println("The elements of ArrayList are: "+arr);
    }
}
Output:

The elements of ArrayList are: [Bhubaneswar, Hyderabad, Kolkatta, Chennai, Bhopal]

Method-2: Java ArrayList ensureCapacity() Method – Example with Integer Type ArrayList

Approach:

  • Create a new ArrayList of type Integer.
  • Set the capacity of the arrayList using ensureCapasity() method
  • Add integer elements into the ArrayList using the add() method.
  • Display the ArrayList elements

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {        
        // Create a ArrayList of string datatype
        ArrayList<Integer> arr = new ArrayList<Integer>();
        // set the capacity of the arraylist
        // arraylist can hold minimum 100 number of elements
        arr.ensureCapacity(100);
        // Adding some integer elements to the ArrayList
        arr.add(100);
        arr.add(101);
        arr.add(102);
        // Prints the ArrayList elements
        System.out.println("The elements of ArrayList are: "+arr);
    }
}


Output:

The elements of ArrayList are: [100, 101, 102]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs:

Pandas drop rows by condition – Python Pandas : How to Drop rows in DataFrame by conditions on column values

How to Drop rows in DataFrame by conditions on column values in Python ?

Pandas drop rows by condition: In this article we will discuss how we can delete rows in a dataframe by certain conditions on column values.

DataFrame provides a member function drop() which is used to drop specified labels from rows or columns in dataframe.

DataFrame.drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)

Let’s try with an example:

#Program :

import pandas as pd
#list of tuples
game = [('riya',37,'delhi','cat','rose'),
   ('anjali',28,'agra','dog','lily'),
   ('tia',42,'jaipur','elephant','lotus'),
   ('kapil',51,'patna','cow','tulip'),
   ('raj',30,'banglore','lion','orchid')]

#Create a dataframe object
df = pd.DataFrame(game, columns=['Name','Age','Place','Animal','Flower'], index=['a','b','c','d','e'])
print(df)
Output:
     Name  Age     Place       Animal       Flower
a    riya     37       delhi           cat             rose
b  anjali    28       agra           dog             lily
c     tia      42       jaipur     elephant        lotus
d   kapil    51      patna          cow           tulip
e     raj      30     banglore      lion          orchid

Delete rows based on condition on a column

Drop rows pandas condition: Let’s try with an example by deleting a row:

deleteRow = df[df['Place'] == 'patna'].index
df.drop(deleteRow, inplace=True)
print(df)
Output:
 Name    Age     Place      Animal       Flower
a    riya    37     delhi           cat            rose
b  anjali   28      agra          dog            lily
c     tia     42      jaipur     elephant      lotus
e     raj     30    banglore      lion         orchid

Here, we give the condition i.e

df[‘Place’] == ‘patna’

Internally if we will see it is giving series object with True and False.

a   False
b   False
c   False
d   True
e   False

Name: Place, dtype: bool

Delete rows based on multiple conditions on a column :

Dataframe drop rows by condition: Let’s try with multiple conditions

deleteRow = df[(df['Age'] >= 30) & (df['Age'] <= 40)].index
df.drop(deleteRow, inplace=True)
print(df)
Output:
    Name  Age     Place     Animal      Flower
b  anjali   28       agra        dog          lily 
c     tia     42       jaipur    elephant    lotus

Here, we join two conditions i.e df[‘Age’]>=30 and df[‘Age’]<=40 by putting ’&’ between two conditions.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Remove Contents from a Dataframe

java print backslash – Java Program to Print Backslash Star Pattern

Program to Print Backslash Star Pattern

Java print backslash: In this article we are going to see how to print the Backslash star pattern

Example-1

When row values=4
*      
  *    
    *  
      *
Example-2

When column values=5
*        
  *      
    *    
      *  
        *

How to print backslash in java: Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Approach:

  • Enter total row and store it an integer variable say row.
  • Take first for loop to print all the rows.
  • Take a inner loop to print the column values.
  • Then go on printing the star symbols according to the iteration.

JAVA Code:

Method-1 : Static Star Character

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) {
    // Take user input for no fo rows 
    System.out.print("Enter the no of rows = ");
    Scanner sc= new Scanner(System.in);
    int r,c,row;
    // store the input value in row
    row=sc.nextInt();
    // loop for no of rows
   for(r=1; r<=row; r++)
   {   
       // inner loop to print symbol
      for(c=1; c<=row; c++)
      {   
          // if row and column have same value print symbol     
         if(r==c)      
            System.out.print("* ");      
         else          
            System.out.print("  ");      
      } 
      System.out.println("");
   } 
    }
}

Output:

Enter the no of rows = 5
*        
  *      
    *    
      *  
        *

Method-2 : User Input Character

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
    	 int r,c,row;
    	// Take user input for no fo rows 
    	Scanner sc= new Scanner(System.in);
    	// store the input value in row
    	System.out.print("Enter the no of rows : ");
        row=sc.nextInt();
        // enter random character
    	System.out.print("Enter symbol : ");
    	char s=sc.next().charAt(0);
        // loop for no of rows
        for(r=1; r<=row; r++)
        {   
           // inner loop to print symbol
          for(c=1; c<=row; c++)
          {   
              // if row and column have same value print symbol     
             if(r==c)      
                System.out.print(s+" ");      
             else          
                System.out.print("  ");      
          } 
          System.out.println("");
        } 
    }
}

Output:

Enter the no of rows : 5

Enter symbol : #
#
  #
     #
        #
           #

Explanation:

Let’s understand the program will detailed explanation.

Let we have taken row as 5.

Iteration-I

Star pattern in java: r=1 (passed through first for loop condition) which will execute till r<=row.

Now inner for loop will execute 1 time and prints a symbol (if column value and row value are same) otherwise a space, which will iterate till c<=row.

*

Iteration-II

r=2 (passed through first for loop condition) which will execute till r<=row.

Now inner for loop will execute 2 time and prints a symbol (if column value and row value are same) otherwise a space, which will iterate till c<=row

 *

Iteration-III

r=3 (passed through first for loop condition) which will execute till r<=row. Now inner for loop will execute 3 time and prints a symbol (if column value and row value are same) otherwise a space, which will iterate till c<=row.

  *

Iteration-IV

r=4 (passed through first for loop condition) which will execute till r<=row. Now inner for loop will execute 4 time and prints a symbol (if column value and row value are same) otherwise a space, which will iterate till c<=row.

   *

Iteration-V

r=5 (passed through first for loop condition) which will execute till r<=row. Now inner for loop will execute 5 time and prints a symbol (if column value and row value are same) otherwise a space, which will iterate till c<=row.

    *

Now r=6 , so first for loop condition fails. Ans no more for loop inside that will be executed. At last we will see a pattern like this as output in the output screen.

*        
 *          
  *          
   *           
    *

C Code:

#include<stdio.h>
int main()
{
   int r,c,k,row;
   printf("Enter the no of rows = ");
   scanf("%d",&row);
   for(r=1; r<=row; r++)
   {    
      for(c=1; c<=row; c++)
      {        
         if(r==c)      
            printf("* ");      
         else          
            printf("  ");      
      }        
      printf("\n");
   }    
   return 0;
}
Output:

Enter the no of rows = 5
*        
  *      
    *    
      *  
        *

C++ Code:

#include <iostream>

using namespace std;

int main()
{
   int r,c,row;
   cout<<"Enter the no of rows = ";
   cin>>row;
   for(r=1; r<=row; r++)
   {    
      for(c=1; c<=row; c++)
      {        
         if(r==c)      
            cout<<("* ");      
         else          
            cout<<("  ");      
      }        
      cout<<("\n");
   }    
   return 0;
}
Output:

Enter the no of rows = 5
*        
  *      
    *    
      *  
        *

Related Java Star Pattern Programs:

List removeall java – Java ArrayList removeAll() Method with Example

Java ArrayList removeAll() Method with Example

Java arraylist removeall: In the previous article we have discussed about Java ArrayList remove() Method with Example

In this article we are going to see the use Java ArrayList removeAll() method along with suitable examples.

Java ArrayList removeAll() Method with Example

removeAll( ):

List removeall java: This java.util.ArrayList.removeAll() method is used to remove all the elements from the arraylist or in the specified collection. It returns true if the original list is changed after calling removeAll() method.

Syntax:

arrayListName.removeAll(Collection col)

Where,

  • arrayListName refers to the name of your ArrayList.
  • Collection col refers to a collection ‘col’ whose all the elements will be removed.

Let’s see a program to understand it more clearly.

Approach:

  • Create a new ArrayList of type Integer.
  • Add Integer elements into the ArrayList using the add() method.
  • Display the ArrayList elements.
  • Remove all the element from the ArrayList using removeAll( ) method.
  • Print the new arrayList

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create an ArrayList of Integer datatype
        ArrayList<Integer> arr1 = new ArrayList<Integer>();
        // Adding some elements to the ArrayList
        arr1.add(1);
        arr1.add(2);
        arr1.add(3);
        // Prints the ArrayList elements
        System.out.println("The elements of ArrayList are: "+arr1);
        // removing all the element from the ArrayList
        arr1.removeAll(arr1);
        // Prints the new ArrayList elements
        System.out.println("The new elements of ArrayList are: "+arr1);
    }
}

Output:

The elements of ArrayList  are: [1, 2, 3]
The new elements of ArrayList are: []

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

Related Java Programs:

Find and Replace all occurrences of a sub string in C++

Find all occurrences of a substring in a string c++: In the previous article, we have discussed about Converting a String to Upper & Lower Case in C++ using STL & Boost Library. Let us learn how to find and Replace all occurrences of a sub string in C++ Program.

Finding and replacing all occurrences of a sub string in C++

Boost replace_all: In this article we will discuss about how we can find and replace all occurrences of a sub string.

We will see 3 different ways to achieve this.

Method-1 : Using STL

// Program :

#include <iostream>
#include <string>

void FindAndReplace(std::string & data, std::string Searching, std::string replaceStr)
{
    // Getting the first occurrence
    size_t position = data.find(Searching);
    // Repeating till end is reached
    while( position != std::string::npos)
    {
        // Replace this occurrence of Sub String
        data.replace(position, Searching.size(), replaceStr);
        // Get the next occurrence from the current position
        position =data.find(Searching, position + replaceStr.size());
    }
}
int main()
{
    // Original String
    std::string data = "BtechGeeks is Good";
    std::cout<<data<<std::endl;
    // Replacing 'Good' with 'Best'
    FindAndReplace(data, "Good", "Best");
    std::cout<<data<<std::endl;
    return 0;
}
Output :
BtechGeeks is Good
BtechGeeks is Best

Method-2 : Using Boost::replace_all

// Program :

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

int main()
{
    std::string sample = "BtechGeeks is Good";
    std::cout<<sample<<std::endl;
    // Replacingb all occurrences of 'Good' with 'Best'
    // This is case Sensitive Version
    boost::replace_all(sample, "Good", "Best");
    std::cout<<sample<<std::endl;
}
Output :
BtechGeeks is Good
BtechGeeks is Best

Method-3 : Using Boost::ireplace_all

// Program :

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>

int main()
{
    std::string sample = "BtechGeeks is Good";
    std::cout<<sample<<std::endl;
    // Replacingb all occurrences of 'Good' with 'Best'
    // This is case Sensitive Version
    boost::ireplace_all(sample, "Good", "Best");
    std::cout<<sample<<std::endl;
}
Output :
BtechGeeks is Good
BtechGeeks is Best

 

Vector setsize – Java Vector setSize( ) Method with Example

Java Vector setSize( ) Method with Example

Vector setsize: In the previous article, we have discussed about Java Vector ensureCapacity( ) Method with Example

In this article, we are going to see the use of Java Vector setSize() method along with examples.

Java Vector setSize( ) Method with Example

This java.util.Vector.setSize() method  sets the size of the vector and any empty element index is assigned null value. Its return type is void.

Syntax:

vectorName.setSize(int new_size );

Where,

  • vectorName refers to the name of the vector.
  • new_size refers to the parameter passed to method which sets the new size of the vector.

Approach:

  • Create a vector of string data type and add some elements to it.
  • Print the elements.
  • Now, set the vector size to 9 by passing it into the setSize( ) method.
  • Print the vector elements and its size after setting the new size.

Program:

import java.util.*;
public class Main
{
   public static void main(String[] args)
   {
       // Create a Vector of string datatype
       Vector<String> vec = new Vector<String>();
       // Adding some elements to the vector
       vec.add("One");
       vec.add("Two");
       vec.add("Three");
       vec.add("Four");
       vec.add("Five");
       vec.add("Six");
       vec.add("Seven");
       // Prints the vector elements
       System.out.println("The vector elements are "+vec);
       // Sets the size of the vector
       vec.setSize(9);
       // Prints the vector elements after set the size of the vector
       System.out.println("The vector elements after set the size are "+vec);
       // Prints the size of the vector
       System.out.println("The size of the vector after setting size to 9 is "+vec.size());
   }
}
Output:

The vector elements are [One, Two, Three, Four, Five, Six, Seven]
The vector elements after set the size are [One, Two, Three, Four, Five, Six, Seven, null, null]
The size of the vector after setting size to 9 is 9

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Related Java Programs:

Removelast() java – Java LinkedList removeLast() Method with Examples

Java LinkedList removeLast() Method with Examples

Removelast() java: In the previous article, we have discussed about Java LinkedList removeIf() Method with Examples

In this article we are going to see the use of Java LinkedList removeLast() method along with suitable examples.

Java LinkedList removeLast() Method with Examples

This java.util.LinkedList.removeLast() method is used to remove any single element from the last/tail of the LinkedList. It returns the last element which got removed.

Syntax:

LinkedListName.removeLast()

Where,

  • LinkedListName refers to the name of your LinkedList.

Let’s see removeLast() method with suitable examples.

Example-1: Java LinkedList removeLast() Method – Example with String Type LinkedList

Approach:

  • Create a new LinkedList of type String.
  • Add String elements into the LinkedList using the add() method.
  • Display the LinkedList elements.
  • Then remove the last element from the LinkedList using removeLast() method.
  • Print the new LinkedList.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create a LinkedList of string datatype
        LinkedList<String> l = new LinkedList<String>();
        // Adding some elements to the LinkedList
        l.add("Hello");
        l.add("this");
        l.add("is");
        l.add("an");
        l.add("example of removeLast() method");
        // Prints the LinkedList elements
        System.out.println("The elements of LinkedList are: "+l);
        // removing the last element from the LinkedList
        l.removeLast();
        // Prints the new LinkedList elements
        System.out.println("The new elements of LinkedList are: "+l);
    }
}
Output:

The elements of LinkedList are: [Hello, this, is, an, example of removeLast() method]
The new elements of LinkedList are: [Hello, this, is, an]

Example-2: Java LinkedList removeLast() Method – Example with Integer Type LinkedList

Approach:

  • Create a new LinkedList of type Integer.
  • Add integer elements into the LinkedList using the add() method.
  • Display the LinkedList elements.
  • Then remove the last element from the LinkedList using removeLast() method.
  • Print the new LinkedList.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create a LinkedList of Integer datatype
        LinkedList<Integer> l = new LinkedList<Integer>();
        // Adding some elements to the LinkedList
        l.add(2);
        l.add(4);
        l.add(6);
        l.add(8);
        l.add(10);
        // Prints the LinkedList elements
        System.out.println("The elements of LinkedList are: "+l);
        // removing the last element from the LinkedList
        l.removeLast();
        // Prints the new LinkedList elements
        System.out.println("The new elements of LinkedList are: "+l);
    }
}
Output:

The elements of LinkedList are: [2, 4, 6, 8, 10]
The new elements of LinkedList are: [2, 4, 6, 8]

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

Related Java Programs:

Jsonarray to string array – Java Program to Convert JSON Array to String Array

Java Program to Convert JSON Array to String Array

Jsonarray to string array: In the previous article, we have seen Java Program to Print Multiple Types of Arrays Using Method Overloading

In this article we are going to see how to Convert JSON array to String array.

Java Program to Convert JSON Array to String Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways how to to Convert JSON array to String array.

Method-1: Java Program to Convert JSON Array to String Array By Static Initialization of Array Elements

Approach:

  • Loop over the JSON array.
  • For each element in the JSON array insert it to the String array after converting it to string using toString() method.

Program:

import java.util.*;
import org.json.*;

public class Main 
{
    public static void main(String[] args) 
    {
        //JSON array created
        JSONArray jsonArray = new JSONArray();
        //Adding elements to JSON array
        jsonArray.add("a");
        jsonArray.add("b");
        jsonArray.add("c");
        //calling the user defined method convertJSONArraytoStringArray()
        convertJSONArraytoStringArray(jsonArray);
    }
    
    //convertJSONArraytoStringArray() converts JSON array to String array
    public public static void convertJSONArraytoStringArray(JSONArray[] jsonArray) 
    {
        String[] stringArray = new String[jsonArray.length];
        for (int i = 0; i < jsonArray.length; i++) 
        {
            //converting to string array by using toString() method
            stringArray[i] = jsonArray[i].toString();
        }

        System.out.println("Given JSON array: " + jsonArray);
        System.out.println("String array: " + Arrays.toString(stringArray));
    }

}
Output:

Given JSON array: ["a ","b ","c "]
String array: ["a ","b ","c "]

Method-2: Java Program to Convert JSON Array to String Array By Dynamic Initialization of Array Elements

Approach:

  • Create scanner class object.
  • Ask the user for number of elements.
  • Ask the user for array elements.
  • Loop over the JSON array.
  • For each element in the JSON array insert it to the String array after converting it to string using toString() method.

Program:

import java.util.*;
import org.json.*;

public class Main 
{
    public static void main(String[] args) 
    {
        JSONArray jsonArray = new JSONArray();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of elements in the array: ");
        int n = sc.nextInt();
        sc.nextLine(); // to consume the newline character
        System.out.println("Enter the elements: ");
        for (int i = 0; i < n; i++) {
            jsonArray.put(sc.nextLine());
        }

        convertJSONArraytoStringArray(jsonArray);
    }

    public public static void convertJSONArraytoStringArray(JSONArray[] jsonArray) 
    {
        String[] stringArray = new String[jsonArray.length];
        for (int i = 0; i < jsonArray.length; i++) 
        {
            stringArray[i] = jsonArray[i].toString();
        }

        System.out.println("Given JSON array: " + jsonArray);
        System.out.println("String array: " + Arrays.toString(stringArray));
    }

}
Output:

Enter the number of elements in the array: 4
Enter the elements:
Hello
World
In
JSON
Given JSON array: ["Hello ","World ","In", “JSON”]
String array: ["Hello ","World ","In", “JSON”]

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs:

C++ list vs vector – Difference Between Vector and List in C++ | Vector vs List | Examples of std::vector & std::list

Difference Between Vector and List in CPP: In the previous article, we have discussed How to check if a given key exists in a Map | C++. Let us learn the Difference Between Vector and List in C++ Program.

Vector vs List in the C++

C++ vector vs list: In this article, we are going to learn about the difference between vector and list in C++.

Before going to this difference directly, First of all, we have to know what is ‘STL’? STL stands for Standard Template Library it is a library of headers containing commonly used data structures and algorithms. They are defined using C++ templates, you can also use different data types to define this.

This STP is broadly divided into four sections:

  1. Containers
  2. Iterators
  3. Algorithms
  4. Functional

C++ list vs vector: Vectors and Lists are the most used containers. Both store a no of items, just like an array but there are interesting differences between the two.

1. Vector:

Vector vs list c++: Vectors are sequence containers means it contains all the elements in a contiguous memory representing arrays that can change in size. Just like arrays, vectors use contiguous storage location for their elements, which means that their element can also be accessed using offsets on regular pointers to its elements, and just as efficiently in arrays.

Pros: Vector is dynamic. It is fast to add items to the end and fast to remove items from the middle or beginning and we can use[].vector is thread-safe and it is synchronized also.

Cons: but it is slow at adding/removing items from the middle or beginning.

Vectors are also called dynamic arrays i.e. you can add and remove items at run-time.

Vectors are perfect for :

  • When you need to access items arbitrarily with []brackets.
  • When you only need to add items to the end of the list.

Insertion & Deletion :

  • Insertion and deletion in the vector are less efficient than a list.
  • As insertion or deletion at start or middle will make all elements to shift by one.`

2. List:

Vector vs list: Lists are sequence containers that allow non-contiguous memory allocation so constant time insert and delete operations anywhere within the sequence and iteration in both directions are possible easily.

Pros: Lists are also dynamic, fast to add items to the beginning, middle, and end so long as you have an iterator. Traverse forward and Backward. Lists are not thread-safe and it is not synchronized.

Cons: slow at accessing items from the middle and no use of [].

The list usually refers to a linear collection of data. one form of linear list is an array, mainly lists are doubly linked lists. They allow fast addition of items to the beginning, middle, and end.

Lists are perfect for:

  • When you only need to access items in the order, either forwards or reverse.
  • When you have to add items to the middle or beginning of the list often very quickly.

Insertion & Deletion of the List:

  • Insertion and Deletion in the list are more efficient than a vector.
  • As insertion or deletion at the start, middle, or at the end only causes swapping of a couple of pointers internally.

Top 10 differences in Vector and List of the C++

Linked list vs vector c++: Here are some of the top points related to Vector vs List of the C++:

  • A Vector has contiguous memory
  • A list has noncontiguous memory
  • A list is not synchronized while a vector is
  • Lists and vectors are both dynamically growing arrays
  • A Vector Pre allocates space for future
  • A list doesn’t pre-allocate space for future
  • Lists have no default size while a vector has a default size of 10
  • A list is not thread-safe whereas a vector is thread-safe
  • A vector grows by its size twice while a list decreases to half, i.e., 50 percent
  • Lists, as they apply only to addition and deletion in the front and rear, are faster while vectors take more CPU

std::vector vs std::list | Vector and List in the C++

C++ list vs vector: The elements of Std List stores at non-contiguous memory locations i.e. it internally uses a doubly linked list i.e.

vector list difference

Whereas, a vector stores elements at contiguous memory locations like an array i.e.

vector vs list

Examples of Vector List in C++

Let us discuss examples of C++ vector vs list.

Example #1 – Vector Example

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
for (int i = 5; i <= 15; i++)
{
vec.push_back(i);
}
cout<< "Size of vector is: " << vec.size() << endl;
cout << "Vector elements are given below : ";
for (auto i = vec.begin(); i != vec.end(); i++)
cout << *i << endl;
vec.insert(vec.begin(), 20);
cout<< "Size of vector is: " << vec.size() << endl;
cout << "Updated Vector elements are given below : ";
for (auto i = vec.begin(); i != vec.end(); i++)
cout << *i << endl;
return 0;
}

Output: 

cpp vector example output

Example #2 – List Example

#include <list>
#include <iterator>
using namespace std;
//function to display the elements of list using iterator 'itr'
void display(list <int> x)
{
list <int> :: iterator itr;
for(itr = x.begin(); itr != x.end(); itr++)
cout << *itr << endl;
}
int main()
{
list <int> list1, list2;
for (int i = 0; i < 5; ++i)
{
list1.push_back(i * 10);
list2.push_front(i + 4);
}
cout << "Elements in List 1 are: "<< endl;
display(list1);
cout << "Elements in List 2 are : " << endl;
display(list2);
cout << "Reversing the list2 : "<< endl;
list2.reverse();
display(list2);
cout << "Sorting the elements of list2:"<< endl;
list2.sort();
display(list2);
return 0;