Getting Started with Java
Optional Reading
Depending on which (if any) IDE you want to you, read the following tutorials, before, or after, reading this section. They may provide some additional help on using your IDE.
Which Java Version should I use?
The best advice is to use the latest Java version available. For a unofficial history of Java Versions, you can read this (if you are interested).
Please note that many of you have heard of the JDK and the JRE for Java. The "Java Runtime Environment" let you run Java apps, but not build them. The JRE is no longer available, as it seems Oracle wants developers to bundle (and pay license fees) for Java Desktop Apps.
The current version of Java is "Java 19" (although by the time you read this it may be Java 20, 21, 22, etc).
Java is available for free from Sun at https://java.sun.com if you are using it for development purposes only, I actually recommend using OpenJDK (shown below), because the licensing is much safer. For example (and I'm not exaggerating) if you download the Oracle JDK to a recognizable commercial domain, Oracle has been known to track people down and ask their companies to pay the fees for the use of their software in a commercial environment.
For server-side applications, the choice of Java versions is really dependent on what your applications server supports, and how "flexible" you want your web application to be in terms of supporting different, and possibly older, web-servers.
Since Java is backward compatible, you can always use an program written for an older version on a newer version of the JVM. If you developed an applications using JDK 1.4, it will probably run on JDK 14. There are a very few things that make older versions not compatible with newer JDK versions. This is because a few new keywords have been introduced in the newer versions that may conflict with older versions that the use of those keywords as variable names was allowed.
Interestingly, one of the things that won't run on the latest versions of Java is something called JavaFX. This was taken out of the JDK (but Swing still remains).
Now, plenty of companies still stayed with JDK 1.8 (Java 8) for a multitude of reasons. Now the obious question is what has changed since then and now?
Much of the info below is taken from https://www.marcobehler.com/guides/a-guide-to-java-versions-and-features if you want to take a look at a bit more of a complete breakdown, but I've pulled the highlights into the following summaries:
Collections got a couple of new helper methods, to easily construct Lists, Sets and Maps.
List<String> list = List.of("one", "two", "three"); Set<String> set = Set.of("one", "two", "three"); Map<String, String> map = Map.of("foo", "one", "bar", "two");
Streams got a couple of additions, in the form of takeWhile,dropWhile,iterate methods.
Stream<String> stream = Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10);
Interfaces got private methods:
public interface MyInterface { private static void myPrivateMethod(){ System.out.println("Yay, I am private!"); } }
There have been a few changes to Java 10, like Garbage Collection etc. But the only real change you as a developer will likely see is the introduction of the "var"-keyword, also called local-variable type inference.
// Pre-Java 10 String myName = "Marco"; // With Java 10 var myName = "Marco"
Strings and Files got a couple new methods (not all listed here):
"Marco".isBlank(); "Mar\nco".lines(); "Marco ".strip(); Path path = Files.writeString(Files.createTempFile("helloworld", ".txt"), "Hi, my name is!"); String s = Files.readString(path);
Nothing really here except Unicode support
Again, not much new, more Unicode updates, some NIO updates, but not too much. There was a preview to allow Switch statements to return a value though:
Old switch statements looked like this:
switch(status) { case SUBSCRIBER: // code block break; case FREE_TRIAL: // code block break; default: // code block }
New statements can look like this:
boolean result = switch (status) { case SUBSCRIBER -> true; case FREE_TRIAL -> false; default -> throw new IllegalArgumentException("something is murky!"); };
Also, you can now do multiline strings!
String htmlBeforeJava13 = "<html>\n" + " <body>\n" + " <p>Hello, world</p>\n" + " </body>\n" + "</html>\n"; String htmlWithJava13 = """ <html> <body> <p>Hello, world</p> </body> </html> """;
The switch expressions that were preview in versions 12 and 13, are now standardized.
(Preview) There are now record classes, which help alleviate the pain of writing a lot of boilerplate with Java. Have a look at this pre Java 14 class, which only contains data, (potentially) getters/setters, equals/hashcode, toString.
final class Point { public final int x; public final int y; public Point(int x, int y) { this.x = x; this.y = y; } }is now record Point(int x, int y) { }
Finally NullPointerExceptions describe exactly which variable was null.
Multiline Strings as showed above are now standard.
A new way of controlling subclasses was introduced. If you ever wanted to have an even closer grip on who is allowed to subclass your classes, there’s now the sealed feature.
public abstract sealed class Shape permits Circle, Rectangle, Square {...}
This means that while the class is public, the only classes allowed to subclass Shape are Circle, Rectangle and Square.
Pattern matching for instandeof:
This:
if (obj instanceof String) { String s = (String) obj; // e.g. s.substring(1) }
Now became this:
if (obj instanceof String s) { // Let pattern matching do the work! // ... s.substring(1) }
You can now connect to Unix domain sockets (also supported by macOS and Windows (10+).
socket.connect(UnixDomainSocketAddress.of( "/var/run/postgresql/.s.PGSQL.5432"));
Java 17 is the new long-term support (LTS) release of Java, after Java 11.
public String test(Object obj) { return switch(obj) { case Integer i -> "An integer"; case String s -> "A string"; case Cat c -> "A Cat"; default -> "I don't know what it is"; }; }
UTF-8 is now the default.
The JDK now includes a simple webserver that you can start by typing "jwebserver"
Java 19 added a few new useful features, but it should be noted that they are all in "Preview mode" so they may change in future releases.. These include
Since Java 1.0, there had been a Security Manager. It’s now deprecated and will be removed in a future version.
Which Java Version will we use for this class?
We will be using the LTS Java 17 and Tomcat 10 as the web server for the class. This is the server your homework must run on when we do Servlets and JSP later on. All of my examples are run on the Tomcat server.
There is no mandated Integrated Development Environment (IDE) or editor to use for this class. However, to make it much easier for the students I am recommending to download the Eclipse Java EE Tools Bundle. This bundles Java, the Java EE libraries you will need, and an IDE which will work with a web server in one package. If you wish to use Netbeans (or something else), feel free, but I'm not able to support questions on the other IDEs (it's hard enough keeping up with the changes in one!), so if you use Netbeans, you'll have to figure out Netbeans specific issues yourself.
Modern web applications have a specific structure regarding where to place different types of files within a directory structure. IDEs now do a good job of helping you placed the appropriate files in the appropriates places. In addition, many of these IDEs have excellent debugging features and version control integration that make them a logical choice to use when developing code.
Installing the Java Development Kit (JDK)
Below is the Windows install of Java. If you are on Linux or a Mac, installation is very similar. Unfortunately, I don't have a Mac, and can't run a Mac VM on a non-Mac, so you'll be on your own for the Mac. Past semesters have had a decent percentage of students on Macs, and they don't seem to have had too many difficulties.
Now it turns out, there are several sources for Java Development Kits. It used to be that Sun Microsystems was the only provider, then Oracle took over, and split Java to the OpenJDK and Oracle Java. Well, it turns out that a number of big vendors liked the OpenJDK but wanted better support and maintenance than Oracle gives with the OpenJDK. Eclipse became the caretaker and you can currently get probably the best JDK from "adoptium" (yeah, strange name, but if you look at the companies supporting this it is a good sign.
As of June 2021, there are 10 members for Adoptium
Now to make things even MORE confusing (or less as the case may be), in November of 2021, Oracle reversed their policy. (see https://blogs.oracle.com/cloud-infrastructure/post/introducing-free-java-license for details) and now once again, the Oracle JDK 17+ is now free for all (even business) to use. So, my recommendation is to use the Oracle JDK, as it even has a nice installer, is packaged for Linux, or has a nice tar for Linux.
First I'll go over the install for the Oracle JDK, then look at some alternatives as well, but...I'm going to assume you are using the Oracle JDK. The JDK 17 LTS release will be supported by Oracle until September 2024
Okay, first go to the Oracle download site, now because I'm a stinker, I will use the "classic" URL that is still supported (and forwards to the Oracle URL), yep, just go to https://java.sun.com (easy to remember!).
Click on the Java SE 17.x.x download link.
Note that their are installers for Linux, macOS and Windows. A few notes here, yes the Linux releases have been packaged for Debian and RPM installs, but if you scroll down a bit you will find this
Which will lead you to a page with these oh-so-useful URLs!
For my Linux boxes, I tend to use these bundles rather than the deb/rpm ones.
With regard to Windows, if you click on the Windows "tab" you will see the following:
Let's take a look at the MSi Instller verion and run it:
Click on Next>
Default location should be fine, click Next> (be aware, you may have some permission window popup under your install window, making it look like the installer is hanging)
Okay, if you want more you can hit "Next Steps" otherwise hit "Close".
Check your install by opening a command prompt and typing "java -version" to make sure your install worked
You are done at this point. The examples below show the installation of alternate JDKs if you don't install the Oracle version
I'm going to go over installation of the Adoptium release of the the OpenJDK first, then I'll present an alternative JDK by OpenJDK itself.
To get the latest version of the JDK from Adoptium, go to https://adoptium.net/index.html
Download the desired release. Note the LTS (Long Term Support) versions are definitely recommended if you don't want to constantly have to update your JDK version, they will be supported for as long as Oracle supports the LTS versions. This is from the Oracle website, which indicates support of LTS versions for at least EIGHT years!!!
Java LTS releases, such as Java 11 and Java 17, are similar to Firefox’s Extended Support Releases. Oracle’s updates to Java LTS releases provide only stability, security, and performance improvements—not new features. This reduces the risk that an update could break interaction with a tool or library. Organizations can count on Java LTS releases being available for at least eight years, providing ample time for toolchains to solidify and for developers to transition to another LTS several years later.
Java 8 is in fact supported until 2030, so these LTS versions are just as they say, Long Term.
So, the web page will auto-detect your OS and provide a recommended download, but you can claerly chose the other options for more choices.
Clicking on the Latest Release gets an MSI installer file for my Windows paltform (you get a .tar.gz file for Linux). Running the installer gets you:
Click Next
At this point you see installer options. Unlike installing the OpenJDK, this installer acts like Java installers of old and actually sets up your Windows machine to work with Java. Note that it adds Java to the PATH and also associates JAR files with Java. Go ahead and change the Set JAVA_HOME variable option to Install...
Now click Next
At this point you are ready to install, so go ahead and select the Install button.
And eventually you should see.
Click Finish.
If you bring up a Command Prompt and run "java -version", you should see the following indicating a succesful install. Look for the "Temuring" text indicated the correct version was installed.
Okay, this is the recommended way of getting a fully functioining JDK, as an alternative, I have a video showing the steps you need to take to install the OpenJDK on a Windows machine. You will see that they are a bit more involved, but not too bad.
Download the Java SDK from https://jdk.java.net. On the page, there will be a Java link for your operating system, select this. You will want to download the latest JDK. (Note that there may be minor changes in the look of the screens for newer versions).
The video below will walk you through the installation of the OpenJDK. Since no installer is provided, you have to make two changes to Environmental Variables in Windows in order for Java to work on your system. These changes are shown in the video. While this video shows installation of JDK 17, it should apply to future versions as well.
Accessing the Java Documentation
There is an API documentation page at https://jdk.java.net. Go to the Java version you downloaded, and then select "API Javadoc"
...and NOW you are done installing Java!
Installing the Java IDE
For this course, we will use Eclipse, but you may see a few stray screens-hots of earlier version. If so, there shouldn't be major differences.
Again, I figure a video will be easier for you to follow than a bunch of screens-hots, so here is the installation instructions for Eclipse.
Download the Java EE Tools Bundle from https://www.eclipse.org.
Click on the Download button (in this window it is at the top right)
Now you will see this screen, but don't click the Download button!
Take a look at that subtle link below the Orange Download x86_64 button, yes, click on the Download Packages link to get to this screen.
Scroll down and look for the Eclipse IDE for Enterprise Java and Web Developers section
Select the architecure that matches your development platform and download that package.
And then click Download. This may take a bit, so be patient. This release is just a zip file. Now Eclipse is tied back to the glory days of Unix, and there is no "Installer" for this, you just plop it in a directory and then run the eclipse.exe file. Ah those were the simpler days. Anyways, copy it to a directory you would like on your system. Me, being the Unix nerd that I am, always put it in /usr/local, even on a Windows box, so once you copy it, you should have this.
If you run the eclipse.exe file, you should see the following.
And then the initial eclipse screen. Now this lets you determine where your projects live. You can choose any directory you want, and you can in fact use multiple locations for different projects.
Okay, once you get to the main screen, choose to go to the projects and you should see an empty workspace.
First thing is to get any updates, by selecting Help-> Check for Updates
Now select Window->Preferences to bring up this monster of a menu
Click on Java->Installed JREs and select the JDK you installed. Click on the "add" button and add the JRE you installed. Below shows the Oracle JDK that was installed earlier. Note I added "Oracle" to the JRE name:
We don't need to realy change anything else here...yet...but once we have Tomcat installed, we will edit the Server window and associate our local web server.
Bob
This won't be the last software install we will be doing, but the next, Tomcat, will be covered in a later module.
Your first Java program
Start Eclipse.
Use the menu and select File->New Project... as shown below. Note that some of the screens-hots may show earlier Eclipse versions as the application. This is because there is no significant change between the versions for the features shown.
The first thing you want to do is to create a New Project
A New Project wizard panel appears.
There are a few things to note about this window. First, the name of the Project is blank...you can name it anything you want.
Next option is where to store your source code, I always leave the default option selected.
Now we get to the JRE. As I mentioned in the Video, if you don't see your JDK installation that you performed earlier, you need to first click on the "Configure JREs..." option to come up with a panel like this:
If you click on the "Add button" you can add the JDK you installed to the list of JREs, you can then use this in your projects.
GUI tidbit: Take a look at the buttons in the above window. This is an excellent example of Button "standards".
Okay, back to our initial New Project panel. For these first few homeworks (the ones that are Java *application*). You can use the default JRE settings. Once we hit the web server applications, then you will need to have your project settings looking like what I have above, because you need to use the JDK you installed, but you need to compile to the Java 1.8 (Java 8) standard.
So, fill in the project name and click Next>
This second window is used to add more information to a project. While you usually don't mess with many of these, you may occasionally want to click on the Libraries tab to add jar files to a project.
For example, if I want to use MySQL in this project, I'll need to add the MySQL JDBC connector JAR file. Having it in a library folder for the project isn't enough, you need to tell the project that it has a JAR file that it needs to use for the execution of the project (we'll see more on this later).
Click Finish. You should see your new project in Eclipse (I've already expanded the project name so you can see details)
you can create new classes several ways, you can use the main menu bar, or I prefer to just right click on the project name and then select New->Class
To create our first Java class, right click on the "example1" node of the tree, the top menu item is New, select that and then select "Java Class". The following window will appear:
Okay, Again, you have the ability to initialize several traits on this new Class.
When done, your window should look something like this.
You can now select Finish and then you should see a new class in the src folder for the project.
Lets take a look a bit more at this window before we go on.
Notice that in the src folder, there is now a package entry "com.rbevans.example1", that holds our HelloWorld.java entry. In addition, eclipse is nice enough to remind you that you need to fill in some code in the main() method (the TODO comment).
It may also help to note that if you look to the right of the HelloWorld.java scrollbar, you'll see a small blue rectangle. This is a visual indication of the TODO text. When we replace the TODO comment, it goes away.
So, our next step is to put a "System.out.println()" statement in the main method. The main method is executed when you run a Java application, so this line to output Hello World will execute when we run the app.
Again, you can run the application several ways, I usually just right click on the project name and then select "Run As -> Java Application"
When you do this you will see the following in the Console panel (the panel at the bottom)
Note that the console shows our "Hello World!" output. You could have also run the application by clicking on the Green Circle with the "play" icon inside, and then selecting Run As->Java Application.
Before you continue, read the Java Tutorial on Classes and Objects which gives an excellent overview of learning about Java classes.
There are already several lines of text in this file. Some are comments, some are actual code. Comments in Java can be in three forms
Comment identifier |
Usage |
// | Any text to the right of these characters is a comment. |
/* comments */ | Any text between the /* and */ characters is a comment, this may be multiple lines |
/** comments */ | This is a special type of comment, known as a Javadoc comment. It is still a comment, but there is a tool to pull these comments out of your code to make online documentation |
Comments help you understand your own code, or somebody else's. If a line of text isn't a comment, it actually does something in your code.
As mentioned earlier, the first non-comment lines in a Java class are package statements. In our case we have the statement
package example1;
which says that this Test class, is qualified to be in the example1 package, and will be referenced later by its fully qualified name of example1.Test1.
The next non comment line is the following:
public class HelloWorld {
This is a Java class definition. The first word public, defines an access level modifier. This means it is visible to all classes everywhere. If it did not have the public keyword, it would only be visible to classes within its own package, example1. See the Java tutorial on access control for a more detailed description of access modifiers.
The next two words indicate you are defining a Java class named Test. Note the curly brace "{" after the class name. This indicates the start of the definition of the class, and is required.
The next two lines of code are the constructor for the Test object.
public HelloWorld() { }
As was mentioned earlier, an object needs a main method to let execution begin with this object. The main method always has a form of:
public static void main(String[] args) { // do something }
When you first execute a Java class, this is the method that is called first. In our example, we are going to print something out to Standard Out (stdout), otherwise known as the console. To do that we use the
System.out.println("some text");
method to output some text out to the screen. If we change the method above to:
public static void main(String[] args) { System.out.println("Hello World!"); }
Congratulations! You've just made your first Java program!
It is possible to compile an run a Java program from a command line, using the javac program to compile the code and the java program to run the code. This sometimes requires a bit more knowledge of how to set up the environment (such as CLASSPATH variables) .
Java Coding Style Guide
I've provided a coding guideline I wrote a few years ago (CodeGuidelines.pdf). There are a few new features in JDK that aren't included in this (like generics), but at least it should suffice for anything you need to do for this class.
While I'm not going to get picky with coding styles, I do expect certain things to always be followed from the coding guidelines above (in other words, if you don't follow the guidelines below, you will miss a few points on your grade).