Download code

Jump to: navigation, search

Back to Convert_Object_to_String_(Java)

Download for Windows: zip

Download for UNIX: zip, tar.gz, tar.bz2

input.nw

  1 <<automatic call to toString>>=
  2 System.out.println("Proof that 1 + 2 = 3");
  3 System.out.println("1 + 2 = " + (1 + 2));
  4 
  5 @ text
  6 
  7 <<convert string literal to String object>>=
  8 String literal = new String("Proof that 1 + 2 = 3");
  9 @ text
 10 
 11 <<convert string literal to String object>>=
 12 String arg0 = new String("1 + 2 = ");
 13 @ text
 14 
 15 <<convert int to String object>>=
 16 String arg1 = new Integer(1 + 2).toString();
 17 @ text
 18 
 19 <<concatenate arguments>>=
 20 String arg = arg0 + arg1;
 21 @ text
 22 
 23 <<print String objects using toString>>=
 24 System.out.println(literal.toString());
 25 System.out.println(arg.toString());
 26 @ text
 27 
 28 <<print 1 + 2 = 3 the long way>>=
 29 <<convert string literal to String object>>
 30 <<convert int to String object>>
 31 <<concatenate arguments>>
 32 <<print String objects using toString>>
 33 @ text
 34 
 35 <<proof that 1 + 2 = 3>>=
 36 assert ("Proof that 1 + 2 = 3").equals(literal.toString());
 37 assert ("1 + 2 = " + (1 + 2)).equals(arg.toString());
 38 @ text
 39 
 40 <<not the way to do it>>=
 41 System.out.println("Proof that sometimes 1 + 2 does not make 3");
 42 System.out.println("1 + 2 = " + 1 + 2);
 43 @ text
 44 
 45 <<not the way to do it>>=
 46 System.out.println(new String("Proof that sometimes 1 + 2 does not make 3").toString());
 47 System.out.println((new String("1 + 2 = ").toString()) + (new Integer(1).toString()) + (new Integer(2).toString()));
 48 @ text
 49 
 50 <<counter proof that 1 + 2 doesn't always make 3>>=
 51 assert ("1 + 2 = " + 1 + 2).equals("1 + 2 = 12");
 52 @ text
 53 
 54 <<StringLiterals.java>>=
 55 
 56 public class StringLiterals {
 57 
 58   public static void main (String [] args) {
 59      System.out.println("Demonstrating that Java's built-in support for string literals\n" +
 60         "relies on the toString method and string concatenation");
 61 
 62      <<automatic call to toString>>
 63 
 64      <<print 1 + 2 = 3 the long way>>
 65 
 66      <<proof that 1 + 2 = 3>>
 67 
 68      <<not the way to do it>>
 69 
 70      <<counter proof that 1 + 2 doesn't always make 3>>
 71 
 72   }
 73 
 74 }
 75 @ text
 76 
 77 @ text
 78 
 79 <<Printing objects>>=
 80 Object o = new Object();
 81 System.out.println("Object printed with toString: " + o);
 82 @ text
 83 
 84 <<Printing objects>>=
 85 String objectAsString = "" + o;
 86 System.out.println("Object as a string literal: " + objectAsString);
 87 @ text
 88 
 89 <<Printing objects>>=
 90 assert objectAsString.equals(o.toString());
 91 @ text
 92 
 93 <<print table of numbers>>=
 94 public static void printTableOfNumbers() {
 95     String table = "Table of the Java Numbers\n" +
 96 		 "Primitive Type\tSize in Bits\tTypical Value\tMinimum Value\t\tMaximum Value\n" +
 97 		 "==============\t=============\t============\t=============\t\t=============\n";
 98 	// byte
 99 	table += "byte\t\t" + 8 + "\t\t" + (byte)5 + "\t\t" + Byte.MIN_VALUE + "\t\t\t" + Byte.MAX_VALUE + "\n";
100 	// short
101 	table += "short\t\t" + 16 + "\t\t" + (short)1024 + "\t\t" + Short.MIN_VALUE + "\t\t\t" + Short.MAX_VALUE + "\n";
102 	// int
103 	table += "int\t\t" + 32 + "\t\t" + 65536 + "\t\t" + Integer.MIN_VALUE + "\t\t" + Integer.MAX_VALUE + "\n";
104 	// long
105 	table += "long\t\t" + 64 + "\t\t" + 1000000000L + "\t" + Long.MIN_VALUE + "\t" + Long.MAX_VALUE + "\n";
106 	// float
107 	table += "float\t\t" + 32 + "\t\t" + 3.14215926 + "\t" + Float.MIN_VALUE + "\t\t\t" + Float.MAX_VALUE + "\n";
108 	// double
109 	table += "double\t\t" + 64 + "\t\t" + 100e100 + "\t\t" + Double.MIN_VALUE + "\t\t" + Double.MAX_VALUE + "\n";
110 	table +=
111 	     "==============\t=============\t============\t=============\t\t=============\n";
112 
113 	System.out.println(table);
114 }
115 @ text
116 
117 <<Printing objects>>=
118 printTableOfNumbers();
119 @ text
120 
121 <<XOR table>>=
122 public static void truthTable() {
123   String table =
124           "  A   \t   B   \t A XOR B\n" +
125           "======\t=======\t========\n" +
126           false + "\t" + false + "\t" + (false ^ false) + "\n" +
127           false + "\t" + true  + "\t" + (false ^ true ) + "\n" +
128           true  + "\t" + false + "\t" + (true  ^ false) + "\n" +
129           true  + "\t" + true  + "\t" + (true  ^ true ) + "\n" +
130          "======\t=======\t========\n";
131   System.out.println(table);
132 }
133 @ text
134 
135 <<Printing objects>>=
136 truthTable();
137 @ text
138 
139 <<simple cypher>>=
140 public static String simpleCypher(String plaintext) {
141    char [] letters = plaintext.toCharArray();
142    String cypherText = "";
143    for (int i = 0; i < plaintext.length(); i ++) {
144      char letter = plaintext.charAt(i);
145 	 letter += 5;
146 	 cypherText += letter;
147    }
148    return cypherText;
149 }
150 @ text
151 
152 <<Printing objects>>=
153 System.out.println(simpleCypher("Now is the time for all good men to come to the aid of the party"));
154 @ text
155 
156 <<PrintingObjects.java>>=
157 <<include a selection of classes from the API>>
158 
159 public class PrintingObjects {
160 	public static void main (String[] args) {
161 	  <<Printing objects>>
162 	}
163 
164 	<<print table of numbers>>
165 	<<XOR table>>
166 	<<simple cypher>>
167 }
168 @ text
169 
170 @ text
171 
172 @ text
173 
174 <<Declare the primitives>>=
175 boolean flag = false;
176 char c = 'A';
177 byte b = (byte)127;
178 short s = (short)32767;
179 int i  = 10000000;
180 long l = 1000000000000L;
181 float f = 3.1415926F;
182 double d = 1.0e99;
183 @ text
184 
185 <<Wrap the primitives and add to an array list>>=
186 ArrayList primitives = new ArrayList();
187 Boolean wflag = new Boolean(flag); primitives.add(wflag);
188 Character wc = new Character(c); primitives.add(wc);
189 Byte wb = new Byte(b); primitives.add(wb);
190 Short ws = new Short(s); primitives.add(ws);
191 Integer wi = new Integer(i); primitives.add(wi);
192 Long wl = new Long(l); primitives.add(wl);
193 Float wf = new Float(f); primitives.add(wf);
194 Double wd = new Double(d); primitives.add(wd);
195 @ text
196 
197 <<Test primitive to string conversion>>=
198 for (int primitive = 0; primitive < primitives.size(); primitive++) {
199   Object wrapper = primitives.get(primitive);
200   System.out.println("Testing toString for " + wrapper.getClass());
201   <<get result of toString>>
202   <<get result of automatic string coercion>>
203   <<compare results>>
204 }
205 @ text
206 
207 <<get result of toString>>=
208 String stringFromWrapper = wrapper.toString();
209 @ text
210 
211 <<get result of automatic string coercion>>=
212 String coercedFromValueOfPrimitive = coerceWrappedPrimitiveValueToString(wrapper);
213 @ text
214 
215 <<compare results>>=
216 assert stringFromWrapper.equals(coercedFromValueOfPrimitive);
217 @ text
218 
219 <<define a method to coerce a primitive to a string>>=
220 static String coerceWrappedPrimitiveValueToString(Object o) {
221    <<process according to type of wrapper object>>
222 }
223 @ text
224 
225 <<process according to type of wrapper object>>=
226 if (o instanceof Boolean) {
227   <<return value of Boolean coerced to String>>
228 }
229 else if (o instanceof Character) {
230   <<return value of Character coerced to String>>
231 }
232 else if (o instanceof Byte) {
233   <<return value of Byte coerced to String>>
234 }
235 else if (o instanceof Short) {
236   <<return value of Short coerced to String>>
237 }
238 else if (o instanceof Integer) {
239   <<return value of Integer coerced to String>>
240 }
241 else if (o instanceof Long) {
242   <<return value of Long coerced to String>>
243 }
244 else if (o instanceof Float) {
245   <<return value of Float coerced to String>>
246 }
247 else if (o instanceof Double) {
248   <<return value of Double coerced to String>>
249 }
250 else {
251   <<unexpected class: return default coercion>>
252 }
253 @ text
254 
255 <<return value of Long coerced to String>>=
256 long l = ((Long)o).longValue();
257 return "" + l;
258 @ text
259 
260 <<return value of Boolean coerced to String>>=
261 boolean b = ((Boolean)o).booleanValue();
262 return "" + b;
263 @ text
264 
265 <<return value of Character coerced to String>>=
266 char c = ((Character)o).charValue();
267 return "" + c;
268 @ text
269 
270 <<return value of Byte coerced to String>>=
271 byte aByte = ((Byte)o).byteValue();
272 return "" + aByte;
273 @ text
274 
275 <<return value of Short coerced to String>>=
276 short s = ((Short)o).shortValue();
277 return "" + s;
278 @ text
279 
280 <<return value of Integer coerced to String>>=
281 int i = ((Integer)o).intValue();
282 return "" + i;
283 @ text
284 
285 <<return value of Float coerced to String>>=
286 float f = ((Float)o).floatValue();
287 return "" + f;
288 @ text
289 
290 <<return value of Double coerced to String>>=
291 double d = ((Double)o).doubleValue();
292 return "" + d;
293 @ text
294 
295 <<unexpected class: return default coercion>>=
296 return "" + o;
297 @ text
298 
299 <<ConvertPrimitivesToStrings.java>>=
300 import java.util.ArrayList;
301 
302 public class ConvertPrimitivesToStrings {
303 
304   public static void main (String [] args) {
305      System.out.println("Demonstrating that Java's built-in support for converting primitives\n" +
306         "to Strings relies on the toString method");
307      <<Declare the primitives>>
308 
309      <<Wrap the primitives and add to an array list>>
310 
311      <<Test primitive to string conversion>>
312   }
313 
314   <<define a method to coerce a primitive to a string>>
315 
316 }
317 @ text
318 


hijacker
hijacker
hijacker
hijacker

PrintingObjects.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Convert_Object_to_String_(Java)?oldid=15740
14 */
15 
16 
17 
18 public class PrintingObjects {
19 	public static void main (String[] args) {
20 	  Object o = new Object();
21 	  System.out.println("Object printed with toString: " + o);
22 	  String objectAsString = "" + o;
23 	  System.out.println("Object as a string literal: " + objectAsString);
24 	  assert objectAsString.equals(o.toString());
25 	  printTableOfNumbers();
26 	  truthTable();
27 	  System.out.println(simpleCypher("Now is the time for all good men to come to the aid of the party"));
28 	}
29 
30 	public static void printTableOfNumbers() {
31 	    String table = "Table of the Java Numbers\n" +
32 			 "Primitive Type\tSize in Bits\tTypical Value\tMinimum Value\t\tMaximum Value\n" +
33 			 "==============\t=============\t============\t=============\t\t=============\n";
34 		// byte
35 		table += "byte\t\t" + 8 + "\t\t" + (byte)5 + "\t\t" + Byte.MIN_VALUE + "\t\t\t" + Byte.MAX_VALUE + "\n";
36 		// short
37 		table += "short\t\t" + 16 + "\t\t" + (short)1024 + "\t\t" + Short.MIN_VALUE + "\t\t\t" + Short.MAX_VALUE + "\n";
38 		// int
39 		table += "int\t\t" + 32 + "\t\t" + 65536 + "\t\t" + Integer.MIN_VALUE + "\t\t" + Integer.MAX_VALUE + "\n";
40 		// long
41 		table += "long\t\t" + 64 + "\t\t" + 1000000000L + "\t" + Long.MIN_VALUE + "\t" + Long.MAX_VALUE + "\n";
42 		// float
43 		table += "float\t\t" + 32 + "\t\t" + 3.14215926 + "\t" + Float.MIN_VALUE + "\t\t\t" + Float.MAX_VALUE + "\n";
44 		// double
45 		table += "double\t\t" + 64 + "\t\t" + 100e100 + "\t\t" + Double.MIN_VALUE + "\t\t" + Double.MAX_VALUE + "\n";
46 		table +=
47 		     "==============\t=============\t============\t=============\t\t=============\n";
48 
49 		System.out.println(table);
50 	}
51 	public static void truthTable() {
52 	  String table =
53 	          "  A   \t   B   \t A XOR B\n" +
54 	          "======\t=======\t========\n" +
55 	          false + "\t" + false + "\t" + (false ^ false) + "\n" +
56 	          false + "\t" + true  + "\t" + (false ^ true ) + "\n" +
57 	          true  + "\t" + false + "\t" + (true  ^ false) + "\n" +
58 	          true  + "\t" + true  + "\t" + (true  ^ true ) + "\n" +
59 	         "======\t=======\t========\n";
60 	  System.out.println(table);
61 	}
62 	public static String simpleCypher(String plaintext) {
63 	   char [] letters = plaintext.toCharArray();
64 	   String cypherText = "";
65 	   for (int i = 0; i < plaintext.length(); i ++) {
66 	     char letter = plaintext.charAt(i);
67 		 letter += 5;
68 		 cypherText += letter;
69 	   }
70 	   return cypherText;
71 	}
72 }


hijacker
hijacker
hijacker
hijacker

ConvertPrimitivesToStrings.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Convert_Object_to_String_(Java)?oldid=15740
14 */
15 
16 import java.util.ArrayList;
17 
18 public class ConvertPrimitivesToStrings {
19 
20   public static void main (String [] args) {
21      System.out.println("Demonstrating that Java's built-in support for converting primitives\n" +
22         "to Strings relies on the toString method");
23      boolean flag = false;
24      char c = 'A';
25      byte b = (byte)127;
26      short s = (short)32767;
27      int i  = 10000000;
28      long l = 1000000000000L;
29      float f = 3.1415926F;
30      double d = 1.0e99;
31 
32      ArrayList primitives = new ArrayList();
33      Boolean wflag = new Boolean(flag); primitives.add(wflag);
34      Character wc = new Character(c); primitives.add(wc);
35      Byte wb = new Byte(b); primitives.add(wb);
36      Short ws = new Short(s); primitives.add(ws);
37      Integer wi = new Integer(i); primitives.add(wi);
38      Long wl = new Long(l); primitives.add(wl);
39      Float wf = new Float(f); primitives.add(wf);
40      Double wd = new Double(d); primitives.add(wd);
41 
42      for (int primitive = 0; primitive < primitives.size(); primitive++) {
43        Object wrapper = primitives.get(primitive);
44        System.out.println("Testing toString for " + wrapper.getClass());
45        String stringFromWrapper = wrapper.toString();
46        String coercedFromValueOfPrimitive = coerceWrappedPrimitiveValueToString(wrapper);
47        assert stringFromWrapper.equals(coercedFromValueOfPrimitive);
48      }
49   }
50 
51   static String coerceWrappedPrimitiveValueToString(Object o) {
52      if (o instanceof Boolean) {
53        boolean b = ((Boolean)o).booleanValue();
54        return "" + b;
55      }
56      else if (o instanceof Character) {
57        char c = ((Character)o).charValue();
58        return "" + c;
59      }
60      else if (o instanceof Byte) {
61        byte aByte = ((Byte)o).byteValue();
62        return "" + aByte;
63      }
64      else if (o instanceof Short) {
65        short s = ((Short)o).shortValue();
66        return "" + s;
67      }
68      else if (o instanceof Integer) {
69        int i = ((Integer)o).intValue();
70        return "" + i;
71      }
72      else if (o instanceof Long) {
73        long l = ((Long)o).longValue();
74        return "" + l;
75      }
76      else if (o instanceof Float) {
77        float f = ((Float)o).floatValue();
78        return "" + f;
79      }
80      else if (o instanceof Double) {
81        double d = ((Double)o).doubleValue();
82        return "" + d;
83      }
84      else {
85        return "" + o;
86      }
87   }
88 
89 }


hijacker
hijacker
hijacker
hijacker

StringLiterals.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Convert_Object_to_String_(Java)?oldid=15740
14 */
15 
16 
17 public class StringLiterals {
18 
19   public static void main (String [] args) {
20      System.out.println("Demonstrating that Java's built-in support for string literals\n" +
21         "relies on the toString method and string concatenation");
22 
23      System.out.println("Proof that 1 + 2 = 3");
24      System.out.println("1 + 2 = " + (1 + 2));
25 
26 
27      String literal = new String("Proof that 1 + 2 = 3");
28      String arg0 = new String("1 + 2 = ");
29      String arg1 = new Integer(1 + 2).toString();
30      String arg = arg0 + arg1;
31      System.out.println(literal.toString());
32      System.out.println(arg.toString());
33 
34      assert ("Proof that 1 + 2 = 3").equals(literal.toString());
35      assert ("1 + 2 = " + (1 + 2)).equals(arg.toString());
36 
37      System.out.println("Proof that sometimes 1 + 2 does not make 3");
38      System.out.println("1 + 2 = " + 1 + 2);
39      System.out.println(new String("Proof that sometimes 1 + 2 does not make 3").toString());
40      System.out.println((new String("1 + 2 = ").toString()) + (new Integer(1).toString()) + (new Integer(2).toString()));
41 
42      assert ("1 + 2 = " + 1 + 2).equals("1 + 2 = 12");
43 
44   }
45 
46 }


hijacker
hijacker
hijacker
hijacker

noweb.log

1 undefined chunk name: <<include a selection of classes from the API>>