Pages

Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Thursday, January 6, 2022

Java String startsWith() Examples

1. Overview

In this article, You'll learn how to Test if this string starts with the specified prefix

Method startsWith() is case-sensitive.

String API is added with a method startsWith() that returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.

This method works exactly opposite to the String endsWith() method.

Java String startsWith() Examples

Sunday, December 19, 2021

Java Float To String Conversion Examples

1. Introduction


In this article, We'll learn how to convert Float values to String. This is a common scenario to the developers and how conversions can be done using Java API methods.

String and Float classes have been provided with utility methods and these methods are always defined as static because directly can be accessed with the class names.

All examples are designed to show the conversion of primitive float and wrapper float to String objects.

Java Float To String Conversion Examples


Monday, December 6, 2021

Java String substring() Method Example

1. Introduction


In this tutorial, You'll learn how to get the portion of a string using the substring() method of String API.

The name of this method indicates that it will fetch substring from an original string for a given index.

Java String substring() Method Example

String program to find the regionmatches() method.

Friday, December 3, 2021

Java Add or Print Newline In A String

1. Overview

In this tutorial, We'll learn how to add and print the new line to string formatting the text in a better way.

Formating strings and resulting in the text in a different format is often needed in java programming.

Let us focus on adding new line escape characters in java. Example programs on adding newline character to String and to HTML contents.

And also we will discuss What is the difference between \n and \r (\n vs \r)?

we have already discussed the difference between \n and \t

Java Add or Print Newline In A String

Saturday, November 20, 2021

Java - How to mix two strings and generate another?

1. Overview

In this tutorial, We'll learn how to mix and concatenate the two or more strings in java.

Strings are used to store the sequence of characters in the order in the memory and they are considered as objects.

Strings are located in java.lang package

If you are new to Strings, please go through the below string methods.



String creation can be done in two ways using new keyword and literals as below.
String s1 = new String("JavaProgramTo.com");
String s2 = "welcome, Java developer";
In the next sections, you will see examples of adding strings using different techniques.

Java - How to mix two strings and generate another?

Friday, November 19, 2021

Java 11 String.lines() - Get Stream of Lines

1. Java 11 String Stream<String> lines() Overview


In this tutorial, We'll learn how to convert String to Stream. lines() method returns Stream of Strings. We'll go through String lines() Method Examples.

Simple words, This method break down the string into lines if input string has lime terminators.

Supported line terminators are '\n', '\r' and '\r\n'.

"\n":  a line feed character
"\r":  a carriage return character
"\r\n": a carriage return followed immediately by a line feed

Java 11 String API lines() Method Example

Tuesday, November 16, 2021

Java String toCharArray() - How to convert string to char array?

Java String toCharArray():


The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.

Returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.


Java String toCharArray() with example - Convert string to char - Internal


Syntax:
public char[] toCharArray​()

Sunday, November 14, 2021

Java - How To Compare Two Strings Lexicographically | String compareTo method works internally

Java - How To Compare Two Strings Lexicographically


Today, we will learn about comparing two strings lexicographically in Java. Many of you might be aware of how to compare two strings in java but not in a manner lexicographically. Lexicographically word looks somewhat new and weird. Do not worry, we will go step by step easily understandable way and how it works internally.

First, We will go through examples of how to compare two string values are the same/equal or not.

Compare Two Strings Lexicographicall

Saturday, November 13, 2021

Java String format() Examples

Java String format​() method

String format method is used to format the string in the specified format. This method can be used as String output format by passing multiple arguments because the second parameter is the variable-arguments(Var-Args). Recommend to read in-depth usage of Var-Args in Java. We can pass any type of object here such as String, Float, Double etc together. You will find the examples on each in this course.

This format method is introduced in java 1.5 version and it is overloaded and static methods

Java String format() Examples

Java String format​() method Syntax: 

// Takes default locale 
public static String format​(String format, Object... args)
//Takes passed locale instead of default locale value
public static String format​(Locale l, String format, Object... args)

Thursday, November 11, 2021

Java 8 - Converting a List to String with Examples

1. Overview

In this tutorial, we will learn how to convert List to String in java with example programs.

This conversion is done with the simple steps with java api methods.


First, we will understand how to make List to String using toString() method.
Next, Collection to String with comma separator or custom delimiter using Java 8 Streams Collectors api and String.join() method.
Finally, learn with famous library apache commands StringUtils.join() method.

For all the examples, input list must be a type of String as List<String> otherwise we need to convert the non string to String. Example, List is type of Double then need to convert then double to string first.

Java 8 Streams- Converting a List to String with Examples.png



2. List to String Using Standard toString() method


List.toString() is the simplest one but it adds the square brackets at the start and end with each string is separated with comma separator.

The drawback is that we can not replace the comma with another separator and can not remove the square brackets.

package com.javaprogramto.convert.list2string;

import java.util.Arrays;
import java.util.List;

/**
 * Example to convert List to string using toString() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingToStringExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");
	
	// converting List<String> to String using toString() method
	String stringFromList = list.toString();
	
	// priting the string
	System.out.println("String : "+stringFromList);		
	}
}
 
Output:

String : [One, Two, Three, Four, Five]

 

3. List to String Using Java 8 String.join() Method


The above program works before java 8 and after. But, java 8 String is added with a special method String.join() to convert the collection to a string with a given delimiter.

The below example is with the pipe and tilde separators in the string.

import java.util.Arrays;
import java.util.List;

/**
 * Example to convert List to string using String.join() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingString_JoinExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");
	
	// converting List<String> to String using toString() method
	String stringFromList = String.join("~", list);
	
	// priting the string
	System.out.println("String with tilde delimiter: "+stringFromList);
	
	// delimiting with pipe | symbol.
	String stringPipe = String.join("|", list);
	
	// printing
	System.out.println("String with pipe delimiter : "+stringPipe);
	
	}
}

 
Output:
String with tilde delimiter: One~Two~Three~Four~Five
String with pipe delimiter : One|Two|Three|Four|Five

 

4. List to String Using Java 8 Collectors.joining() Method


Collectors.join() method is from java 8 stream api. Collctors.joining() method takes delimiter, prefix and suffix as arguments. This method converts list to string with the given delimiter, prefix and suffix.

Look at the below examples on joining() method with different delimiters. But, String.join() method does not provide the prefix and suffix options.

If you need a custom delimiter, prefix and suffix then go with these. If you do not want the prefix and suffix then provide empty string to not to add any before and after the result string.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Example to convert List to string using Collectors.joining() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingString_JoinExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");

	// using java 8 Collectors.joining with delimiter, prefix and suffix
	String joiningString = list.stream().collect(Collectors.joining("-", "{", "}"));
	
	// printing
	System.out.println("Collectors.joining string : "+joiningString);
	
	String joiningString3 = list.stream().collect(Collectors.joining("@", "", ""));
	
	// printing
	System.out.println("Collectors.joining string with @ separator : "+joiningString3);
	
	
	}
}
 
Output:
Collectors.joining string : {One-Two-Three-Four-Five}
Collectors.joining string with @ separator : One@Two@Three@Four@Five

 

5. List to String Using Apache Commons StringUtils.join() method


Finally way is using external library from apache commons package. This library has a method StringUtils.join() which takes the list and delimiter similar to the String.join() method.

import org.apache.commons.lang3.StringUtils;

/**
 * Example to convert List to string using apache commons stringutils.join() method.
 * 
 * @author javaprogramto.com
 *
 */
public class ListToStringUsingStringUtils_JoinExample {

	public static void main(String[] args) {
		
	// creating a list with strings.
	List<String> list = Arrays.asList("One",
					  "Two",
					  "Three",
					  "Four",
					  "Five");

	// using java 8 Collectors.joining with delimiter, prefix and suffix
	String joiningString = StringUtils.join(list, "^");
	
	// printing
	System.out.println("StringUtils.join string with ^ delimiter : "+joiningString);
	
	String joiningString3 = StringUtils.join(list, "$");
	
	// printing
	System.out.println("StringUtils.join string with @ separator : "+joiningString3);
	
	
	}
}
 

Output:
StringUtils.join string with ^ delimiter : One^Two^Three^Four^Five
StringUtils.join string with @ separator : One$Two$Three$Four$Five
 

6. Conclusion


In this article, we've seen how to convert List to String in java using different methods before and after java 8.

It is good to use the String.join() method for a given delimiter to produce the string from List.
or If you want to add a prefix or suffix then use stream api Collectors.joining() method with delimiter, prefix and suffix values.



Monday, December 21, 2020

Java String subSequence() Examples - Print subSequence in String

1. Overview


In this article, You'll learn how to get the subsequence from a String. This looks similar to the java string substring() method but the substring method returns a new String but subSequence method returns CharSequence rather than String.

Java String subSequence() Examples - Print subSequence in String

Sunday, December 6, 2020

Java String split() Examples on How To Split a String With Different Delimiters

1. Overview


As part of String API features series, You'll learn how to split a string in java and also how to convert a String into String array for a given delimiter

This concept looks easy but quite a little tricky. You'll understand this concept clearly after seeing all the examples on the split() method.

The string split() method breaks a given string around matches of the given regular expression.
Java String split() Examples on How To Split a String

Monday, November 23, 2020

How To Convert String to Date in Java 8

1. Overview


In this article, you'll be learning how to convert String to Date in Java 8 as well as with Java 8 new DateTime API.

String date conversion can be done by calling the parse() method of LocalDate, DateFormat and SimpleDateFormat classes.

LocalDate is introduced in java 8 enhancements.

DateFormat is an abstract class and direct subclass is SimpleDateFormat.

To convert a String to Date, first need to create the SimpleDateFormat or LocalDate object with the data format and next call parse() method to produce the date object with the contents of string date.

Java Convert String to Date (Java 8 LocalDate.parse() Examples)


First, let us write examples on string to date conversations with SimpleDateFormat classs and then next with DateFormat class.

At last, Finally with LocalDate class parse() method.

All of the following classes are used to define the date format of input string. Simply to create the date formats.

LocalDate
DateFormat
SimpleDateFormat

Note: In date format Captial M indicates month whereas lowercase m indicate minutes.

This will be asked in the interview or written test on How to Format Date to String in Java 8?

Friday, November 13, 2020

Java Program to check String is Palindrome Or Not (Best way and Recursive)

1. Introduction


In this article, We will be learning how to write a java program to check whether a given string is a palindrome or not. This can be solved in many ways and will see all possible ways.

First, What is a palindrome? A String is said palindrome if and only if all characters of the string remain the same even the string is reversed. To solve this first we need to reverse the string and compare the reversed string with the original string. If both are same then the given string is a palindrome, Otherwise, it is not.

java-program-check-string-palindrome


Example:

String input = "madam";
String reversedString = "madam";

Let us observe that input and reversedString contents are the same. So, the input string is called a palindrome.

Tuesday, September 15, 2020

How To Convert String To Byte Array and Vice Versa In Java 8

1. Overview

In this article, you will learn how to convert String to Byte[] array and vice versa in java programming.

First, let us explore the different ways using String.getBytes(), Charset.encode(), CharsetEncoder methods to convert String to a byte array, and last using java 8 Base64 api.

In the next section, you'll find similar methods for byte array to String.

How To Convert String To Byte Array and Vice Versa In Java 8

Tuesday, July 21, 2020

Java String replaceFirst() Example

Java String replaceFirst()

1. Overview


In this String API Methods series, You'll learn replaceFirst() method of String class.

Replaces the first substring of this string that matches the given regular expression with the given replacement.

This method is mostly useful when you want to do the changes only for the first found value and not for all values. But, replace() method replaces for all matches with the given string. You must be careful and choose the right one for your use-case.

Java String replaceFirst() Example

Monday, July 20, 2020

Java String hashCode() example

Java String hashCode()

1. Overview


In this String Methods series, You are going to learn hashcode() method of String class with example programs.

Java String hashCode() method returns the hash code for the String. Hash code value is used in hashing based collections like HashMap, HashTable etc. This method must be overridden in every class which overrides equals() method.

Java String hashCode() example

Thursday, July 16, 2020

Java String codePoints() Example

1. Overview

Java String codePoints()

In this String API Series, You'll learn how to convert String to IntStream with codepoints.

In the new version of java 9, the String class is added with the codePoints() method and returns Stream with integer values.

codePoints() method returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined as if by Character.toCodePoint and the result is passed to the stream. Any other code units, including ordinary BMP characters, unpaired surrogates, and undefined code units, are zero-extended to int values which are then passed to the stream.

Java String codePoints()

Java String codePointCount()

1. Overview


In this String API Series, You'll learn how to get the count of the codepoints in the string for a given text range.

In the previous article, we have discussed codePointAt() method which is to get the codepoint at the given index.

codePointCount() returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.

Let us jump into codePointCount() method syntax and example programs.

Java String codePointCount()

Wednesday, July 15, 2020

Java String codePointBefore()

1. Overview


In this String Methods series, you'll learn what is codePointBefore() method in String API and with example programs.

2. Java String codePointBefore()


codePointBefore() method returns the character (Unicode code point) before the specified index. The index refers to char values (Unicode code units) and ranges from 1 to length.

If the char value at (index - 1) is in the low-surrogate range, (index - 2) is not negative, and the char value at (index - 2) is in the high-surrogate range, then the supplementary code point value of the surrogate pair is returned. If the char value at index - 1 is an unpaired low-surrogate or a high-surrogate, the surrogate value is returned.

Java String codePointBefore()