Guide to Object-oriented Programming With Java (Buffalo State College 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.


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:

Figure 4-1: Access Modifiers


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 non-first character (letter, digit, $, _).


Figure 4-2: Java Identifiers


A keyword is a reserved word.


Figure 4-3: Some Common Java Keywords


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.

// declare variables
double w;
double h;
double BMI;

Figure 4-4: Sample Java Variables


A method is a similar to functions in C++ or PHP.

public BMIcalculator(double w, double h) { weight = w; height = h; }
Figure 4-5: A Sample Java Method
package edu.buffalostate.cis425.sp19.exercises.assignments.your-last-name;
  * File:
* * Calculate Body Mass Index (BMI) * It prints a the BMI to standard out * * @author Your Name Here * */
public class BMIcalculator { // declare variables double weight; double height; 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); } }
Figure 4-6: Code
Your BMI is 20.761245674740486

Figure 4-7: Output

Let's get started with a variables & functions program!

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2019 Jim Gerland