What is the exact difference between out.write() and out.print() - java

In my servlet I gave both out.print and out.write. but both prints in the browser.
What is the exact difference between these two and when to use out.print and out.write ?

The short answer is that out.write() explodes if you pass it a null:
String s = null;
out.print(s); // outputs the text "null"
out.write(s); // NullPointerException
The more complete answer is that out in servlets is a PrintWriter whose overloaded write() methods only accept a few basic types but do the work of outputting bytes to the underlying OutputStream.
The print() method is a convenience wrapper method that wraps calls to write() to provide custom behaviour for its numerous overloaded implementations. For example:
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
public void print(Object obj) {
write(String.valueOf(obj));
}
public void print(double d) {
write(String.valueOf(d));
}
etc for all the primitive types.

There are three major differences:
1) If you try to print a null value of a String with out.write() , It will throw NullPointerException while out.print() will simply print NULL as a string.
String name = null;
out.write(name); // NullPointerException
out.print(name); // 'Null' as text will be printed
2) out.print() can print Boolean values but out.write() can not.
boolean b = true;
out.write(b); // Compilation error
out.print(b); // 'true' will be printed
3) If you are using out.write(), you simply can not place arithmetic operation code but out.print() provides the support.
out.write(10+20); // No output will be displayed.
out.print(10+20); // Output '30' will be displayed.

PrintWriter:
public void write(String s)
Write a string. This method cannot be inherited from the Writer class
because it must suppress I/O exceptions.
print method has higher level of abstraction.
public void print(String s)
Print a string. If the argument is null then the string "null" is
printed. Otherwise, the string's characters are converted into bytes
according to the platform's default character encoding, and these
bytes are written in exactly the manner of the write(int) method.
Hope this helps.

The out variable in your case is most likely refers to a PrintWriter
Just compare the description of write...
public void write(String s)
Write a string. This method cannot be inherited from the Writer class because it must suppress I/O exceptions.
... with the description of println ...
public void println(String x)
Print a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
... and print ...
public void print(String s)
Print a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
All in all I'd say that the print methods work on a higher level of abstraction and is the one I prefer to work with when writing servlets.

PrintWriter's implementation communicates the difference better than javadoc
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}

First thing is you can't use javax.​servlet.​jsp.​JspWriter out in a servlet. It has to be used in a .jsp file, because out is a method local variable in _jspService(...) method of your .jsp file.
There is no difference in the purpose of using out.print() and out.write(). Both are used to write the String version of the given object to JspWriter's buffer.
However, JspWriter.print() is capable of taking many types of arguments than Writer.write().
JspWriter.print()
Object
String
boolean
char
char[]
double
float
int
long
Writer.write()
String
char
int

write() method only writes characters to stream(or console) but does not print, while print() method writes and print it on stream (or console).
System.out.write(97);
System.out.print('j');
first statement writes character 97 i.e 'a' on console but does not print, while second statement prints 'a' which is written already on stream and 'j' which is passed in print() method.

I simply know it as like this:
out.println() is method of javax.​servlet.​jsp.​JspWriter
out.write() is method of java.io.Writer

out.write(-) vs out.print(-)
One more difference is out.write(-)
method just write data or object to browser like a file. You can not write any statement like out.write(10*20); but we do this with out.print(10*20);

Related

Pass the result of Object.toString() and String.valueOf(Object) as the key in the HashMap caused different results [duplicate]

In Java, is there any difference between String.valueOf(Object) and Object.toString()?
Is there a specific code convention for these?
According to the Java documentation, String.valueOf() returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So there shouldn't really be a difference except for an additional method invocation.
Also, in the case of Object#toString, if the instance is null, a NullPointerException will be thrown, so arguably, it's less safe.
public static void main(String args[]) {
String str = null;
System.out.println(String.valueOf(str)); // This will print a String equal to "null"
System.out.println(str.toString()); // This will throw a NullPointerException
}
Differences between String.valueOf(Object) and Object.toString() are:
1) If string is null,
String.valueOf(Object) will return "null", whereas Object::toString() will throw a null pointer exception.
public static void main(String args[]){
String str = null;
System.out.println(String.valueOf(str)); // it will print null
System.out.println(str.toString()); // it will throw NullPointerException
}
2) Signature:
valueOf() method of String class is static. whereas toString() method of String class is non static.
The signature or syntax of string's valueOf() method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)
The signature or syntax of string's toString() method is given below:
public String toString()
In Java, is there any difference between String.valueOf(Object) and Object.toString()?
Yes. (And more so if you consider overloading!)
As the javadoc explains, String.valueOf((Object) null) will be treated as a special case by the valueOf method and the value "null" is returned. By contrast, null.toString() will just give you an NPE.
Overloading
It turns out that String.valueOf(null) (note the difference!) does give an NPE ... despite the javadoc. The real explanation1 is obscure:
There are a number of overloads of String.valueOf, but there are two that are relevant here: String.valueOf(Object) and String.valueOf(char[]).
In the expression String.valueOf(null), both of those overloads are applicable, since null is assignment compatible with any reference type.
When there are two or more applicable overloads, the JLS says that the overload for the most specific argument type is chosen.
Since char[] is a subtype of Object, it is more specific.
Therefore the String.valueOf(char[]) overload is called.
String.valueOf(char[]) throws an NPE if its argument is a null array. Unlike String.valueOf(Object), it doesn't treat null as a special case.
Another example illustrates the difference in the valueOf(char[]) overload even more clearly:
char[] abc = new char[]('a', 'b', 'c');
System.out.println(String.valueOf(abc)); // prints "abc"
System.out.println(abc.toString()); // prints "[C#...."
Is there a specific code convention for these?
No.
Use which ever is most appropriate to the requirements of the context in which you are using it. (Do you need the formatting to work for null?)
Note: that isn't a code convention. It is just common sense programming. It is more important that your code is correct than it is to follow some stylistic convention or "best practice" dogma2.
1 - You can confirm this by using javap -c to examine the code of a method that has a String.valueOf(null) call. Observe the overload that is used for the call.
2 - Please read "No Best Practices", and pass this reference on to the next person who tells you that it is "best practice" to do something in the programming or IT domains.
Personal opinion
Some developers acquire the (IMO) bad habit of "defending" against nulls. So you see lots of tests for nulls, and treating nulls as special cases. The idea seems to be prevent NPE from happening.
I think this is a bad idea. In particular, I think it is a bad idea if what you do when you find a null is to try to "make good" ... without consideration of why there was a null there.
In general, it is better to avoid the null being there in the first place ... unless the null has a very specific meaning in your application or API design. So, rather than avoiding the NPE with lots of defensive coding, it is better to let the NPE happen, and then track down and fix the source of the unexpected null that triggered the NPE.
So how does this apply here?
Well, if you think about it, using String.valueOf(obj) could be a way of "making good". That is to be avoided. If it is unexpected for obj to be null in the context, it is better to use obj.toString().
Most has already been mentioned by other answers, but I just add it for completeness:
Primitives don't have a .toString() as they are not an implementation of the Object-class, so only String.valueOf can be used.
String.valueOf will transform a given object that is null to the String "null", whereas .toString() will throw a NullPointerException.
The compiler will use String.valueOf by default when something like String s = "" + (...); is used. Which is why Object t = null; String s = "" + t; will result in the String "null", and not in a NPE. EDIT: Actually, it will use the StringBuilder.append, not String.valueOf. So ignore what I said here.
In addition to those, here is actually a use case where String.valueOf and .toString() have different results:
Let's say we have a generic method like this:
public static <T> T test(){
String str = "test";
return (T) str;
}
And we'll call it with an Integer type like this: Main.<Integer>test().
When we create a String with String.valueOf it works fine:
String s1 = String.valueOf(Main.<Integer>test());
System.out.println(s1);
This will output test to STDOUT.
With a .toString() however, it won't work:
String s2 = (Main.<Integer>test()).toString();
System.out.println(s2);
This will result in the following error:
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer
Try it online.
As for why, I can refer to this separated question and its answers. In short however:
When using .toString() it will first compile and evaluate the object, where the cast to T (which is an String to Integer cast in this case) will result in the ClassCastException.
When using String.valueOf it will see the generic T as Object during compilation and doesn't even care about it being an Integer. So it will cast an Object to Object (which the compiler just ignores). Then it will use String.valueOf(Object), resulting in a String as expected. So even though the String.valueOf(Object) will do a .toString() on the parameter internally, we've already skipped the cast and its treated like an Object, so we've avoided the ClassCastException that occurs with the usage of .toString().
Just thought it was worth mentioning this additional difference between String.valueOf and .toString() here as well.
The most important difference is the way they handle null String references.
String str = null;
System.out.println("String.valueOf gives : " + String.valueOf(str));//Prints null
System.out.println("String.toString gives : " + str.toString());//This would throw a NullPointerExeption
String.valueOf(Object) and Object.toString() are literally the same thing.
If you take a look at the implementation of String.valueOf(Object), you'll see that String.valueOf(Object) is basically just a null-safe invocation of toString() of the appropriate object:
Returns the string representation of the Object argument.
Parameters:
obj an Object.
Returns:
if the argument is null, then a string equal to "null";
otherwise, the value of obj.toString() is returned.
See also:
Object.toString()
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
When argument is null, the String.valueOf returns "null", but Object.toString throws NullPointerException, that's the only difference.
There is one more major difference between the two methods is when the object we are converting is an array.
When you convert an array using Object.toString() you will get some kind of garbage value(# followed by hashcode of array).
To get a human-readable toString(), you must use String.valueOf(char[]); plz note that this method works only for Array of type char. I would recommend using Arrays.toString(Object[]) for converting arrays to String.
Second difference is when the object is null, ValueOf() returns a String "null", while toString() will return null pointer exception.
String.valueOf() can be used with primitive types which do not have toString() methods.
I can't say exactly what the difference is but there appears to be a difference when operating at the byte level. In the following encryption scenario Object.toString() produced a value that couldn't be decrypted whereas String.valueOf() worked as intended ...
private static char[] base64Encode(byte[] bytes)
{
return Base64.encode(bytes);
}
private static String encrypt(String encrypt_this) throws GeneralSecurityException, UnsupportedEncodingException
{
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
//THIS FAILED when attempting to decrypt the password
//return base64Encode(pbeCipher.doFinal(encrypt_this.getBytes("UTF-8"))).toString();
//THIS WORKED
return String.valueOf(base64Encode(pbeCipher.doFinal(encrypt_this.getBytes("UTF-8"))));
}//end of encrypt()
The below shows the implementation for java.lang.String.valueOf as described in the source for jdk8u25. So as per my comment, there's no difference. It calls "Object.toString". For primitive types, it wraps it in its object form and calls "toString" on it.
See below:
/*
* Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
public static String valueOf(char data[]) {
return new String(data);
}
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
public static String copyValueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
public static String copyValueOf(char data[]) {
return new String(data);
}
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
public static String valueOf(char c) {
char data[] = {c};
return new String(data, true);
}
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String valueOf(long l) {
return Long.toString(l);
}
public static String valueOf(float f) {
return Float.toString(f);
}
public static String valueOf(double d) {
return Double.toString(d);
}

int value converted to Integer Wrapper class object with System.out.println?

This more of a clarity than a doubt. In the following :
int a = 10;
System.out.println(a);
What I conclude is that variable 'a' of the primitive type int is first converted to the Integer Wrapper class object and then toString method is invoked for that Integer object which returns the integer value in String form to the println method. Is my understanding correct? If not what is the correct explanation?
You're wrong. It can handle int, see the docs*:
public void println(int x)
* Always :)
If you check the type of System.out, you'll see it's a PrintStream. Read the docs.
Quote:
public void println(int x)
Prints an integer and then terminate the line. This method behaves
as though it invokes print(int) and then println().
Parameters:
x - The int to be printed.
So, no, no conversion to Integer is done. The int matches the signature of the above method exactly, so that method is called. What happens internally is unspecified, but it probably calls Integer.toString() directly, with out a conversion to Integer.
No i think it's not the way you explained.
System.out is a static reference of PrintStream class (present in java.io package) which has methods to print primitives directly!!!
To be precise, it actually uses the String.valueOf(int) method.
This is the source code, from PrintStream
/**
* Prints the string representation of the int {#code i} followed by a newline.
*/
public void println(int i) {
println(String.valueOf(i));
}

implicit toString() call in sysout - unexpected behavior [duplicate]

I was experimenting with toCharArray() and found some strange behavior.
Suppose private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
System.out.println(HEX_CHARS);
/* prints 0123456789abcdef */
System.out.println("this is HEX_CHARS "+HEX_CHARS);
/* prints [C#19821f */
Any theoretical reason behind this?
It is because the parameter to println is different in the two calls.
The first parameter is called with char[] and the second is called with a string, where HEX_CHARS is converted with a call to .toString().
The println() have an overriden method that accepts a charArray.
The first line calls the method
print(char[] s)
on the PrintStream which prints what you expect. The second one calls the method
print(String s)
Where is concatenating the string with the toString implementation of the array which is that ugly thing you get ([C#19821f).
Arrays are objects, and its toString methods returns
getClass().getName() + "#" + Integer.toHexString(hashCode())
In your case [C#19821f means char[] and #19821f is its hashcode in hex notation.
If you want to print values from that array use iteration or Arrays.toString method.
`System.out.println(Arrays.toString(HEX_CHARS));`
The strange output is the toString() of the char[] type. for some odd reason, java decided to have a useless default implementation of toString() on array types. try Arrays.toString(HEX_STRING) instead.

What happens when printing an object in java

class Data {
int a = 5;
}
class Main {
public static void main(String[] args) {
int b=5;
Data dObj = new Data();
System.out.println(dObj);
System.out.println(b);
}
}
I want to know what's happening when printing a object or number or string.
I ran the above code, I'm getting the result as "data#1ae73783" for System.out.println(dObj); and "5" for System.out.println(b);
Then I did debug to check whats really happening when printing a object, there was lot of parameter called in a debug mode(like classloader,theards)
I know for the first print the value represent class name followed by address. But don't know what's really happening in debug mode, for the 2nd print only variable assignment happened in the debug mode i.e b=5.
Please explain whats really happening?
You don't need a debugger to know what's happening. System.out is of type PrintStream. The javadoc of PrintStream.println(Object) says:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
The javadoc of String.valueOf(Object) says:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
And the javadoc of Object.toString() says:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Please explain whats really happening?
As other have told you, using System.out.println with an object will call to toString method on that object. If the class doesn't have it's own toString method, then it's a call to the super class's toString. If the super class call goes all the way back to java.lang.Object, the default toString method prints the name of the object's type (what class it is), followed by an # sign, and the memory location of the object--the hexidecimal address of where that object is stored in memory.
ClassName#MemoryLocation
when we print object of any class System.out.print() gives string of class name along with memory address of object (ClassName#MemoryAdress)
All objects inherit from java.lang.Object which has a default implementation of toString. If an object overrides this method then out.print (obj) will put something useful on the screen.
Primitive data types are handled by a different, much simpler implementation of println. The println method is overridden for every data type in addition to Object.
First, int isn't an Object. It's primitive type.
Second, when Class haven't overrived toString() method, toString() from Object class is invoked.
data dObj = new data() does not exist in the source code;
you want to print the string value of the object (Data), you have to override the toString method;
try this
public class Program {
public static void main(String[] args) {
Data data = new Data();
System.out.println(data);
}
}
class Data {
int a = 5;
#Override
public String toString() {
return String.valueOf(a);
}
}
In Addition to #JB Nizet answer,
To Provide our own string representation, we have to override toString() in our class which is highly recommended because
There are some classes in which toString() is overridden already to get the proper string representation.
Examle: String, StringBuffer, StringBuilder and all wrapper classes
Integer ob1 = new Integer("10");
String ob2 = new String("Doltan Roy");
StringBuffer ob3 = new StringBuffer("The Rock");
StringBuilder ob4 = new StringBuilder("The Joshua");
System.out.println(ob1);
System.out.println(ob2);
System.out.println(ob3);
System.out.println(ob4);
Output:
10
Doltan Roy
The Rock
The Joshua
Hope this would help!

Java Programming Help

im a bit confused on this and i dont know how to solve this question that i have been asked, id be grateful if you could assist me on this question, maybe try to tell me what needs to be done, and how. the question is:
Write a method called countChars which takes an InputStream as a parameter, reads the stream and returns the number of characters it contains as an int. Any IOExceptions which might occur in the method should be passed back to the method's caller.
Note that the method header should show that it is possible that an exception might occur.
i attempted this question with the following code:
public class countChars
{
public int countChars(int InputStream)
{
return InputStream;
}
}
and i get an error message saying :
Main.java:26: cannot find symbol
symbol : method countChars(java.io.InputStream)
location: class Main
s1 = "" + countChars(f1);
^
1 error
public class CounterUtility
{
public static Integer countChars(InputStream in)
{
Integer counter = 0;
/* your code here */
return counter;
}
}
s1 = CounterUtility.countChars(f1).toString();
You have a couple things mixed up. For one your function is going to take in an InputStream and return an int. You have your function set up to take in an int called InputStream and return an int.
InputStream has a function, read(), which loads the next character of the stream (or -1 if there are no remaining characters). You'll need to define an integer counter and then call read() as many times as it takes to get that response of -1. Once you see a -1 you know that you're at the end of the stream and you can return the counter (which will have a value equal to the number of characters).
//take in an InputStream object and return an int
public int countChars(InputStream input){
int counter = 0; //start counting at zero
while (input.read() != -1){
//as long as there are more characters, keep incrementing the counter
counter++; //add one to the counter
}
return counter; //return the result
}
I never attempted to compile the above code and I haven't written in Java since college, so there may be syntactical errors.
Your countChars method is inside of a class called countChars.
When you call the method, you need an instance of the class.
You need to make the method static, then change the call to countChars.countChars(f1).
The error is probably due to the fact that the countChars method was not successfully compiled. If you review the rest of the output of the compiler you'll probably see it complaining on the return statement. Replace the stub return, with return 0 and it should go through.
Besides, you should not use InputStream as variable name. Use is or something similar.
Furthermore, if the method should take an InputStream as argument, the signature should be
public int countChars(InputStream is) { ...
Seems like you may be compiling the wrong file. The code example you included does not contain the code from the error message. I therfore conclude that the compiler is not acting on the source file that you believe it is (assuming you have accurately copy/pasted the code you are using).
First things first: In Java, class names should always be capitalized.
Second, the code you are running is in the Main class. Your countChars method is in the countChars class. You need to create a countChars object to call it on, or make countChars a static method, which would be called via countChars.countChars(intHere).
Third, int InputStream would be an integer value with the name InputStream, not an InputStream object.
A few points. Generally it is considered good practice to Capitalize all Java Classes. You aren't forced to do so, but when you don't it makes readability much more difficult for the rest of the world.
So public class countChars becomes public class CountChars.
Second, you are attempting to call a method on an object, but you don't specify which object you want to use. Generally you can't use a method all by itself in object oriented programming, you must specify the class and then the method to call on the class. This is done one of two ways:
By creating an Object (instance of the class) and the calling the method on that Object, like so:
CountChars counter = new CountChars();
s1 = "" + counter.countChars(i);
By declaring the method to be static, which means it will be a method on the "Class" Object, CountChars. To call a static method, the class name is used, like so:
s1 = "" + CountChars.countChars(i);

Categories

Resources