Javaの文字列を大文字に変換する。

Javaの文字列を大文字に変換するには、toUpperCase()メソッドを使用することができます。

JavaのStringを大文字に変換する

java string to uppercase
  • Java String toUpperCase() method has two variants – toUpperCase() and toUpperCase(Locale locale).
  • Conversion of the characters to upper case is done by using the rules of default locale. Calling toUpperCase() function is same as calling toUpperCase(Locale.getDefault()).
  • Java String to upper case method is locale sensitive, so use it carefully with strings that are intended to be used locale independent. For example programming language identifiers, HTML tags, protocol keys etc. Otherwise you might get unwanted results.
  • To get correct upper case results for locale insensitive strings, use toUpperCase(Locale.ROOT) method.
  • String toUpperCase() returns a new string, so you will have to assign that to another string. The original string remains unchanged because String is immutable.
  • If locale is passed as null to toUpperCase(Locale locale) method, then it will throw NullPointerException.

ジャヴァの文字列を大文字に変換する例

簡単な例で文字列を大文字に変換し、それを表示してみましょう。

String str = "Hello World!";
System.out.println(str.toUpperCase()); //prints "HELLO WORLD!"

ユーザーの入力を取得して、それを大文字に変換し出力するために、Scannerクラスも使用することができます。以下は、Javaの文字列を大文字に変換し出力する完全な例です。

package com.scdev.string;

import java.util.Scanner;

public class JavaStringToUpperCase {

	public static void main(String[] args) {
		String str = "hello World!";

		String strUpperCase = str.toUpperCase();

		System.out.println("Java String to Upper Case: " + strUpperCase);

		readUserInputAndPrintInUpperCase();
	}

	private static void readUserInputAndPrintInUpperCase() {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please write input String and press Enter:");
		String str = sc.nextLine();
		System.out.println("Input String in Upper Case = " + str.toUpperCase());
		sc.close();
	}

}

上記プログラムの実行のサンプルを示す、下記のコンソール出力をご覧ください。

Java String to Upper Case: HELLO WORLD!
Please write input String and press Enter:
Welcome to JournalDev Tutorials
Input String in Upper Case = WELCOME TO JOURNALDEV TUTORIALS

Javaの文字列を大文字に変換する例については以上です。参照: APIドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *