Join Peggy Fisher for an in-depth discussion in this video Anatomy of a Java program, part of Learning Java.
- Each programming language has some of the same basic parts in the Main Method. Comments, which can be both single line comments, and multi-line comments. Variables, which include both the name of the variable, and the data that the varible will hold. Equations, or statements, input and output that's written to the console, decision statements, loops, methods, some languages refer to these as functions. File input and output, and more. I think the easiest way to learn about the syntax of Java is to walk through a program.
Using our algorithm on calculating travel cost, I have written a basic Java program. By asking the user to enter the information, the program can be reused many times to calculate the cost of various trips without re-writing the code. Let's take a look. If we start at the top of the program, you'll notice that there's a multi-line comment that describes the program's function. "This program uses total distance of the trip, "the mpg of vehicle, and the current price of gas "to calculate the total cost of the trip." What you see on line six is telling the program what package it belongs to.
You can see it has the same name as the class name, but it's all lowercase, "travelcosts." On line seven, this is the first time we've seen the import statement. The import statement is used to include libraries that were written by somebody else. In this case, I'm importing java.util.Scanner. The Scanner class is used to read and write from the console. You also see a comment that has the author's name in it. Every Java program starts with a class name.
Our class name is "TravelCosts." Note that Travel is a capital T, and Cost is a capital C. This is called CamelCase, where you capitalize the first letter of every word. Right below that is the start of our Main Method. Every Java project must have one, and only one, Main Method. To calculate the cost of our trip, we need to know the distance they plan to travel, the mpg of their vehicle, and the current price of one gallon of gas. The first few lines of code are used to define our variables and associated data types.
In the program, we will prompt the user for the information, assign it to these variables, and use these values to calculate the gallons needed, and total cost. Let's take a look. Starting on line 15, you can see there's four lines declaring four different variables. One to hold the distance, one to hold the miles per gallon. I abbreviated as mpg. One to hold the price per gallon, and one for the total cost. i have a comment, because I wanted to show you that you could actually list each one of these together on one line, so if I wanted to, I could change these to be commented out, and just do it one time, on one line, if they're all the same data type.
OK, let's go to line 20. Line 20 says, "Scanner in = new Scanner(System.in)." This is what's going to allow us to read whatever the user types at the keyboard. We'll talk more about the Scanner class a little bit later. Line 21 has, "System.out.println" and prompts the user to enter the total distance in miles. Notice the use of the literal, with the double quotes around, "Enter the total distance in miles: " Line 22 is the first time we've seen where we're gonna put a value into a variable.
Notice that the variable is on the left-hand side of the equals sign. For all assignments and equations in Java, we'll always have the receiving variable on the left-hand side. "distance = in.nextDouble();" This is gonna read whatever the user types, it's gonna look for a number that has a decimal, and it's gonna put it into the variable called, "distance". We're gonna continue to ask the user to enter the mpg for the vehicle, read that into the "mpg" variable, and finally ask the user what is the current price of one gallon of gas, and read that value into "pricePerGallon".
Now that I have all the values that I need to calculate the total cost, I'm going to do that "totalCost = (distance/mpg)" That will tell me how many gallons of gas I need for this trip. I'm gonna multiply that times the "pricePerGallon" that the user entered. The last two lines says, "The trip is going to cost, totalCost". This will print out the value in the variable totalCost to the screen in line with the sentence that says, "The trip is going to cost $" The very last line is just gonna print a blank line.
Let's go ahead and run our program so we can see how this works. I'm gonna click on the green arrow, "Enter the total distance in miles:" Well let's say our trip is about 500 miles, and our car gets 20 miles to the gallon. The current price of gas, let's go ahead and say $2.55. When I hit Enter, the program automatically calculated the cost, and printed it out saying, "The trip is going to cost $63.75" What's nice about using variables, and allowing the user to enter in the values is I can rerun the program with different values now.
What if I'm going the same distance, but this time I'm using a nice hybrid car that gets 50 miles to the gallon, and the price of gasoline is still the same, $2.55. We can see that the hybrid car is going to cost a lot less for the same distance. Let's go back real quick to the calculation where I have the calculation on the right-hand side, and the variable on the left. Again, this is really important in programming. When we learn algebra and other maths subjects, we write math equations where this is not always true.
For example, I'm sure you're all familiar with how to find the hypothenuse of a triangle, a-squared plus b-squared equals c-squared. In Java and in most programming languages, you must reverse the equation so the result of the equation is stored in the variable on the left side of the equals sign. So in our example about the hypothenuse, it would have to be written as, c equals the square root of a-squared plus b-squared. One more item that is worth noting is the use of curly brackets.
Every block of code is enclosed in open and closing curly brackets. Every open curly bracket must have a matching closing curly bracket. In Java, if you click to the right of the curly bracket and you scroll down, it'll show you where the ending curly bracket is, so you can see how they're matched up. We will continue to look at programs that I have already written and also write programs togther, to help you to learn more about the syntax and programming in Java.
- Downloading and exploring NetBeans
- Understanding Java basics: data types, strings, arrays, and more
- Controlling flow with functions and loops
- Creating classes
- Sorting and searching arrays
- Manipulating files
- Handling errors
- Building GUIs