aspose file tools*
The moose likes Java in General and the fly likes please explain me the output of the following programs Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "please explain me the output of the following programs" Watch "please explain me the output of the following programs" New topic
Author

please explain me the output of the following programs

kanna kesavan
Greenhorn

Joined: May 09, 2005
Posts: 6
please explain me the output of the following programs

1.
public class AQuestion
{
private int i = giveMeJ();
private int j = 10;

private int giveMeJ()
{
return j;
}

public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}

ans:0(zero)

2.if(" String ".trim() == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");
ans rints "not Equal:.
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
1. Member variables gets initialized only after the call to constructor is finished hence 0.
Try this it works.


2. Use .equals instead.
String.trim produces a new Object


Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
Stefan Willi
Ranch Hand

Joined: Mar 11, 2005
Posts: 47
The answer of your second question:
If you use the == Operator, then you compare the references of an Object, not there value.

after " String ".trim() you got a new reference to a String Object, which contains the value "String".

To compare the value of 2 Strings, you have to use equals() or equalsIgnoreCase().

Stefna
Stefan Willi
Ranch Hand

Joined: Mar 11, 2005
Posts: 47
Let me take one addition.

Don't be confused by the result of the following code

If you try to compare Strings in this manner, you have to know, that there are not two strings createt. Java uses a Literal-Pool and uses for the property first and second the same String-Object. So the references are the same and the == Operator would return TRUE.

Stefan
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

the trim() method will return a reference to a new object. In this case, it will refer to a newly created string with a value of "String".

in other words, you will end up with 3 String objects created. two in the string pool (with values of " String " and "String"), and a third created by the trim() call. since the == operator checks to see if we refer to the same object, we get a false.

if you had instead done



after being chastized for writing such an ugly test condition, you'd get a true (assuming i didn't make any typos).


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: please explain me the output of the following programs