Download presentation
Presentation is loading. Please wait.
1
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);
2
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); }
3
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!"); }
4
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
5
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
6
PrintMyName class anExample { public static void main (String arg[]) {
PrintMyName(); // Method call } public static void PrintMyName () { // Method declaration System.out.println(“Tintin”);
7
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);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.