Dose java have the concept of scalar context as perl?

J

Jack Dowson

Hello Everyone:
I'm new to java.I'm now confused by the output of the following two
examples:

The first example:
import java.util.*;
class UtilCalender{
public static void main(String[] args){
Calendar c = Calendar.getInstance();
System.out.println("current date: ");
System.out.println("Year: " +c.get(c.YEAR));
System.out.println("Month: " + (c.get(c.MONTH)+1));
System.out.println("Day: " + c.get(c.DAY_OF_MONTH));
}
}
And the result is:
current date:
Year: 2007
Month: 5
Day: 1

The second example:
import java.util.*;
class UtilCalender1{
public static void main(String[] args){
Calendar c = Calendar.getInstance();
System.out.println("current date: ");
System.out.println(c.get(c.YEAR) + (c.get(c.MONTH)+1)
+c.get(c.DAY_OF_MONTH));
}
}
And the result is:
current date:
2013

What leads to the different output?
It can be easily interpreted in perl as different scalar context.Then
what's the reason in java?

Any reply will greatly be appreciated!
 
C

Chris Dollin

Jack said:
Hello Everyone:
I'm new to java.I'm now confused by the output of the following two
examples:

The first example:
import java.util.*;
class UtilCalender{
public static void main(String[] args){
Calendar c = Calendar.getInstance();
System.out.println("current date: ");
System.out.println("Year: " +c.get(c.YEAR));
System.out.println("Month: " + (c.get(c.MONTH)+1));
System.out.println("Day: " + c.get(c.DAY_OF_MONTH));
}
}
And the result is:
current date:
Year: 2007
Month: 5
Day: 1

The second example:
import java.util.*;
class UtilCalender1{
public static void main(String[] args){
Calendar c = Calendar.getInstance();
System.out.println("current date: ");
System.out.println(c.get(c.YEAR) + (c.get(c.MONTH)+1)
+c.get(c.DAY_OF_MONTH));
}
}
And the result is:
current date:
2013

What leads to the different output?

`c.get()` is returning integers, which your second example adds together
before printing. There are multiple `println`s, distinguished by the
compile-time type of their argument; the one with an integer argument
prints integers in the usual way. In your first example, the `+` is
adding strings to things by converting the things to strings (someone
please write the tune for this); `+` has a somewhat horrible overloading
to allow this.

--
"It was the first really clever thing the King had said that day."
/Alice in Wonderland/

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top