Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^66) | Java Syntax and Semantics, Classes, and Objects
A synonym for the term callis invoke. Saying that a method is invoked is another way of
saying that it is called.


printand printlnMethods Java provides an object that represents an output device—by de-


fault, the screen. We can send messages to this object, asking it to print something on the
screen. The name of the object is System.outand the messages that we can send (the meth-
ods that we can apply) are printand println. For example,

System.out.print(“Susy”+ “ “ + “Sunshine”);

prints

Susy Sunshine

in a window on the screen. There are several things to notice about this statement. The
method is invoked (the message sent) by placing the method name next to the object name
with a dot in between. The “something” to be printed is a string expression that serves as an
argument to the method. Notice that the string appears within the parentheses. What do you
think the next code fragment prints?

System.out.print(“Susy”);
System.out.print(“ “);
System.out.print(“Sunshine”);

If you said that the two code fragments print the same thing, you would be correct. Successive
messages sent via the printmethod print the strings next to each other on the same line. If
you want to go to the next line after the string is printed, you use the printlnmethod. For ex-
ample, the code fragment

System.out.println(“Susy”);
System.out.println(“ “);
System.out.println(“Sunshine”);

prints

Susy

Sunshine

Note that theprintlnmethod does not go to the next line until afterthe string is printed. The
second line contains two blanks—it is not the empty string. We can print variables as well
as literals. For example,

String myName = “Susy Sunshine”;
System.out.println(myName);
Free download pdf