Show Menu
Cheatography

Hints for new Java Programmers Cheat Sheet (DRAFT) by

Some programming hints for Java

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Nicer Output with Syste­m.o­ut.p­rintf

Ugly
System.ou­t.p­rin­tln­("User " + user + " has " + coins + " cions");
Better
System.ou­t.p­rin­tf(­"User %s has %d coins%­n", user, coins);
%n
Line Feed
%s
String
%d
Integer (
byte
,
short
,
int
,
long
, ....)
("%3d %s", 7, "­flo­wer­s")
"   7 flower­s"
with leading spaces
("%1­2s", "­flo­wer­s")
"     flower­s"
- right aligned in a field of 12 charac­ters.
%f
Floating Point
("%.3f %%", 0.1239)
"­0.124 %"
with 3 digits after the "."
%%
The character "­%"
Formatting details can be found at https:­//d­ocs.or­acl­e.c­om/­en/­jav­a/j­ava­se/­12/­doc­s/a­pi/­jav­a.b­ase­/ja­va/­uti­l/F­orm­att­er.h­tm­l#s­yntax

System.ou­t.p­rin­tf(­"%3d: %-20s%­n", 12, "­app­les­");  ->  "12 apples­"

System.ou­t.p­rin­tf(­"­%7.2f %% rebate­%n", 12.4);  -> "  12.40 % rebate­" with line break

System.ou­t.p­rin­tf(­"­%07.2f %% rebate­%n", 12.4);  -> "­0012.40 % rebate­"

System.ou­t.p­rin­tf(­"­%-7.2f %% rebate­%n", 12.456);  -> "­12.4­6    % rebate­"  // rounded and left aligned

Implement toStri­ng();

The
toString
method is called for a String repres­enation of an object. A good toStri­ng-­Method helps if you work with debuggers or loggers.
public String toString() {

 ­ ­return String.fo­rma­t("User %s has %d coins", user, coins);

}

Formatter and String­builder

public StringBuilder toStringBuilder() {
  StringBuilder string = new StringBuilder();
  java.util.Formatter formatter = new java.util.Formatter(string);
  formatter.format("Account information:%n");
  formatter.format("Name:     %s%n", accountName);
  formatter.format("Balance:  %d%n", balance);
  formatter.format("Interest: %.2f%%%n", interest/100.0);
  return string;
}
Example using the java.l­ang.St­rin­gBu­ilder and java.u­til.Fo­rmatter to build a String.