Friday, February 20, 2026
HomeLanguagesJavaJava Program to Replace All Line Breaks from Strings

Java Program to Replace All Line Breaks from Strings

Given a string, write a Java program to replace all line breaks from the given String.

Examples

Input - Geeks
        For
        Geeks
        
Output - Geeks For Geeks

Line Break: A line break (“\n”) is a single character that defines the line change. 

In order to replace all line breaks from strings replace() function can be used.

String replace(): This method returns a new String object that contains the same sequence of characters as the original string, but with a given character replaced by another given character.

Syntax:

public String replace(char old,char new)

Parameters:

  • old: old character
  • new: new character

Returns value: Returns a string by replacing an old character with the new character

Java




// Java Program to Replace All
// Line Breaks from Strings
 
public class remove {
    public static void main(String[] args)
    {
        String s = "Replace\n"
                   + " all\n"
                   + " line\n"
                   + " breaks\n"
                   + " from\n"
                   + " strings";
       
        System.out.println(
            "Original String with line breaks - " + s);
       
        // replacing line breaks from string
        s = s.replace("\n", "");
       
        System.out.println(
            "String after replacing line breaks - " + s);
    }
}


Output

Original String with line breaks - Replace
 all
 line
 breaks
 from
 strings
String after replacing line breaks - Replace all line breaks from strings
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS