Scope of variables class scopeofvars { public static void main(String args[]) { int x; // known to all code within main x = 10; if(x == 10) { // start new scope int y = 20; // known only to this block // x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } // y = 100; // Error! y not known here // x is still known here. System.out.println("x is " + x);
Scope of variables contd class lifetime1 { public static void main(String args[]) { int x; for(x = 0; x < 3; x++) { int y = -1; // y is initialized each time block is entered System.out.println("y is: " + y); // this always prints -1 y = 100; System.out.println("y is now: " + y); }
Scope of variables contd class lifetime2 { public static void main(String args[]) { int count; for(count = 0; count < 10; count = count+1) { System.out.println("This is count: " + count); int count; // illegal!!! for(count = 0; count < 2; count++) System.out.println("This program is in error!"); }
Methods in problem solving Often we think of solving a large problem in parts Computing the number of digits in n! involves two major steps: computing k=n! and computing the number of digits in k So I can have two “procedures”, one computes n! and the other computes the number of digits in it Such procedures are called methods These are just like functions A method may or may not produce a value The type of the produced value determines the “return type” of a method
Return and parameter type Can be int, float, String, double, char, or void We have seen one method so far: main It does not produce any value: void public static void PrintMyName () { System.out.println(“Tintin”); } Every method must be a part of a class
PrintMyName class anExample { public static void main (String arg[]) { PrintMyName(); // Method call } public static void PrintMyName () { // Method declaration System.out.println(“Tintin”);
Method parameters Methods can have parameters also class anExample { Just like functions class anExample { public static void main (String arg[]) { String myName = “Tintin”; PrintMyName(myName); } public static void PrintMyName (String s) { System.out.println(s);