w3resource

Java Exercises: Replace a string "python" with "java" and "java" with "python" in a given string

Java Basic: Exercise-230 with Solution

Write a Java program to replace a string "python" with "java" and "java" with "python" in a given string.

Input:

English letters (including single byte alphanumeric characters, blanks, symbols) are given on one line. The length of the input character string is 1000 or less.

Pictorial Presentation:

Java Basic Exercises: Replace a string 'python' with 'java' and 'java' with 'python' in a given string.

Sample Solution:

Java Code:

 import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Input the string:");
        String str1 = br.readLine();
 
        str1 = str1.replaceAll("java", "py_thon");
        str1 = str1.replaceAll("python", "java");
        str1 = str1.replaceAll("py_thon", "python");
        System.out.println("New string:");
        System.out.println(str1);
    }
}


Sample Output:

Input the string:
python is more popular than java
New string:
java is more popular than python

Flowchart:

Flowchart: Replace a string 'python' with 'java' and 'java' with 'python' in a given string.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous:Write a Java program that reads n digits (given) chosen from 0 to 9 and prints the number of combinations where the sum of the digits equals to another given number (s). Do not use the same digits in a combination.
Next: Write a Java program to find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9. The number that can be rearranged shall start with 0 as in 00135668.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH