java 211 – lecture 3  · web viewjava 211. strings, reading input . yosef mendelsohn. i....

23
Java 211 Strings, Reading Input Yosef Mendelsohn I. Strings The String data type is not one of the primitive data types (e.g. int, char, double, etc) that we have been discussing over the last couple of lcctures. They are in fact, objects (which you will better understand later in the course). This distinction will become important. For now, we will begin with some String fundamentals and then learn more about them as we learn about objects. The best way to describe a string is to give some examples: String s1 = "hello"; //a string of length=5 String s2 = "hello, Bob.. How are you? "; String s3 = "h"; //a string of length=1 String s4 = "123456"; //a string of digits – it is NOT a number) Notice that the data type String begins an upper case ‘S’. However: char c1 = ‘h’; if (c1 == s3) //error!!! – type mismatch int x = s4; //error – type mismatch Some commonly used methods that can be invoked by a string object include: - equals (returns a bool) - length (returns an int)

Upload: others

Post on 25-Jul-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

Java 211Strings, Reading Input

Yosef Mendelsohn

I. StringsThe String data type is not one of the primitive data types (e.g. int, char, double, etc) that we have been discussing over the last couple of lcctures. They are in fact, objects (which you will better understand later in the course). This distinction will become important. For now, we will begin with some String fundamentals and then learn more about them as we learn about objects.

The best way to describe a string is to give some examples:String s1 = "hello";//a string of length=5

String s2 = "hello, Bob.. How are you? ";

String s3 = "h"; //a string of length=1

String s4 = "123456";//a string of digits – it is NOT a number)

Notice that the data type String begins an upper case ‘S’.

However:char c1 = ‘h’;if (c1 == s3) //error!!! – type mismatchint x = s4; //error – type mismatch

Some commonly used methods that can be invoked by a string object include:- equals (returns a bool)- length (returns an int)- toLowerCase (returns a String)

The idea of an object invoking its own method may confuse you. Again, we will discuss this at a later point.

For now, we will concern ourselves with simply USING these methods. You will have to take my word on a few things for now. I will explain the reasoning behind them as we progress.

To compare two strings you can NOT use the == operator. The == operator works ONLY for primitive data types (eg to compare two variables of type int or double).

Page 2: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

Recall that strings are not primitive data types. So we need another way to compare two strings. Here is the an example of some code to compare two strings:

String s1 = "hello";String s2 = "goodbye";

To compare these two strings to see if they are identical, we would write:s1.equals(s2)

To use this inside an ‘if’ statement:if ( s1.equals(s2) ){ System.out.println("The strings are identical");}

Another example:

if ( s1.equals(“hello”) ){System.out.println("The string s1 holds the word hello. ");

}The ‘equals’ method is very important. Be sure that you are very comfortable with its basic usage.

Another very useful String method is called length() . Here it is in use:String s1 = "hello";int length = s1.length();System.out.println("The length of the string is: "

+ length );

Or:if ( s1.length() > 10 ){ System.out.println("The string s1 is longer than 10

characters. "); }

Notice the need for a pair of parentheses after the word length().

There are numerous other methods available to String objects that we will discuss in class. I will also show you how to look up others on your own.

ConcatenationThere is a special operator, represented by the ‘+’ sign, that can be used to concatenate two or more strings together. This is why you can have two strings inside a println

Page 3: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

statement joined by + that will then be represented as a single string. The second string is appended on to the end of the first string.

- Also, strings can be concatenated with numbers- If the two operators on both sides of a + are numbes, then addition is performed.

Otherwise, concatenation is performed. You can also control behavior by using brackets.

Here are a couple of examples of concatenation in action. You will find yourself concatenating strings often, and in many different ways.

String s1, s2, s3;s1 = "Hello";s2 = "How are you?"s3 = s1 + s2;//what is wrong with the resulting output???

//Better:s3 = s1 + ". " + s2;

As with numeric variables, a string can be ‘added’ (i.e. concatenated) to itself:String s = "hello";s = s+s;//what is the current value of s?

Escape SequencesSometimes we want to output special characters such as quotation marks or \ signs or newlines, etc. in our strings. Because these characters can interfere with our source code, we need a way of indicating to the compiler that these are special characters and must not be treated in their usual way. The technique is to precede these characters by a ‘\’ character. A partial list of escape sequences can be found in an appendix or by googling.

Examples include: \n newline \t tab \’ single quote \" double quote

For example:System.out.println("How are you?\nIam fine."); //on two lines

System.out.println("How are you?\tIam fine."); //tab in between

//putting several together:

Page 4: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

System.out.println("Bob said \"How y\'all doin\'\"");

Since we have established that Strings are objects of a class called ‘String’, lets take a quick look at some of the methods of that class by checking out the String API. (Yet again, to be discussed later…)

II. The Scanner classAs mentioned in lecture, one of the great advantages of a powerful and widely used programming language such as Java is the possibility to extend the language to add features. One glaring hole in earlier versions of Java (prior to SDK v.14) was an easy way to read input from the user. Fortunately, this has been remedied by a new library that includes a class called ‘Scanner’.

Again, because we do not understand classes and objects very well (or at all!) yet, for now you will have to simply get comfortable with the code as I demonstrate it to you. Again, as we progress, some of the things that may seem mysterious now will become clear.

Here is an example of some code to take input in from the user via the keyboard:Scanner console = new Scanner(System.in); //this line is required to use the Scanner class//it should be placed near the top of your method

int age;double gpa;String firstName;

System.out.println("How old are you?");age = console.nextInt();

System.out.println("What is your GPA?");gpa = console.nextDouble();

System.out.println("What is your name?");firstName = console.next();

Notice how the method attached to the word ‘input’ changes depending on the type of data we want to read. For example, if you are expecting the user to enter a double, you should use .nextDouble() . If you are expecting an int: nextInt(). A String: next() .

What would happen with the following:System.out.println("How many miles did you run?");miles = console.next();

Page 5: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

Answer: The method ‘next()’ returns a String. If you put a string into a variable of type double you have a type mismatch.

One note: The word ‘console’ is simply an identifier. You could choose any identifier that you like such as:

Scanner keyboardInput = new Scanner(System.in);However, the book uses ‘console’, so I’ll use it here as well.

As with Strings, the Scanner class is another class that we will be using throughout the course, so you should become familiar with it now.

There is one thing that you need to do to use the Scanner class: you need to “import” the package that holds it. We’ll talk more about this later, but for the moment, whenever you want to use the Scanner class, include the following line at the very top of your program (even before the class declaration):

import java.util.Scanner;

Here is a link to the complete program using the code we’ve just discussed.

III. if-elseLast lecture we talked about ‘if’ statements. If you have a lone ‘if’ statement, the program’s flow begins by evaluating the conditional. If the conditional evaluates to ‘true’, flow enters the body of the ‘if’ block. If the conditional evalutes to ‘false’, flow simply skips the ‘if’ block by jumping ahead to the closing brace ‘}’ .

However, there may be situations where you want to have your program do something even when the conditional is false. The easiest way to demonstrate this is by an (admittedly frivolous) example:

System.out.println("What is your GPA?");gpa = console.nextDouble();

if ( gpa > 3.5 ){ System.out.println("You're a good student!");}else{ System.out.println("Better work harder!");}

In other words, if the conditional turns out to be false, flow will jump directly to the ‘else’ block and execute it. If the conditional is true, flow will execute the ‘if’ block, and will then skip the ‘else’ block by jumping to its closing brace.

Page 6: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

‘Else’ statements are optional. Whether or not you include one really depends on the logic of your program. Most of the time you will have no problem deciding whether or not your code needs to have an ‘else’ block.

If and else-if statements:There will also be situations where you want your code to evaluate several different possibilities. Again, this is best explained by an example. Let’s write some code that prompts the user for their percentage score for the course. The code will then determine the appropriate letter grade.

int percentGrade;System.out.println("What was your % for the course?");percentGrade = console.nextInt();

if ( percentGrade >= 90 ){ System.out.println("You receive an A.");}else if ( percentGrade >= 80 ){ System.out.println("You receive a B.");}else if ( percentGrade >= 70 ){ System.out.println("You receive a C. ");}else if ( percentGrade >= 60 ){ System.out.println("You receive a D.");}else //user’s score is less than 60{ System.out.println("You receive an F.");}

The moment flow finds a conditional that is true, it will execute the corresponding block. It will then skip all the way to the end of the if / else-if statements – regardless of how many of them are present.

A common mistake: Many beginniners tend to write ‘if else’ instead of ‘else if’. The proper syntax is: else if ( conditional ) …

One other thing:Notice how the last ‘else’ does not have to be an ‘else if’. The reason is that if flow makes it that far in the if / else-if statements, then the user MUST have scored less than 60. It would certainly be possible to write:

else if ( percentGrade < 90 )

Page 7: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

for the last situation, but it isn’t necessary. Either version is fine.What do you think? (An argument could be made that having a final else if is preferable since it makes the code a bit more clear).

Page 8: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

METHODS

MethodsIt is surely no surprise to you that computer programs can be very long and complex. For this reason, there are many ways of organizing programs. One of the key ways to organize a program is to divide it into specific tasks. Every task (and often, individual parts of a given task) may be included in its own little section called a method. (Some people and programming languages will also call them functions. There are subtle distinctions, but we won’t worry about them here. For now, you may hear me use the terms interchangably).

Methods have another valuable use: They are a great way to allow you to repeat code over and over again. For example, suppose you find that in a program you want to ask the user for a number and then determine the square root of that number. Suppose also that you will want to do this over and over again in your program. This is a great time to use a method. In other words, whenever you want to do this little bit of functionality, you don’t have to go back and re-type (or copy-paste) the code into your program. You can simply invoke the method that you have already written.

Don’t confuse methods with loops. A loop repeats code over and over again, but only at the current location in a program. A method allows your to repeat code, but at any location in the program.

A method is a collection of programming statements that is given a specific name. When you “invoke” a method (by giving its name), you are transferring the flow of control to that group of statements. When the method has completed, flow returns to the location from which the method was called.

Pre-Defined MethodsAre methods that have been pre-created for us by the people who created Java. For example, the length() method used with String objects is a pre-defined method. So are all of those methods seen in the String API. Let’s look at a few of those methods now:String s = “Hello DePaul!”;System.out.println( s.charAt(0) ); //outputs an ‘H’System.out.println( s.charAt(12) ); //outputs a ‘!’System.out.println( s.charAt(13) ); //error – there is no 13th index!System.out.println( s. charAt (s.length()-1) ); //okay too!

String s1 = “Hello DePaul!”;String s2 = “Hello DePaul!”;

if ( s1.equals(s2) ) //returns trueif ( s1.equals(“Hello DePaul!”)) //also returns true

Page 9: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

If you look at a class called ‘Math’, you will see numerous pre-defined methods that are available to us for basic mathematical functionality.

For example, to calculate a square root, there is a method called ‘sqrt’ that accepts any numeric data-type and returns it’s square root. Here is the “header” of that method:

static double sqrt (double a)This tells you that the method accepts one argument of type double. By reading the information in the API you can also see that the method returns a double corresponding to the square root of ‘a’.

Therefore, you should be able to invoke the method by typing something like:double x = sqrt(9.0); //x will be set to 3.0

Right? Actually, WRONG!

The problem is one of context. Consider where you would see this line of code:public class Test{ public static void main (String[] args) {

double x = sqrt(3.0); //will give a ‘No such method’ errorSystem.out.println(x);

}}

Using our favorite algorithm we say: “The system looks for a method called ‘sqrt’ that accepts ‘1’ argument(s) of type ‘double’.” Will it find such a method?

No… Why? Because the method lives in a completely different class.

In other words, we somehow need to indicate to the system to look for the ‘sqrt’ method in the Math class. How do we do this? By typing: Math.sqrt(…) //note the dot!

By changing the line to read: double x = Math.sqrt(9.0);

we tell the system where to go to look for the sqrt method.

Note: This method of invoking methods (ie: preceding the method name by the class name) will NOT work for all methods. It will only work for methods that have the word ‘static’ in their signature. For now, then, you should put the word static before all of your methods because they are meant to be stand alone. (You will understand more about ‘stand alone’ methods when we discuss classes in more detail).

User-Defined Methods

Page 10: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

Comments: All methods must have a comment at the top detailing what the method will do. This will keep you focused on exactly what it is the method is supposed to accomplish. Methods generally have one and only one very specific task to do.

Here is the outline of a very basic method that outputs a simple greeting to the screen. (Note the comment at the beginning of the method).

//output a generic greeting to the screenpublic static void printGreeting() {

System.out.println("Hi, welcome to the printGreeting function!");System.out.println("Hello Miss/Sir, how are you today?");

} //end of printGreeting method

Now at any point in your program (e.g. from somewhere in your main() method, this method can be invoked by simply typing:

printGreeting();

ALWAYS WRITE YOUR COMMENT FIRST. THEN WRITE THE METHOD.This last instruction WILL save you time in the long run. I promise. One key to writing a method is being VERY explicit about what you want the method to do.

Another simple example://output the sum of two numbers to the screen//the numbers have been hard-coded with valuespublic static void outputTheSum() {

int num1 = 10;int num2 = 22;System.out.println("The sum of the numbers is " + (num1+num2) );

} //end of outputTheSum method

Parameters (Arguments)When creating a method, it is sometimes required to provide the method with parameters.(Parameters should not be confused with “arguments” – more on this later).

For example, suppose you wanted to create a version of the greeting method earlier, but one that personalizes the greeting based on the user’s name.

//Outputs a personalized greeting to the screen.//This method requires that a String representing the //user’s name be provided as an argument//when the method is invoked.public static void printGreeting(String name) {

System.out.println("Hi, welcome to the printGreeting function!");System.out.println("Hello " + name + ", how are you today?");

} //end of printGreeting method

Page 11: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

When we created the above method, we decided to include a parameter. This means that in order to invoke this method, it is not enough to simply write the method’s name. For example, trying to invoke the method by typing: printGreeting(); will not work. This is because this particular method has one parameter. What this means is that in order to invoke the method, you must

1. Write the method’s name2. Provide the method with one argument (of the proper type!)

So, to invoke this method, you must type:printGreeting(“Bob”); orprintGreeting(“Erin Brokovitch”);

Again: The above method takes one argument. When you call the method, you must pass it one argument of type ‘String’. Note that passing an argument of a different type will produce an error.

Memorize and use the following statement to answer the questions that follow: The system looks for a method called _____________ that accepts ____ argument(s) of type _______________________ .

Given the method just above, what will take place with the following?printGreeting(5)printGreeting(Bob);printGreeting(“Yosef Mendelsohn”);printGreeting(“Bob”, 5);

Methods that Return a Value:Methods can do an infinite number of things. Sometimes a method will output information to the screen, sometimes it may play sounds, it could enter information into a database, etc, etc, etc. Sometimes a method’s job is to return some information back to the computer program itself.

For example, suppose your program periodically needs to calculate the square of some number. You could write a method that accepts one argument, then calculates the square of that number, and then returns the resulting value back to the program. Here is how you might write such a method:

//calculates the value of number * number and returns itpublic static int calcSquare (int number) { return (number * number);} //end of method calcSquare

Here is the method in use:int num, squareOfNumber;

Page 12: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

System.out.print(“Please enter an integer number: “);num = console.nextInt(); //assumes a Scanner object exists

squareOfNumber = calcSquare(num);

System.out.print(“The square of your number is: “ + squareOfNumber);//Can you suggest a “shortcut” for the previous two lines?

Notice the highlighted line – let’s review what has happened: There are two operations on that line, an assignment (‘=’) and a method call. If you review your precedence table, you will see that method calls have higher precedence than assignments. So the method call is carried out first:

1. The method call returns the value of ‘num’ squared. 2. The value returned by the method is then assigned to the variable

squareOfNumber

A useful way to think about this: When a method call returns a value, the method call (e.g. calcSquare(num) ) is essentially replaced by the value that was returned. So for example, from:

squareOfNumber = calcSquare(6);We would get:

squareOfNumber = 36;

The Return Type:

public static int calcSquare (int number)

Look closely at the header of this last method. Notice that where we have usually written the word ‘void’ (e.g. in our main() methods), we instead see the word ‘int’. The word after public static tells you what data-type is returned by the method. In the case of our calcSquare() method, the data-type is an int.

Now look at our printGreeting method:public static void printGreeting(String name)

If a method does not return a value, we simply put the word ‘void’ as the return type.

Terminology:Let's go over some of the terminology of method definitions. You should become very familiar with these terms.

The header refers to the first line of the method.

A method is invoked by listing its identifier (i.e. its name) followed by the appropriate number of arguments. (The argument must, of course, be of the appropriate type). In the above example, the identifer is ‘square’ and the method requires one argument (of type ‘int’) .

Page 13: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

A formal parameter is the identifier that appears in the header of the method. The formal parameter is (are) a placeholder for the value of the argument.

The method body describes how the method computes its value.

- A method consists of a method header and a body, much like the main part of the program does.

Return Statements:If you are writing a method that returns a value, the method MUST have a return statement. If a method does not return a value (e.g. a method that has a return type of ‘void’), a return statement is optional.

The return statement ends the method: If a return statement is present, execution of that return statement automatically ends the method. In other words, there may be more code in the method after the return statement, but once a return statement is reached, the method is over. Flow then returns to the point in your program from where the method was invoked.

If the method returns a value, this value must be appended to the return statement.Eg: public static int calcSquare (int number) { return number*number;}

In a void method, return statements are used to break out of a method. You will see examples of this later in the course.

One more example:Let’s write a method that will accept two parameters of type ‘int’, and then return the sum of those two values. Here is the method definition:

//returns the average of num1 and num2public static int sumTwoNumbers(int num1, int num2) {

int theSum = num1 + num2;return (theSum);

} //end of method sumTwoNumbers()

Can you suggest a shorter way of implementing this method?Answer: leave out the variables and simply say: return (num1+num2);

‘void’ methodsAs discussed earlier, some methods do not need to return a value. Consider a method that accepts one argument representing a person’s name, and a second argument representing an integer number ‘n’. The method then outputs the name ‘n’ times to the screen:

//outputs ‘name’ to the screen ‘n’ times

Page 14: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

public static void printName(String name, int n) {

for (int i=0; i<n; i++)System.out.println(name);

} //end of printName method

Hopefully you’ll agree that no return value is needed from this method. In such cases, the return type of the method is indicated to be ‘void’. Note: This does not mean that ‘return’ is never needed in void methods. For example:

//prints inspirational message if ‘sales’ < 50000public static void motivationalMessage(int sales) {

if (sales < 50000)return;

elseSystem.out.println(“Congratulations!!!”);

} //end of motivationalMessage method

- Remember, a ‘return’ immediately returns the flow of control to the location from where the method was originally called.

How Methods Get Invoked When a method is invoked, Java looks for a method called _____________ that accepts ____ argument(s) of type _______________________ .

Eg: printName(String name, int n)“Java looks for a method called ‘printName’ that accepts 2 arguments of type String, then int.”

Being clear on this concept will help tremendously to understand our next topic:

Method Overloading:It is possible and often very useful to have methods that have the same name. Think back to our printGreeting() earlier in the lecture. We begain by writing a version that was very generic and simply outputted a (very impersonal) greeting to the screen. We then decided to write a version of printGreeting that accepted one argument (of type String) and outputted a slightly more personal version of the greeting to the user.

Since these methods are extremely similar, we decided to give them the same name. Is this possible? Sure….Well, if you have two methods with the exact same name, how does Java know which of the two methods you wish to invoke? Answer: See the section above: “How Methods Get Invoked”…

Page 15: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

The reason it works is that when invoking a method, Java not only looks at the identifier (name), it also looks at the number and type of arguments provided to the method. So if you invoke:

printGreeting();Java will look for a method called printGreeting that accepts zero arguments. It will then invoke that particular version of printGreeting.

If instead, we invoked printGreeting and also provided an argument to the method of type String, Java will look for a method called printGreeting that accepts one argument of type String and will invoke that one. For example:

printGreeting(“Elizabeth”);

Question: What if we invoked printGreeting and passed the method one argument of type int? (e.g. printGreeting(23); )Answer: It won’t work. Java will look for a method called printGreeting that accepts one argument of type int. When it doesn’t find it, it will give an error.

This ability to have multiple methods with the same name, and distinguished only by their signatures (identifier and number/types of arguments), is called method overloading. Method overloading is used A LOT in Java.

CommentsNote how all of the methods had a comment before them detailing what the method does. The comments preceding a method are the instruction manual for the method. These comments:

1. explain what it is the method does2. warn the user of any limitations to the method (Eg: “//This method only

works with arguments that are integers between 1 and 10”)

Put some thought into your comments. They are not there to make teacher haappy. They are there to ensure that you have a clear and specific goal for the method that you are about to write.

Abstraction (& Comments reiterated)- Anyone who uses your method should not have to know anything about how the

method does its work. - For example, when you call a method, you don’t need to know anything about

how the method works, you only need to know what it does. Eg: In “real life”, to drive a car, you need only know how to turn it on, turn it off, steer, break, and accelerate. You don’t need to know anything about how these things work, you

Page 16: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

need only know the proper way of ‘invoking’ the functionality. (E.g. Turn the key in the ignition to start the car).- The advent of automatic transmissions from manual transmissions is

analogous to ‘raising the level of abstraction’.- It is possible that some people may want or need to know more low-level details,

but our methods should be designed so that people who wish to remain blissfully ignorant, can do so.

- So what does this mean? It means that another programmer should be able to completely ignore the body of your method. If they wish to use your method, they should only need to see:

1. The comment preceding the method2. The header (aka the “signature”) of the method

- In other words, ALL of your methods must have a comment detailing exactly what the method does. This is not optional!!! (And you will be graded on it from now until the end of the course!)

- See MethodsPractice.java

Fill in the blank: You must always write your method comments __________ writing the code for the method.Answer: before!

III. ScopeVariables or constants are all contained in a particular context. For example, in the ‘printName’ method mentioned earlier, the variable ‘i’ in the for-loop has the loop as its scope. This means that outside of that loop (and certainly outside of the method), ‘i’ has no meaning. Or another way of looking at it, in a different method, you could declare the variable ‘i’ and that would be okay. (Try declaring ‘int i’ twice in the same method, though, and see what happens).

for (int i=0; i<5; i++)System.out.println("hello world");

System.out.println(i); // would generate an error

int i=3; //Redeclaring ‘i’. This is okay since//the previous declaration of ‘i’ had//the for-loop as its scope

System.out.println(i);

What would happen if we took the first declaration of ‘int i’ and placed it just before the for-loop?

- A variable declared inside a method is local to that method. In other words, outside of that method, attempting to set or read the value of that variable would generate an error.

- A variable declared inside a loop is local to that loop. (See above example).

Scope is not a difficult concept, but should not be taken for granted. It is important to have a good understanding of scope. (This will show up on exams!!)

Page 17: Java 211 – Lecture 3  · Web viewJava 211. Strings, Reading Input . Yosef Mendelsohn. I. Strings. The String data type is not one of the primitive data types (e.g. int, char, double,

Another example: Consider the Scanner objects we have been creating to read input. We have been declaring the object inside main like so:public class Test{

public static void main(String[] args){

Scanner console = new Scanner(System.in);//scope of console is the method main()

etc.....

The only problem with this is that if we want to read input from any other method, we will NOT be able to do so. Again, the reason for this is scope: The object is only visible as long as we are inside the main method. If we enter a different method, this object is no longer available.

If you understand scope, however, there is a little ‘trick’ we can use for now: Declare the object outside of any method, but still inside the class. This makes it a class variable. In other words, the variable (aka object) will now be available anywhere inside the class because “it has the class as its scope”. public class Test{

Scanner console = new Scanner(System.in);//scope of console is the class Test

public static void main(String[] args){

etc.....