Java 02
Java 02
BASICS
UMBC CMSC 331 Java
Comments are almost like C++
Variable
class Person {
String name; Method
int age;
void birthday ( ) {
age++;
System.out.println (name +
' is now ' + age);
}
}
{ int x = 12;
/* only x available */
{ int q = 96;
This is ok in C/C++ but not in Java.
/* both x and q
available */
{ int x = 12;
}
{ int x = 96; /* illegal */
/* only x available */
}
/* q “out of scope” */
}
}
UMBC CMSC 331 Java 4
An array is an object
• Person mary = new Person ( );
• int myArray[ ] = new int[5];
• int myArray[ ] = {1, 4, 9, 16, 25};
• String languages [ ] = {"Prolog",
"Java"};
• Since arrays are objects they are allocated dynamically
• Arrays, like all objects, are subject to garbage collection
when no more references remain
– so fewer memory leaks
– Java doesn’t have pointers!
C:\UMBC\331\java>javac echo.java
C:\UMBC\331\java>
Factorial Example
From Java in a Nutshell
/**
* This program computes the factorial of a number
*/
public class Factorial { // Define a class
public static void main(String[] args) { // The program starts here
int input = Integer.parseInt(args[0]); // Get the user's input
double result = factorial(input); // Compute the factorial
System.out.println(result); // Print out the result
} // The main() method ends here
// An instance field
public double r; // The radius of the circle
• Overloading occurs when Java can distinguish two procedures with the
same name by examining the number or types of their parameters.
• Shadowing or overriding occurs when two procedures with the same
signature (name, the same number of parameters, and the same
parameter types) are defined in different classes, one of which is a
superclass of the other.