Thursday, October 9, 2008

Static Method Tutorial

Table of Contents




  1. Introduction to methods

  2. Paremeters / arguments

  3. How call works

  4. Defining a static method

  5. Example with 3 methods





1. Introduction to methods



Basic idea - A named group of statements - Verbs


Java statements are grouped together into units called methods.
Each method must be inside a class. It has a name, which starts with
a lowercase character and typically is a verb because it
does something.



Terminology: Call / return


When you go to a method, the term is call. When the group of statements
in the method is finished, the method returns to the where it was
called from.




1.2. Static / class methods



1.2.1 main method


This tutorial starts with static (also called class) methods
because all applications start with the static method main.
Altho main is static, as you progress in Java, you will find that
relatively few of your methods will be static - only those that
are self-contained, depending only on parameters.
This self-contained nature makes them a good place to start the
discussion of methods.



1.2.2 Method calls occur before parentheses ()


You can always identify a method call because it it followed by left and
right parentheses, which may contain arguments (parameters).
If you see a left parenthesis with a name preceding it, it will be a method
call, or a constructor, which is very similar.
Here is an example where the method names are hilited.



 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

 
// File : intro-dialog/KmToMiles.java
// Purpose: Convert kilometers to miles. Use JOptionPane for input / output.
// Author : Michael Maus
// Date : 16 Apr 2005

import javax.swing.*;

public class KmToMiles {

//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.

//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);

//... Computation
mi = km * 0.621; // There are 0.621 miles in a kilometer.

//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}
}



The above code defines the main method, which someone
(eg, the operating system) will call.
To do its work, main calls on other methods:
showInputDialog which is defined in the JOptionPane class),
parseDouble which is defined in the Double class, and
showMessageDialog which is also in the JOptionPane class.


When you call a static method in someone else's class, you have to
precede it with the name of the class containing its definition, followed by a dot.




Static and Instance Method calls - Preceded by class or value


The calls for static and instance methods look the same, except
that a static method name is preceded by the class name (unless it's in the
same class when the class name can be omitted).

Instance method calls are preceded by a value instead of a class name.




Business analogy - different departments


You could think of methods as being similat to departments /sections / groups
in an organization, which are responisible for doing one thing.






2. Parameters / Arguments




Method call arguments (actual parameters) - enclosed in the parentheses


When you call a method, you can pass information for it to use.
These arguments (also called actual parameters) are inside
parentheses following the method name. Use commas to separate
the arguments if there is more than one. The previous program is
shown below, but the arguments in the calls (not the main definition)
are hilited.



 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

 
// File : intro-dialog/KmToMiles.java
// Purpose: Convert kilometers to miles. Use JOptionPane for input / output.
// Author : Michael Maus
// Date : 16 Apr 2005

import javax.swing.*;

public class KmToMiles {

//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.

//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);

//... Computation
mi = km * 0.621; // There are 0.621 miles in a kilometer.

//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}
}






3. How call works




How to define your own method


The previous program is rewritten below to define a method to
convert from kilometers to miles.



The method call, and the first line of the method definition are hilited.



 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

 
// File : intro-dialog/KmToMilesMethod.java
// Purpose: Convert kilometers to miles using a method. JOptionPane IO.
// Author : Michael Maus
// Date : 28 Oct 2004

import javax.swing.*;

public class KmToMilesMethod {

//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.

//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);

//... Computation
mi = convertKmToMi(km);

//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}

//========================================================= convertKmToMi
private static double convertKmToMi(double kilometers) {
// Assume there are 0.621 miles in a kilometer.
double miles = kilometers * 0.621;
return miles;
}
}



The method call process



Terminology - call and return


A call is the process of suspending one method (the caller) in the middle in
order to start another method (the called method). When the called method
is finished, it returns to the point immediately after the call took
place. Commonly this is described as the returning to the place of the
call, but of course it is really the next instruction or we would have a loop.



Terminology - argument and parameter


Terminology regarding method parameters/arguments is inconsistent, but
the most common practice is the following.


Argument is the name for each of the comma-separated values in
a method call. However, these are sometimes referred to as
actual parameters or simply parameters.
The preferred usage is argument.



Parameter is the name for each of "variable" in the method
definition that corresponds to the argument in the call.
The term formal parameter is sometimes used.




Specific example


We'll take a look at how the convertKmToMi method is called,
because it illustrates how all methods are called. Later, when we look
at instance methods, the only difference will be the automatic addition
of one extra parameter.



Assume we've gotten to the call on line 22.


 
mi = convertKmToMi(km);

Before the assignment can be made, the right-hand-side must be evaluated.
In this case, the method must be called. The following describes the steps
in calling a method.



1. Evaluating the arguments


The only argument in this call, kilometers, is a simple
variable that doesn't require evaluation. When an expression is used
as an argument (eg, in line 25), the expression must be evaluated before
the call can be made.



2. Creating a new Stack Frame


When a method is called, memory is required to store the following information.



  • Parameter and local variable storage. The storage that is needed for
    each of the parameters and local variables is reserved in the stack frame.


    In the convertKmToMi method's stack frame there
    would be space for the parameter kilometers and
    the local variable miles.



    The main method's stack frame has the one parameter
    args and three local variables,
    kmStr, km, and mi.



  • The saved state of the calling method. You don't have to worry about
    this; it's automatically saved for you.
    It includes the calling method's return address,
    which is where to continue when it's time to return.

  • Other working storage needed by the method may be required. You don't have
    to do anything about this because it's handled automatically.



3. Initializing the parameters


When the arguments are evaluated, they are assigned to the
local parameters in the called method. In the example
above, the value in km in main is assigned to
the parameter kilometers in convertKmToMi.



4. Executing the method


After the stack frame has been initialized, execution starts with the
first statement and continues as normal.



5. Returning from the method


When a return statement is encountered, or the end of a void method
is reached, the method returns.
For non-void methods, the return value is passed back to the calling method.
The stack frame storage for the called method is made available for reuse
by other methods.
Execution is continued in the called method immediately after where
the call took place.






Defining a static method




How to define your own method


The previous program is rewritten below to define a method to
convert from kilometers to miles.



The method call, and the first line of the method definition are hilited.



 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

 
// File : intro-dialog/KmToMilesMethod.java
// Purpose: Convert kilometers to miles using a method. JOptionPane IO.
// Author : Michael Maus
// Date : 28 Oct 2004

import javax.swing.*;

public class KmToMilesMethod {

//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.

//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);

//... Computation
mi = convertKmToMi(km);

//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}

//========================================================= convertKmToMi
private static double convertKmToMi(double kilometers) {
// Assume there are 0.621 miles in a kilometer.
double miles = kilometers * 0.621;
return miles;
}
}



Anatomy of the convertKmToMi method


There are several parts to a method



Visibility - public, private, or package


 
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}


When you define a method, you should think about who can use it.
To achieve the best encapsulation (information hiding) you should
always declare methods with the least visibility that works.
Here are the four options, from least visible to most visible.



  • private - If you don't want any other class to use it,
    declare it private. This is a good choice.

  • None (package) - If you don't specify anything, the default visibility allows
    only classes in the same package (directory) to
    see it. This is a common choice.

  • protected - Don't use this controversial option which limits
    visibility to child classes.

  • public - Let's anyone see it. Choose this if you've defined
    a method that will be used by others outside of your project.
    Note that main must be
    declared public so the run-time system
    can call it.





Class (static) or instance method


 
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}

A method that doesn't use variables other than parameters should be declared
static. If the static keyword is omitted, the
method will be an instance method. This example uses static,
but if it's in a class that represents an object, you will usually define instance methods.




Return type


 
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}



Method name


 
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}

Method names should begin with a lowercase letter. Method names are typically
verbs, whereas variable names are usually nouns.




Parameter(s)


 
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}

In parentheses following the method name are the parameters (sometimes called formal parameters). There is only
one parameter in this example - kilometers.
The type of each parameter must be specified before the name (eg, double).
The parameters are variables that only exist inside the method, and they are
assigned values from the arguments (actual parameters) when the method is called.





Method body


 
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;

}

The body of a method is the statements which are executed when the method is called
are enclosed in braces following the the method header.
Additional local variables may be defined (eg, miles).





Return statement


 
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}

A method returns to the caller after it has done what it wants.
If the method returns a value (not a void method), it must contain
a return statement that specifies a value to return.
This example returns the value in miles.
The return statement can be followed by an expression of the appropriate type, not just
a single value. For example, this method body could be replaced
by a single return statement.


 
private static double convertKmToMi(double kilometers) {
return kilometers * 0.621;
}









Example with three methods



Here is another variation of the program, this time using three methods.
Altho there is no real need for these methods in
such a small program, large programs are in fact composed of many small methods.
It is the essential way that all code is structured.



There are a couple of things worth noting in this example.
Each of the user-defined method names is hilited.



  • One of the methods is void, so it doesn't return a value.

  • To of the methods call other methods.

  • The main program consists of calls to other methods.



Source code


 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

 
// File : simple-dialog/KmToMilesMethods.java
// Purpose; Converts kilometers to miles using two methods.
// Author : Michael Maus
// Date : 24 Apr 2005

import javax.swing.*;

public class KmToMilesMethods {

//============================================================== main
public static void main(String[] args) {
double kilometers = getDouble("Enter number of kilometers.");
double miles = convertKmToMi(kilometers);
displayString(kilometers + " kilometers is " + miles + " miles.");
}


//===================================================== convertKmToMi
// Conversion method - kilometers to miles.
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621; // 0.621 miles/kilometer
return miles;
}


//========================================================= getDouble
// I/O convenience method to read a double value.
private static double getDouble(String prompt) {
String tempStr;
tempStr = JOptionPane.showInputDialog(null, prompt);
return Double.parseDouble(tempStr);
}


//===================================================== displayString
// I/O convenience method to display a string in dialog box.
private static void displayString(String output) {
JOptionPane.showMessageDialog(null, output);
}
}

Origin Of Aids



Since first being broadcast in 2003 the Origins Of Aids has yet to be aired on UK television. Despite winning many awards and being hotly debated the reason is because of the barrage of legal assaults made on potential screeners by Dr Koprowski (and his legal network), who strongly denies causing the Aids epidemic during his 1950s trials of an experimental polio vaccine in Africa. Doc-Film-Net has also been threatened with more legal action for showing this important film than any other! If this copy goes dead post a comment and I will endeavor to locate another host. 




Update: High quality version taken down by hosts after more threats.

Update: Here it is again in medium quality.










Hobbes@Start Up

full time Web Designer / Visualizer @ FirstPhera.com (Ahmedabad)

at FirstPhera in Other

Position is in Ahmedabad at FirstPhera

If you are passionate about understanding user behavior and developing interfaces that are stupidly simple and highly engaging, get in touch with us. While designing gives you the kicks, you must enjoy writing clean CSS based markup that is cross-browser compatible, standards based and search engine friendly.

We really don’t care about Web 2.0 and/or past degrees. 2+ years experience would help, but if you have done the right stuff before or have the passion to learn, send us your work samples and a cover letter.

Standard drill for tools applies – Photoshop, Flash, Corel, Illustrator, Dreamweaver, etc.

U.S. Stock-Index Futures Climb; IBM, Intel, AIG Gain in Europe

By Adria Cimino

Oct. 9 (Bloomberg) -- U.S. stock futures rose, indicating the Standard & Poor's 500 Index will rebound from a six-day drop, as International Business Machines Corp. repeated its profit forecast and investors speculated market declines were overdone.

IBM, the largest computer-services company, climbed 7 percent in Europe after reporting third-quarter earnings that beat analysts' estimates. Intel Corp., the biggest chipmaker, gained 1.4 percent. American International Group Inc. surged 7 percent as the Federal Reserve Bank of New York said the insurer may access $37.8 billion in additional liquidity.

S&P 500 Index futures expiring in December added 17.5, or 1.8 percent, to 998.50 as of 11:51 a.m. in London. Dow Jones Industrial Average futures gained 139, or 1.5 percent, to 9,340 and Nasdaq-100 Index futures increased 32.25, or 2.4 percent, to 1,352.25.

``IBM's earnings and the tone of the company's outlook reassured the market,'' said Clemence Bounaix, a fund manager at KBL Richelieu Gestion, which oversees about $5.5 billion in Paris. ``This is an early indicator of the economy.''

U.S. stocks fell yesterday after Treasury Secretary Henry Paulson said more banks may collapse and unprecedented global interest-rate cuts failed to convince investors the economy will avoid a recession.

Paulson signaled the government may invest in banks as the next step in trying to resolve the deepening credit crisis.

The S&P 500's six-day losing streak was the longest since 2002. Its year-to-date slump of 32.9 percent is the worst since 1974 and the second-biggest drop ever compared with previous returns through Oct. 8, according to Harrison, New York-based research firm Bespoke Investment Group LLC.

Valuations

The 37 percent decline from a record a year ago has left the measure valued at less than 19 times the reported earnings of its companies, the cheapest since February. Europe's Dow Jones Stoxx 600 Index trades at 9.59 times profit, while the MSCI World is valued at 12.07 times the reported earnings of companies in the index, according to Bloomberg data.

IBM jumped 7 percent to $96.90 in Germany. Profit for the year will be at least $8.75 a share, IBM said, reaffirming a previous forecast. Earnings last quarter increased to $2.05 a share, excluding some items, the company said. That topped the $2.01 average estimate of analysts in a Bloomberg survey.

Intel added 1.4 percent to $16.47. Microsoft Corp., the biggest software maker, gained 2.3 percent to $23.55. Hewlett- Packard Co., the largest personal-computer maker, increased 1.4 percent to $40.56.

Earnings Estimates

Analysts expect a 5.6 percent drop in third-quarter profit at S&P 500 companies, according to Bloomberg data. IBM's results came after Alcoa Inc., the biggest U.S. aluminum producer, kicked off the earnings season with lower-than-estimated profit, saying net income slid by more than half.

AIG, the insurer taken over by the government, surged 7 percent to $3.41. AIG can swap as much as $37.8 billion of its ``investment-grade, fixed-income securities'' for cash to ``replenish liquidity'' at the insurer, the Fed said.

Wachovia Corp. rose 4.3 percent to $5.28. An agreement suspending federal litigation over the fate of Wachovia was extended by two days after lawyer David Boies said a ``grand solution'' between bidders Citigroup Inc. and Wells Fargo & Co. was being negotiated.

The end of a three-week ban on short selling financial stocks may reduce the market's record price swings as hedge funds increase trading.

Since the Securities and Exchange Commission started the rule Sept. 19, volume on the New York Stock Exchange dropped 35 percent and the Chicago Board Options Exchange Volatility Index surged to 57.53, its third straight record. Options on the VIX, as the volatility gauge is known, imply it will fall 44 percent in the next two weeks after the rule expired last night.

To contact the reporter on this story: Adria Cimino in Paris atacimino1@bloomberg.net.

HoopLa - News

cDc releases Goolag Scanner (posted by MiB on Februari 20th, 2008)

FOR IMMEDIATE RELEASE

SECURITY ADVISORY: The following program may screw a large Internet search
engine and make the Web a safer place.

LUBBOCK, TX, February 20th -- Today CULT OF THE DEAD COW (cDc), the world's
most attractive hacker group, announced the release of Goolag Scanner, a web
auditing tool. Goolag Scanner enables everyone to audit his or her own web
site via Google. The scanner technology is based on "Google hacking," a form
of vulnerability research developed by Johnny I Hack Stuff. He's a lovely
fellow. Go buy him a drink.

"It's no big secret that the Web is the platform," said cDc spokesmodel
Oxblood Ruffin. "And this platform pretty much sucks from a security
perspective. Goolag Scanner provides one more tool for web site owners to
patch up their online properties. We've seen some pretty scary holes through
random tests with the scanner in North America, Europe, and the Middle East.
If I were a government, a large corporation, or anyone with a large web site,
I'd be downloading this beast and aiming it at my site yesterday. The
vulnerabilities are that serious."

Goolag Scanner will be released open source under the GNU Affero General
Public license. It is dedicated to the memory of Wau Holland, founder of the
Chaos Computer Club, and a true champion of privacy rights and social justice.

GOOLAG SCANNER FUNCTIONS AND FEATURES

Goolag Scanner is a standalone windows GUI based application. It uses one
xml-based configuration file for its settings. All dorks coming with the
distribution of gS are kept inside one file.

--

Press Contact
Oxblood Ruffin
oxblood at hacktivismo.com

About Goolag Scanner
http://www.goolag.org/

About CULT OF THE DEAD COW
Based in Lubbock, Texas, CULT OF THE DEAD COW (cDc) is the most influential
computer underground group in the world. The cDc alumni list reads like a
Who's Who of hacking and includes a former Presidential advisor on Internet
security, among others. The group is further distinguished by publishing the
longest running e-zine on the Internet [est. 1984], stretching the limits of
the First Amendment, and fighting anyone or any government that aspires to
limit free speech. For more information, please visit 
www.cultdeadcow.com

About Johnny I Hack Stuff
http://johnny.ihackstuff.com/
and here
http://en.wikipedia.org/wiki/Johnny_Long

About Wau Holland
http://en.wikipedia.org/wiki/Wau_Holland
and here
http://www.ccc.de/?language=en