2.11.1: Reading and Printing a String Java

Chapter ii  Variables and types

2.1  More than printing

Y'all can put as many statements as you desire in main; for example, to print more than i line:

class Hullo { // Generates some simple output. public static void main(String[] args) { Arrangement.out.println("Hello, world."); // impress one line Organisation.out.println("How are you?"); // print another } }

As this example demonstrates, y'all tin can put comments at the end of a line, as well as on a line by themselves.

The phrases that appear in quotation marks are called strings, considering they are made up of a sequence (string) of characters. Strings can incorporate any combination of letters, numbers, punctuation marks, and other special characters.

println is short for "print line," because after each line it adds a special character, called a newline, that moves the cursor to the adjacent line of the display. The side by side fourth dimension println is invoked, the new text appears on the side by side line.

To display the output from multiple print statements all on one line, use print:

course How-do-you-do { // Generates some unproblematic output. public static void main(Cord[] args) { System.out.print("Goodbye, "); System.out.println("fell globe!"); } }

The output appears on a single line as Cheerio, barbarous globe!. In that location is a space betwixt the word "Farewell" and the second quotation mark. This infinite appears in the output, so information technology affects the behavior of the plan.

Spaces that announced outside of quotation marks generally practice not touch the behavior of the program. For case, I could have written:

class How-do-you-do { public static void main(Cord[] args) { Arrangement.out.print("Goodbye, "); System.out.println("vicious world!"); } }

This program would compile and run just as well every bit the original. The breaks at the ends of lines (newlines) practice non affect the program's behavior either, then I could have written:

class Hullo { public static void main(String[] args) { System.out.print("Goodbye, "); System.out.println ("cruel world!");}}

That would work, also, but the program is getting harder and harder to read. Newlines and spaces are useful for organizing your program visually, making information technology easier to read the program and locate errors.

two.2  Variables

1 of the most powerful features of a programming language is the ability to manipulate variables. A variable is a named location that stores a value. Values are things that can be printed, stored and (as we'll see after) operated on. The strings we take been printing ("Hello, World.", "Good day, ", etc.) are values.

To shop a value, yous take to create a variable. Since the values nosotros want to store are strings, we declare that the new variable is a cord:

String bob;

This argument is a declaration, because information technology declares that the variable named bob has the type Cord. Each variable has a blazon that determines what kind of values it can store. For example, the int blazon can store integers, and the String type tin store strings.

Some types begin with a uppercase letter of the alphabet and some with lower-example. Nosotros will learn the significance of this distinction later, just for now you lot should accept intendance to become it right. There is no such type as Int or string, and the compiler volition object if y'all try to make one upwardly.

To create an integer variable, the syntax is int bob;, where bob is the arbitrary proper noun you fabricated up for the variable. In general, you volition want to brand up variable names that indicate what yous plan to do with the variable. For example, if you saw these variable declarations:

String firstName; String lastName; int hour, infinitesimal;

you lot could guess what values would be stored in them. This case likewise demonstrates the syntax for declaring multiple variables with the same type: hour and 2d are both integers (int type).

2.iii  Assignment

Now that we accept created variables, nosotros want to shop values. Nosotros do that with an assignment statement.

bob = "Hello."; // give bob the value "Hello." 60 minutes = xi; // assign the value 11 to hour minute = 59; // set minute to 59

This instance shows three assignments, and the comments prove 3 different ways people sometimes talk almost assignment statements. The vocabulary can exist disruptive here, but the idea is straightforward:

  • When you declare a variable, you create a named storage location.
  • When yous make an assignment to a variable, you give it a value.

A common way to stand for variables on paper is to draw a box with the proper name of the variable on the outside and the value of the variable on the inside. This figure shows the effect of the three assignment statements:

As a general rule, a variable has to have the same blazon as the value you assign information technology. You cannot store a String in infinitesimal or an integer in bob.

On the other mitt, that rule can be confusing, because there are many ways that you can convert values from i type to another, and Java sometimes converts things automatically. For now you should remember the full general rule, and we'll talk about exceptions later.

Another source of confusion is that some strings look similar integers, simply they are not. For example, bob tin can incorporate the cord "123", which is fabricated up of the characters 1, two and 3, but that is not the same thing equally the number 123.

bob = "123"; // legal bob = 123; // not legal

2.4  Printing variables

You can print the value of a variable using println or print:

course Hello { public static void main(String[] args) { String firstLine; firstLine = "Hello, over again!"; System.out.println(firstLine); } }

This program creates a variable named firstLine, assigns it the value "Hello, again!" then prints that value. When we talk almost "printing a variable," nosotros mean printing the value of the variable. To print the proper noun of a variable, you have to put information technology in quotes. For example: Organization.out.println("firstLine");

For case, you can write

String firstLine; firstLine = "Hello, again!"; Organization.out.print("The value of firstLine is "); System.out.println(firstLine);

The output of this program is

The value of firstLine is Hello, again!

I am happy to report that the syntax for press a variable is the same regardless of the variable's type.

int hour, minute; hr = xi; minute = 59; Arrangement.out.print("The electric current fourth dimension is "); Organization.out.print(hour); System.out.print(":"); Organization.out.print(minute); System.out.println(".");

The output of this program is The electric current time is 11:59.

WARNING: To put multiple values on the same line, is common to apply several print statements followed by a println. But you lot have to call up the println at the end. In many environments, the output from impress is stored without being displayed until println is invoked, at which point the entire line is displayed at once. If you omit println, the program may end without displaying the stored output!

2.v  Keywords

A few sections agone, I said that you tin brand upward any name you want for your variables, simply that's non quite true. In that location are certain words that are reserved in Coffee because they are used past the compiler to parse the construction of your plan, and if you employ them equally variable names, it will get dislocated. These words, chosen keywords, include public, class, void, int, and many more than.

The complete list is bachelor at http://download.oracle.com/javase/tutorial/coffee/nutsandbolts/_keywords.html. This site, provided by Oracle, includes Coffee documentation I refer to throughout the book.

Rather than memorize the listing, I suggest you lot take reward of a characteristic provided in many Java development environments: code highlighting. Every bit you blazon, parts of your programme should appear in different colors. For example, keywords might be blue, strings red, and other code blackness. If you blazon a variable proper noun and it turns bluish, lookout out! Y'all might become some strange beliefs from the compiler.

2.half dozen  Operators

Operators are symbols used to represent computations similar addition and multiplication. Most operators in Java do what you wait them to do because they are common mathematical symbols. For case, the operator for improver is +. Subtraction is -, multiplication is *, and division is /.

1+ane 60 minutes-1 hour*60 + minute minute/threescore

Expressions can incorporate both variable names and numbers. Variables are replaced with their values earlier the computation is performed.

Improver, subtraction and multiplication all do what yous expect, just you might be surprised past division. For example, this program:

int hour, minute; hour = 11; infinitesimal = 59; System.out.print("Number of minutes since midnight: "); System.out.println(hour*threescore + minute); System.out.print("Fraction of the hour that has passed: "); Organization.out.println(minute/60);

generates this output:

Number of minutes since midnight: 719 Fraction of the hour that has passed: 0        

The first line is expected, simply the 2d line is odd. The value of minute is 59, and 59 divided by threescore is 0.98333, not 0. The problem is that Java is performing integer division.

When both operands are integers (operands are the things operators operate on), the result is likewise an integer, and past convention integer division always rounds down, even in cases like this where the next integer is so shut.

An alternative is to summate a pct rather than a fraction:

System.out.print("Pct of the hour that has passed: "); System.out.println(minute*100/60);

The result is:

Percentage of the hour that has passed: 98        

Again the issue is rounded downward, merely at least now the answer is approximately correct. To get a more accurate reply, we tin can employ a unlike type of variable, called floating-betoken, that can store fractional values. Nosotros'll get to that in the next affiliate.

2.7  Order of operations

When more than 1 operator appears in an expression, the guild of evaluation depends on the rules of precedence. A complete explanation of precedence can become complicated, but but to go you started:

  • Multiplication and partition happen earlier addition and subtraction. So 2*iii-one yields 5, not iv, and 2/three-1 yields -1, non ane (think that in integer division 2/iii is 0).
  • If the operators have the aforementioned precedence they are evaluated from left to correct. Then in the expression minute*100/60, the multiplication happens commencement, yielding 5900/threescore, which in plow yields 98. If the operations had gone from right to left, the result would be 59*i which is 59, which is incorrect.
  • Any time you want to override the rules of precedence (or you are non sure what they are) yous can use parentheses. Expressions in parentheses are evaluated start, and then 2 *(iii-1) is iv. You lot tin can also apply parentheses to make an expression easier to read, as in (minute * 100) / 60, fifty-fifty though it doesn't alter the upshot.

2.8  Operators for Strings

In full general you lot cannot perform mathematical operations on Strings, even if the strings look similar numbers. The post-obit are illegal (if we know that bob has type String)

bob - one         "Hello"/123      bob * "Hello"        

By the way, can you tell by looking at those expressions whether bob is an integer or a string? Nope. The only way to tell the blazon of a variable is to await at the identify where it is declared.

Interestingly, the + operator does work with Strings, but it might not do what you expect. For Stringsouth, the + operator represents concatenation, which means joining up the two operands by linking them cease-to-end. So "Hello, " + "earth." yields the cord "Hello, world." and bob + "ism" adds the suffix ism to the finish of any bob is, which is handy for naming new forms of bigotry.

2.nine  Composition

So far nosotros have looked at the elements of a programming language—variables, expressions, and statements—in isolation, without talking nigh how to combine them.

One of the most useful features of programming languages is their power to accept small edifice blocks and compose them. For instance, we know how to multiply numbers and we know how to print; it turns out nosotros can combine them in a single argument:

System.out.println(17 * 3);

Whatsoever expression involving numbers, strings and variables, tin can be used inside a print statement. We've already seen 1 example:

System.out.println(60 minutes*60 + minute);

But you can besides put arbitrary expressions on the right-hand side of an assignment statement:

int percentage; percentage = (minute * 100) / 60;

This ability may not seem impressive now, but we will see examples where composition expresses complex computations neatly and concisely.

WARNING: The left side of an consignment has to be a variable proper name, not an expression. That'south because the left side indicates the storage location where the outcome will go. Expressions do non correspond storage locations, only values. So the following is illegal: minute+1 = hour;.

2.10  Glossary

variable:
A named storage location for values. All variables accept a type, which is alleged when the variable is created.
value:
A number or string (or other affair to be named afterwards) that can be stored in a variable. Every value belongs to a blazon.
blazon:
A set of values. The type of a variable determines which values tin be stored there. The types we have seen are integers (int in Java) and strings (String in Java).
keyword:
A reserved word used past the compiler to parse programs. You cannot employ keywords, like public, class and void equally variable names.
annunciation:
A statement that creates a new variable and determines its type.
consignment:
A statement that assigns a value to a variable.
expression:
A combination of variables, operators and values that represents a single value. Expressions too take types, as determined by their operators and operands.
operator:
A symbol that represents a computation similar addition, multiplication or cord concatenation.
operand:
One of the values on which an operator operates.
precedence:
The social club in which operations are evaluated.
concatenate:
To join ii operands end-to-end.
composition:
The ability to combine simple expressions and statements into compound statements and expressions to correspond circuitous computations concisely.

two.11  Exercises

Exercise 1

If you lot are using this book in a class, you might enjoy this exercise: find a partner and play "Stump the Chump":

Starting time with a plan that compiles and runs correctly. One role player turns abroad while the other role player adds an error to the program. Then the get-go thespian tries to find and fix the error. You get two points if you lot find the error without compiling the plan, ane point if yous find it using the compiler, and your opponent gets a signal if you don't find it.

Practise two

  1. Create a new program named Date.coffee. Re-create or blazon in something like the "Hello, Earth" plan and make sure you can compile and run it.
  2. Following the example in Section two.4, write a plan that creates variables named mean solar day, date, month and twelvemonth. mean solar day will contain the day of the week and date will contain the day of the month. What blazon is each variable? Assign values to those variables that represent today'due south date.
  3. Print the value of each variable on a line past itself. This is an intermediate step that is useful for checking that everything is working so far.
  4. Modify the program then that it prints the date in standard American form: Sat, July 16, 2011.
  5. Modify the programme once more and then that the total output is:
                                      American format: Sat, July 16, 2011 European format: Saturday 16 July, 2011                              

The signal of this do is to apply string concatenation to brandish values with different types (int and String), and to practice developing programs gradually past adding a few statements at a time.

Do iii

  1. Create a new program called Time.java. From at present on, I won't remind y'all to start with a small, working plan, but you should.
  2. Following the example in Section 2.6, create variables named hour, minute and second, and assign them values that are roughly the current time. Use a 24-hour clock, and then that at 2pm the value of hr is fourteen.
  3. Brand the plan calculate and print the number of seconds since midnight.
  4. Make the program summate and impress the number of seconds remaining in the day.
  5. Make the programme calculate and impress the percentage of the day that has passed.
  6. Change the values of hour, minute and 2nd to reflect the current time (I presume that some fourth dimension has elapsed), and cheque to make sure that the program works correctly with dissimilar values.

The point of this exercise is to use some of the arithmetics operations, and to starting time thinking about compound entities similar the time of day that that are represented with multiple values. Too, you might run into problems computing percentages with ints, which is the motivation for floating point numbers in the next chapter.

HINT: yous may desire to use additional variables to hold values temporarily during the computation. Variables similar this, that are used in a computation only never printed, are sometimes called intermediate or temporary variables.

Similar this book?

Are you using one of our books in a form?

We'd like to know almost it. Delight consider filling out this short survey.

diamondaffir1942.blogspot.com

Source: https://greenteapress.com/thinkapjava/html/thinkjava004.html

0 Response to "2.11.1: Reading and Printing a String Java"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel