# Use Predefined Standard Charset

# Description

This rule replaces invocations of Charset.forName(String) (opens new window) by constants defined in StandardCharsets (opens new window).

# Benefits

Avoids creating new objects that are already predefined.

# Tags

# Code Changes

# Using Charset forName with "UTF-8"

Pre

Charset c = Charset.forName("UTF-8");

Post

Charset c = StandardCharsets.UTF_8;

# Using Charset forName with "US-ASCII"

Pre

Charset c = Charset.forName("US-ASCII");

Post

Charset c = StandardCharsets.US_ASCII;

# Using Charset forName with "ISO-8859-1"

Pre

Charset c1 = Charset.forName("ISO-8859-1");

Post

Charset c1 = StandardCharsets.ISO_8859_1;

# Using Charset forName with "UTF-16"

Pre

Charset c3 = Charset.forName("UTF-16");

Post

Charset c3 = StandardCharsets.UTF_16;

# Using Charset forName with "UTF-16BE"

Pre

Charset c4 = Charset.forName("UTF-16BE");

Post

Charset c4 = StandardCharsets.UTF_16BE;

# Using Charset forName with "UTF-16LE"

Pre

Charset c5 = Charset.forName("UTF-16LE");

Post

Charset c5 = StandardCharsets.UTF_16LE;

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID UsePredefinedStandardCharset
First seen in jSparrow version 3.21.0
Minimum Java version 1.7
Remediation cost 2 min
Links