• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

please explain me the output of the following programs

 
kanna kesavan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Stefan Willi
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12203
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic