Tuesday 21 April 2020

Java: Convert String to a character

Following snippet converts the string to a character.

public static char getChar(String str) {
         if (str == null || str.length() > 1) {
                  throw new IllegalArgumentException("String must not be null and has length 1");
         }

         return str.charAt(0);
}

App.java
package com.sample.app;

public class App {

	public static char getChar(String str) {
		if (str == null || str.length() > 1) {
			throw new IllegalArgumentException("String must not be null and has length 1");
		}

		return str.charAt(0);
	}

	public static void main(String args[]) {

		char ch = getChar("A");

		System.out.println("ch : " + ch);
	}

}

Output
ch : A

You may like

No comments:

Post a Comment