# 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;

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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