Java Methods
Java Methods
Modules in java are called methods and classes. Java programs are written by
combining new methods and classes the programmer writes with “prepackaged” methods
and classes available in the Java API (also referred to as the Java class library) and in
various other method and class libraries.
The Java API provides a rich collection of classes and methods for performing common
mathematical calculations, string manipulations, character manipulations, input/output,
error checking and many other useful operations.
As well, the programmer can write methods to define specific tasks that need to be used
at many points in a program. They are called programmer-defined methods.
A method is invoked by a method call.
int result;
for ( int x = 1; x <= 10; x++ ) { Calling the square method
result = square( x );
output += "The square of " + x +
" is " + result + "\n";
}
outputArea.se tText( output ); Declares the container reference C
}
method of the container
// square method definition arguments
public int square( int y )
{ programmer-defined method
return y * y;
}
}
int result;
outputArea.setText( output );
}
String s1 = JOptionPane.showInputDialog(
"Enter first floating-point value" );
String s2 = JOptionPane.showInputDialog(
"Enter second floating-point value" );
String s3 = JOptionPane.showInputDialog(
"Enter third floating-point value" );
if ( i % 5 == 0 )
output += "\n";
}
System.exit( 0 );
}
}
// summarize results
for ( int roll = 1; roll <= 6000; roll++ ) {
face = 1 + (int) ( Math.random() * 6 );
switch ( face ) {
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
}
}
JTextArea outputArea = new JTextArea( 7, 10 );
outputArea.setText(
"Face\tFrequency" +
"\n1\t" + frequency1 +
"\n2\t" + frequency2 +
"\n3\t" + frequency3 +
"\n4\t" + frequency4 +
"\n5\t" + frequency5 +
"\n6\t" + frequency6 );