Guide to Object-oriented Programming With Java (University at Buffalo Version)
Chapter 4: Java Language Structures
In addition to the previously mentioned Java structures (projects, packages, classes, and comments), Java's other structures include: identifiers, keywords, variables, and methods. Most Java programmings use camelCase to name their variables, identifiers, and methods. For example, a variable to store the first name would be: firstName
.
Classes
As previously mentioned, a class is a "container" for code. Each Java program can contain only one (1) class
method. The name of the class must begin with an Uppercase letter. The name of your .java
file should be the same as the name of your class. For example, the file HelloWorld
would have a public class HelloWorld { }
statement. All code in a class in enclosed in braces: { }
. A class can have different access modes Valid Access modifiers are:
public
- the class is available to any other class in the any packageprotected
- ony available to the classes in the packages and its subclassesno modifier
- only available to the classes in the same packageprivate
- a member of a c lass can only access that class
Identifiers
An identifier is a sequence of one or more characters. The first character must be a valid first character (letter
, $
, _
). Each subsequent character in the sequence must be a valid nonfirst character (letter
, digit
, $
, _
).
w
h
weight
height
Keywords
break
case
if
int
String
Variables
In Java variables are devices that are used to store data, such as a number, an array, an object, or a string of character data. Java is considered as a strongly typed programming language so all variables should be declared as a type before they can be used. Variables follow the same naming conventions as other Java structures except variable start with a lowercase letter.
double w;
double h;
double BMI;
Methods
A method is a similiar to functions in C++ or PHP.
weight = w;
height = h;
}
/**
* File: BMIcalculator.java *
* Calculate Body Mass Index (BMI)
* It prints a the BMI to standard out
*
* @author Your Name Here
*
*/
public class BMIcalculator {
// declare variables
double w;
double h;
double BMI;
public BMIcalculator(double w, double h) {
weight = w;
height = h;
}
public calculateBMI() {
return weight / (height * height);
}
/**
* The main() is the entry point for a Java program when executed
*
* @param string array - command line arguments passed to program
* @return none
*
*/
public static void main(String[] args) {
BMIcalculator calculator = new BMIcalculator(60, 1.70);
double bmi = calculator.calculateBMI();
// print to the console
System.out.println("Your BMI is " + bmi);
}
}
BMIcalculator.java
Code
<terminated>
Your BMI is 20.761245674740486
BMIcalculator.java
OutputLet's get started with a variables/methods program!