Let’s start with a really simple program.
So using jshell, perhaps the simplest Java program is:
System.out.println("Hello, World!");This program just prints "Hello, World!".
System.out.println, in this case, means outputting or printing the "Hello, World!" somewhere. That somewhere is probably the terminal where the program was run.
We will use System.out.println to do a lot in the coming pages.
It’s a simple statement, one that in other languages might be print or write or puts
(and why we all cannot just agree on one way to do this, well, beats me. Java’s is System.out.println)
Here’s your second Java program:
double milesPerHour = 55.0;
System.out.println("Car's Speed: " + milesPerHour);Now, how do we run this program? Use jshell!
jshell is Java’s built-in interactive tool that comes with Java 9 and later. It lets you type Java code and see results immediately, without having to create full programs with classes and main methods.
If you haven’t already got a jshell, open your terminal or command prompt and type:
jshellYou’ll see a prompt like this:
| Welcome to JShell -- Version 17.0.2
| For an introduction type: /help intro
jshell>(And if you get something like jshell: command not found, see the appendix at the back of the book on how to install the java software you need.) - (and if the number up there is Version 9 or 11 or 21… well it really doesn’t matter) - (I’ll wait. Go ahead, come back here when it’s installed.)
Now you can type simple Java statements directly! For example:
jshell> double milesPerHour = 55.0;
milesPerHour ==> 55.0
jshell> System.out.println("Car's Speed: " + milesPerHour);
Car's Speed: 55.0Take a LOT of care to type the code is exactly as you see it above. Notice, the double quotes " and the semi-colon ;.
ProTip: All of this matters, and being precise with your code, well, it’s expected by potential employers.
Throughout this book, code examples are designed to work directly in jshell. You can type these statements one by one and see immediate results. For example:
jshell> double milesPerHour = 55.0;
jshell> System.out.println("Car's Speed: " + milesPerHour);jshell is perfect for learning Java because you can experiment immediately without the overhead of creating full programs. You can: - Test individual statements - Try different values - See results instantly - Fix mistakes quickly
To exit jshell when you’re done, type /exit or press Ctrl+D.
Cool, huh? The ability to communicate with you is one of Java’s most fundamental capabilities. And you’ve run Java code interactively. Congratulations, you’re a coder. (Well, at least for today you are.)
Note on exercises: So yeah, I want you to learn Java. And you claim you want to learn Java. So, then, about the these exercises; remember when I said learning the hard way is best? (the idea that by typing code in with your own two-little-fingers (oh wait, what? you know how to type? You’ll go far in this gig!!)) Yeah, so here’s the deal.
You should NOT copy/paste these exercises into jshell. You should t-y-p-e them. Yes, that’s right, t-y-p-e them in with your fingers. You will practice what code looks like and how it goes together if you do enough of it.
Try these exercises in jshell to practice System.out.println and basic Java syntax:
Exercise 1: Your First Output
Print your name and age using System.out.println: Replace [Your Name] and [Your Age] with your actual information.
System.out.println("My name is [Your Name]");
System.out.println("I am [Your Age] years old");
// so to be clear, I would type this in jshell:
System.out.println("My name is Kris Younger");
System.out.println("I am 25 years old");Exercise 2: Using Variables and Concatenation
Create variables (hmm, what’s a variable?) for your favorite food and hobby, then print them:
String favFood = "pizza";
String hobby = "reading";
System.out.println("I love eating " + favFood);
System.out.println("My favorite hobby is " + hobby);We will talk about variables very soon.
Exercise 3: Numbers and Math
Create variables for two numbers and print their sum:
int num1 = 15;
int num2 = 27;
System.out.println("Sum of " + num1 + " & " + num2 + " is " + (num1 + num2));Exercise 4: Multiple Data Types
Practice with different data types:
String name = "Java";
int version = 21;
double pi = 3.14159;
boolean isAwesome = true;
System.out.println("Language: " + name);
System.out.println("Version: " + version);
System.out.println("Pi: " + pi);
System.out.println("Is awesome: " + isAwesome);What does int and double signify?
Well, see how they proceed another descriptive word describing how many loaves and the flour amount?
int loavesToMake = 2;
//^
double flourAmount = 3.5;
//^^^^
System.out.println("We need " + flourAmount
+ " cups of flour to make "+loavesToMake+" loaves.");It is our way of telling Java what kind of number flourAmount is.
We want flourAmount to be place holder for the number 3.5,
because using a descriptive term like flourAmount makes the code easier to read and understand.
int and double also tell Java what kind of number we want for these values.
See much more on this, up ahead, in Variables.
While you’re not thinking about the long term, or about large Java programs, there is a powerful thing in Java that helps with tracking comments and notes about the code.
In your program, you can write stuff that Java will ignore, it’s just there for you (or readers of your code). We use two slashes to start a comment, and the comment goes to the end of the line. Java will ignore anything on a line after two forward slashes. "//"
// this is a comment. it might describe something in the code.
int x = 53 - 11;
int y = x * 4; // this is also a comment.Often, you’ll see something like this in this book.
double flourAmount = 3.5;
System.out.println(flourAmount); // -> 3.5That comment at the end of the System.out.println line is showing what you can expect to see in the output. Here it would be "3.5" printed by itself. Try it in jshell:
jshell> double flourAmount = 3.5;
jshell> System.out.println(flourAmount);
3.5We can also add useful stuff to the println method call.
double flourAmount = 3.5;
System.out.println("We need " + flourAmount + " cups of flour.");See how Java types it all out as a useful phrase? That proves to be very handy in a million-plus (or more) cases.
But comments can be used to explain tricky bits of code, or describe what you should see in output. Comments in code are primarily used to enhance readability and understanding, both for a "future you" and for others who might work with the code later. Comments serve as documentation, explaining the purpose, logic, and functionality of the code, especially in complex or tricky parts. Comments also help with collaboration, making it easier for teams working with you to understand and modify code in the future.
Comments are your friend. And they are FREE, no cost to using them.
The statement "everything is number" is attributed to the ancient Greek philosopher Pythagoras (born circa 570BCE) and his followers, the Pythagoreans. They believed that numbers, particularly whole numbers and their ratios, were the fundamental essence and underlying principle of all things in the universe.
Little did the Pythagoreans know how close they got it: everything in your new world is digital. Numbers, simplified all the way down to 1 and 0 (as in bits).
There basically two kinds of numbers in Java. There are times when I cannot believe I have to make this point. It just seems like, "well, if Java is so smart why do I have to care about this."
What am I complaining about?
Well, to make a strange distinction between two types of numbers, in actuality Java has a bunch different types of numbers.
In Java, we have to decide what type of number we are going use with a variables like flourAmount and loavesToMake.
If you’re just going to count things (like say the number of birthdays a person has had), we will use integers for that. integers in Java, are called int.
An int means a number, but just an integer like 0, 1, 2, 42, 99, etc. It even means negative numbers -5 or -123487262. The math teacher might say that integers are whole numbers.
But a lot of things need a lot more flexibility. The value of your debit account could be $105.55, which is a number between 105 and 106. The amount of fuel in your car’s gas tank isn’t 13 or 16 gallons, it’s probably something like 13.42 gallons, and changes by small amounts as you drive.
So Java has another type of number, a floating point number and in these early days in this book,
we will use double as the kind of number we use when we need a number that might not be a whole number, but rather real numbers.
A double can have decimal point and some number after, so I can write 3.5 or 42.0.
Or even more complicated numbers like:
3.14159
1000000.000001
7.5
55.0
14.0506
0.00678We will use throughout this book, two types of numbers. ints which are whole numbers like
2
0
-16
4560072615728And there are doubles which are real numbers like
1.5
0.0
-7.005
822.98676253
0.000000000000020983028029
3.1415926535897931
10.And it turns out Java has a few more types of numbers, more than just int and double. I’ll list them, but you’ll need to go to a larger Java book or website to understand how they are different from int and double.
There are four more types of numbers: long, short, byte, and float. Long, short, and byte are whole numbers and float is a real number.
In Java, there are parts of a program and different parts have different names. Two of the most basic (and fundamental) are statements and expressions.
An expression is something that needs to be computed to find out the answer. Here are a few simple ones.
2 + 2 * 65536
speed > 55.0
regularPrice * (1.0 - salePercentOff)Each of these lines is something we’d like Java to compute for us. That computation is often referred to as "evaluation" or "evaluate the expression" to get to the answer. There are two kinds of expressions in Java, arithmetic expressions and boolean expressions.
Arithmetic expressions are, as their name implies, something that require arithmetic to get the answer. An expression like "5 + 8 - 3" gets evaluated to 10. So an arithmetic expression will end up being a number.
Boolean expressions result in either a True or a False value. Example: "maxSpeed > 500.0" - this is either true or false depending on the value of maxSpeed. Or "homeTeamScore > visitorTeamScore" which will be true is and only if the Home team’s score is greater than the Visitor team’s score. Both scores are numbers, the result of the greater than makes the result of the epxression a boolean expression (either true or false).
A statement is just a line of Java. It ends with a ';' (semi-colon).
// at the Grocery
double salesTaxRate = 0.06;
double totalGroceries = 38.99;
double salesTax = totalGroceries * salesTaxRate;
double chargeToCard = totalGroceries + salesTax;And this is what a Java program looks like. It’s just a list of statements, one after the other, that get computed from the top down.
Some of the statements have expressions in them (like totalGroceries * salesTaxRate), while some are just simple assignment statements (like totalGroceries = 38.99, where we assign the variable 'totalGroceries' the value 38.99). Don’t panic. These are just some simple examples of Java to give you a feel for it. We’ll go thru each of these kinds of things slowly in sections ahead.
In this book, you may see that the code used in examples is longer than can fit on one line in the code boxes. Well, Java doesn’t care. That’s why it has semi-colons ';' at the end of the statements. So to be clear, a statement with long variable names is the same as one with a short name.
k = h * kph - (rest / 60);
// OR
kilometersCycled = numberOfHoursPedalled * kilometersPerHour - (totalMinutesOfRest / 60);When you come across code that goes onto multiple lines, do like Java does, read until you find the ';'. It’s like a period in an English sentence.
Very often in Java, we will see a block of statements. It is a list of statements inside of a pair of curly-braces "{ }". It acts like a container to make clear what statements are included in the block.
if (magePower > 120.0) {
maxMagic = 500.0;
lifeSpan = 800.0;
maxWeapons = magePower / maxPowerPerWeapon;
}
// some more codeSee those curly-braces? They start and stop the block, and contain the statements within. You can also see how the code is indented, but the real key are those braces. You’ll see lots of blocks when you’re looking at Java code.
And, while this is a bad idea, this code:
if (wizardStrength > 120.0) { maxMagic = Wizard.maxpower(); lifeSpan = Wizard.maxlife(); maxWeapons = wizardStrength * numberOfWands; }is identical to this:
if (wizardStrength > 120.0) {
maxMagic = Wizard.maxpower();
lifeSpan = Wizard.maxlife();
maxWeapons = wizardStrength * numberOfWands;
}But the SECOND example is formatted much cleaner, making it more readable and therefore easier to understand. So I encourage you to make your code easy to read by keeping it tidy. Why? Well, if no other reason than that it is what the professionals do.