Java Articles
Java powers much of the online world and tons of apps and programs. You can read all about it right here. (Perhaps over a cup of java?)
Articles From Java
Filter Results
Cheat Sheet / Updated 01-11-2023
Writing Java statements (like for and if) and classes (like Math and NumberFormat) help you start and build strong programs. Variables hold different kinds of Java data types: numbers, characters, and true/false numbers. You designate Java operations that can be performed on operands, including arithmetic operators, relational operators (or binary) and logical operators (or Boolean).
View Cheat SheetCheat Sheet / Updated 02-25-2022
When doing anything with Java, you need to know your Java words — those programming words, phrases, and nonsense terms that have specific meaning in the Java language, and get it to do its thing. This Cheat Sheet tells you all about Java's categories of words.
View Cheat SheetArticle / Updated 01-13-2022
In Listing 1, below, you get a blast of Java code. Like all novice programmers, you're expected to gawk humbly at the code. But don't be intimidated. When you get the hang of it, programming is pretty easy. Yes, it's fun, too. Listing 1: A Simple Java Program /* * A program to list the good things in life * Author: Barry Burd, [email protected] * February 10, 2021 */ public class ThingsILike { public static void main (String[] args) { System.out.println("Chocolate, royalties, sleep"); } } Buried deep in the heart of Listing 1 is the single line that actually issues a direct instruction to the computer. The line System.out.println("Chocolate, royalties, sleep"); tells the computer to display the words Chocolate, royalties, sleep in the command prompt window. This line can be described in at least two different ways: It's a statement: In Java, a direct instruction that tells the computer to do something is called a statement. The statement in Listing 1 tells the computer to display some text. The statements in other programs may tell the computer to put 7 in certain memory location, or make a window appear on the screen. The statements in computer programs do all kinds of things. It's a method call: A method call is a separate piece of code (in a different part of the Java program) that tells the computer to call the method into action.The statement <tt>FixTheAlternator(junkyOldFord);</tt> is an example of a method call, and so is <tt>System.out.println("Chocolate, royalties, sleep");</tt> Java has many different kinds of statements. A method call is just one kind. Ending a statement with a semicolon In Java, each statement ends with a semicolon. The code in Listing 1 has only one statement in it, so only one line in Listing 1 ends with a semicolon. Take any other line in Listing 1, like the method header, for instance. The method header (the line with the word main in it) doesn't directly tell the computer to do anything. Instead, the method header describes some action for future reference. The header announces "Just in case someone ever calls the main method, the next few lines of code tell you what to do in response to that call." Every complete Java statement ends with a semicolon. A method call is a statement, so it ends with a semicolon, but neither a method header nor a method declaration is a statement. The method named System.out.println The statement in the middle of Listing 1 calls a method named System.out.println. This method is defined in the Java API. Whenever you call the System.out.println method, the computer displays text on its screen. Think about the name Pauline Ott, for example. Believe it or not, I know two people named Pauline Ott. One of them is a nun; the other is physicist. Of course, there are plenty of Paulines in the English-speaking world, just as there are several things named println in the Java API. So to distinguish the physicist Pauline Ott from the film critic Pauline Kael, write the full name "Pauline Ott." And, to distinguish the nun from the physicist, write "Sister Pauline Ott." In the same way, write either System.out.println or DriverManager.println. The first writes text on the computer's screen. The second writes to a database log file. Just as Pauline and Ott are names in their own right, so System, out, and println are names in the Java API. But to use println, you must write the method's full name. You never write println alone. It's always System.out.println or some other combination of API names. The Java programming language is case-sensitive. If you change a lowercase letter to an uppercase letter (or vice versa), you change a word's meaning. You can't replace System.out.println with system.out.Println. If you do, your program won't work. The Java class You may have heard the term object-oriented programming (also known as OOP). OOP is a way of thinking about computer programming problems — a way that's supported by several different programming languages. OOP started in the 1960s with a language called Simula. It was reinforced in the 1970s with another language named Smalltalk. In the 1980s, OOP took off big time with the language C++. Some people want to change the acronym, and call it COP, class-oriented programming. That's because object-oriented programming begins with something called a class. In Java, everything starts with classes, everything is enclosed in classes, and everything is based on classes. In Java, your main method has to be inside a class. The code in Listing 1 starts with the words class ThingsILike. Take another look at Listing 1, and notice what happens after the line class ThingsILike. The rest of the code is enclosed in curly braces. These braces mark all the stuff inside the class. Without these braces, you'd know where the declaration of the ThingsILike class starts, but you wouldn't know where the declaration ends. It's as if the stuff inside the ThingsILike class is in a box. To box off a chunk of code, you do two things: You use curly braces: These curly braces tell the compiler where a chunk of code begins and ends. You indent code: Indentation tells your human eye (and the eyes of other programmers) where a chunk of code begins and ends. Don't forget. You have to do both.
View ArticleArticle / Updated 01-13-2022
The late 1980s saw several advances in software development, and by the early 1990s, many large programming projects were being written from prefab components. Java came along in 1995, so it was natural for the language's founders to create a library of reusable code. The library included about 250 programs, including code for dealing with disk files, code for creating windows, and code for passing information over the Internet. Since 1995, this library has grown to include more than 4,000 programs. This library is called the Application Programming Interface (API). Every Java program, even the simplest one, calls on code in the Java API. This Java API is both useful and formidable. It's useful because of all the things you can do with the API's programs. It's formidable because the API is so extensive. No one memorizes all the features made available by the Java API. Programmers remember the features that they use often, and look up the features that they need in a pinch. So many ways to write computer programs To write Java programs, you need four tools: A Java compiler A Java Virtual Machine. The Java API. The Java API documentation. The Java smorgasbord This section explains some of the terminology you might see as you travel through the Java ecosystem. Medium Java, little Java, and gigantic Java At some point, you may see mention of Java SE, Java ME, or Java EE. Here’s the lowdown on these three kinds of “Java E”: Java Standard Edition (Java SE): This is the only edition you should think about (for now, anyway). Java SE includes all the code you need in order to create general-purpose applications on a typical computer. Nowadays, when you hear the word Java, it almost always refers to Java SE. Java Micro Edition (Java ME): The Micro Edition contains code for programming special-purpose devices such as television sets, printers, and other gadgets. Java Enterprise Edition (Java EE): In 1999, the stewards of Java released an edition that was tailored for the needs of big companies. The starring role in this edition was a framework called Enterprise JavaBeans — a way of managing data storage across connected computers. In 2017, Oracle walked away from Java EE, handing it over to the Eclipse Foundation, which renamed it Jakarta EE. The rest of this book deals exclusively with Java Standard Edition. How do you type this stuff? A computer program is a big piece of text. So to write a computer program, you need a text editor — a tool for creating text documents. A text editor is a lot like Microsoft Word, or like any other word processing program. The big difference is that the documents that you create with a text editor have no formatting whatsoever. They have no bold, no italic, no distinctions among fonts. They have nothing except plain old letters, numbers, and other familiar keyboard characters. That's good, because computer programs aren't supposed to have any formatting. A document with no formatting is called a plain text document. Documents without formatting are fairly simple things, so a typical text editor is easier to use than a word processing program. (Text editors are a lot cheaper than word processing programs, and they're lightning fast. Even better, text editors take very little space on your hard drive.) You can use a word processor, like Microsoft Word, to create program files. But, by default, word processors insert formatting into your document. This formatting makes it impossible for a Java compiler to do its job. Using word processors to write Java programs isn't recommended. But, if you must use a word processor, be sure to save your source files with the .java extension. (Call a file SomeName.java.) Remember, also, to use the Save As command to save with the plain text file type. Using a customized editor Even if you don't use an integrated development environment, you can use other tools to make your programming life easy. Think, for a moment, about an ordinary text editor — an editor like Windows Notepad. With Notepad you can Create a document that has no formatting Find and replace characters, words, and other strings Copy, cut, and paste Print Not much else Notepad is fine for writing computer programs. But if you plan to do a lot of programming, you may want to try a customized editor. These editors do more than Windows Notepad. They have Syntax highlighting Shortcuts for compiling and running programs Explorer-like views of your works in progress Code completion Other cool stuff When it comes to choosing a custom editor, one favorite is IntelliJ IDEA. IntelliJ Idea comes in two different editions: Ultimate Edition or Community Edition. The Community Edition is free. To download the IntelliJ IDEA Community Edition, visit www.jetbrains.com/idea/download.
View ArticleArticle / Updated 01-13-2022
Sometimes, error messages can strike fear into the heart of even the bravest programmer. Fortunately some helpful, calming advice is here — advice to help you solve the problem when you see one of these messages. NoClassDefFoundError You get this error when you're trying to run your code. So first ask yourself, did you attempt to compile the code? If so, did you see any error messages when you compiled? If you saw error messages, look for things you can fix in your .java file. Try to fix these things, and then compile the .java file again. If you normally keep code in the JavaPrograms directory, make sure that you're still working in this JavaPrograms directory. (In Windows, make sure that the command prompt says JavaPrograms.) Make sure you have an appropriately named .class file in your working directory. For instance, if you're trying to run a program named MyGreatProg, look for a file named MyGreatProg.class in your working directory. Check your classpath to make sure that it contains the .class file that you need. For example, if all your Java code is in your working directory, make sure that the classpath includes a dot. NoSuchMethodError When you encounter this error message, check for the misspelling or inconsistent capitalization of a method name. Check the capitalization of main (not Main). When you issue the java command (or do whatever you normally do to run a program in your environment), does the class that you're trying to run contain its own main method? If not, then find the class with the main method and run that class instead. Cannot Resolve Symbol If you get an error message that includes cannot resolve symbol, check the spelling and capitalization of all identifiers and keywords. Then check again. If the unresolved symbol is a variable, make sure that this variable's declaration is in the right place. For instance, if the variable is declared in a for loop's initialization, are you trying to use that variable outside the for loop? If the variable is declared inside a block (a pair of curly braces), are you trying to use that variable outside of the block? Finally, look for errors in the variable's declaration. If the compiler finds errors in a variable's declaration, then the compiler can't resolve that variable name in the remainder of the code. Expected ';' (Or Expected Something Else) When you see an error message that says ';' expected, go through your code and make sure that each statement and each declaration ends with a semicolon. If so, then maybe the compiler's guess about a missing semicolon is incorrect. Fixing another (seemingly unrelated) error and recompiling your code may get rid of a bogus ';' expected message. For a missing parenthesis, check the conditions of if statements and loops. Make sure each condition is enclosed in parentheses. Also, make sure that a parameter list (enclosed in parentheses) follows the name of each method. For an expected message, check your assignment statements. Make sure that each assignment statement is inside a method. (Remember, a declaration with an initialization can be outside of a method, but each plain old assignment statement must be inside a method.) For the 'class' or 'interface' expected message, make sure you've spelled the word class correctly. If your code has an import declaration, check the spelling and capitalization of the word import. Missing Method Body or Declare Abstract You get a missing method body or declare abstract message when the compiler sees a method header, but the compiler can't find the method's body. Look at the end of the method's header. If you ended the header with a semicolon, then try removing the semicolon. If the header doesn't end with a semicolon, then check the code immediately following the header. The code immediately following the header should start with an open curly brace (the beginning of a method body). If some code comes between the header and the body's open curly brace, consider moving that code somewhere else. An 'else' without an 'if' Compare the number of if clauses with the number of else clauses. An if clause doesn't need to have an else clause, but each else clause must belong to an if clause. Remember, you enclose an if condition in parentheses, but you don't put a semicolon after the condition. Did you mistakenly end an if condition with a semicolon? Look at all the lines between an if and its else. When you find more than one statement between an if and its else, look for curly braces. If the statements between the if and its else aren't surrounded by curly braces, you may have found the culprit. Non-static Variable Cannot Be Referenced from a Static Context Lots of things can give you a non-static variable cannot be referenced from a static context error message. But for beginning programmers, the most common cause is having a variable that's declared outside of the main method. It's no sin to declare such a variable, but because the main method is always static, you need some special help to make the main method refer to a variable that's declared outside the main method. The quickest solution is to put the word static in front of the variable's declaration. But first, ask yourself why this variable's declaration isn't inside the main method. If there's no good reason, then move the variable's declaration so that it's inside the main method. FileNotFoundException (The System Cannot Find the File Specified) or EOFException If you encounter a FileNotFoundException message, check that the file named in your code actually exists. (Look for the file using your system's explorer or using the command prompt window.) Double-check the spelling in your code against the name of the file on your hard drive. If you've found a correctly named file on your hard drive, make sure that the file is in the correct directory. (For a program running in your working directory, a typical data file is in the working directory also.) If you're a Windows user, make sure that the system didn't add an extra .txt extension when you created the file. (Use the command prompt window to check the file's name. Windows Explorer can hide the .txt extension, and that always leads to confusion.) For an EOFException, you're probably trying to read more data than you have in the file. Very often, a small logic error makes your program do this. So do a careful review of all the steps in your program's execution. Look for subtle things, like improperly primed loops or the reading of array values past the array's largest index. Look for conditions that use <= when they should use <. Conditions like these can often be troublesome.
View ArticleArticle / Updated 01-13-2022
Most Java programs don’t work correctly the first time you run them, and some programs don’t work without extensive trial and error on your part. This code is a case in point. To write this code, you need a way to generate three-letter words randomly. This code would give you the desired result: anAccount.lastName = " + (char) (myRandom.nextInt(26) + 'A') + (char) (myRandom.nextInt(26) + 'a') + (char) (myRandom.nextInt(26) + 'a'); Here’s how the code works: Each call to the Random.nextInt(26) generates a number from 0 to 25. Adding 'A' gives you a number from 65 to 90. To store a letter 'A', the computer puts the number 65 in its memory. That’s why adding 'A' to 0 gives you 65 and why adding 'A' to 25 gives you 90. Applying (char) to a number turns the number into a char value. To store the letters 'A' through 'Z', the computer puts the numbers 65 through 90 in its memory. So applying (char) to a number from 65 to 90 turns the number into an uppercase letter. Pause for a brief summary. The expression (char) (myRandom.nextInt(26) + 'A') represents a randomly generated uppercase letter. In a similar way, (char) (myRandom.nextInt(26) + 'a') represents a randomly generated lowercase letter. Watch out! The next couple of steps can be tricky. Java doesn’t allow you to assign a char value to a string variable. The following statement would lead to a compiler error: //Bad statement: anAccount.lastName = (char) (myRandom.nextInt(26) + 'A'); In Java, you can use a plus sign to add a char value to a string. When you do, the result is a string. So "" + (char) (myRandom.nextInt(26) + 'A') is a string containing one randomly generated uppercase character. And when you add (char) (myRandom.nextInt(26) + 'a') onto the end of that string, you get another string — a string containing two randomly generated characters Finally, when you add another (char) (myRandom.nextInt(26) + 'a') onto the end of that string, you get a string containing three randomly generated characters. So you can assign that big string to anAccount.lastName. That’s how the statement works. When you write a program, you have to be very careful with numbers, char values, and strings. This isn’t the kind of programming you do every day of the week, but it is a lesson that you need to be persistent in your Java programming.
View ArticleArticle / Updated 01-13-2022
You will probably find times when programming with Java that you need to display a window on your computer screen. This code has very little logic of its own. Instead, this code pulls together a bunch of classes from the Java API. import javax.swing.JFrame; import javax.swing.ImageIcon; import javax.swing.JLabel; class ShowPicture { public static void main(String args[]) { var frame = new JFrame(); var icon = new ImageIcon("androidBook.jpg"); var label = new JLabel(icon); frame.add(label); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } } You can create an instance of the Purchase class with the line var purchase1 = new Purchase(); So in the code, you can do the same kind of thing. You can create instances of the JFrame, ImageIcon, and JLabel classes with the following lines: var frame = new JFrame(); var icon = new ImageIcon("androidBook.jpg"); var label = new JLabel(icon); Here’s some gossip about each of these lines: A JFrame is like a window (except that it’s called a JFrame, not a “window”). The line var frame = new JFrame(); creates a JFrame object, but this line doesn’t display the JFrame object anywhere. (The displaying comes later in the code.) An ImageIcon object is a picture. At the root of the program's project directory, there is a file named androidBook.jpg. That file contains the picture. The line var icon = new ImageIcon("androidBook.jpg"); creates an ImageIcon object — an icon containing the androidBook.jpg picture. You can use almost any .gif, .jpg, or .png file in place of the (lovely) Android book cover image. To do so, drag your own image file to Eclipse's Package Explorer. (Drag it to the root of this example's project folder.) Then, in Eclipse's editor, change the name androidBook.jpg to your own image file's name. That's it! You need a place to put the icon. You can put it on something called a JLabel. The line var label = new JLabel(icon); creates a JLabel object and puts the androidBook.jpg icon on the new label’s face. If you read the previous bullets, you may get a false impression. The wording may suggest that the use of each component (JFrame, ImageIcon, JLabel, and so on) is a logical extension of what you already know. “Where do you put an ImageIcon? Well of course, you put it on a JLabel.” When you’ve worked long and hard with Java’s Swing components, all these things become natural to you. But until then, you look everything up in Java's API documentation. You never need to memorize the names or features of Java’s API classes. Instead, you keep Java’s API documentation handy. When you need to know about a class, you look it up in the documentation. If you need a certain class often enough, you’ll remember its features. For classes that you don’t use often, you always have the docs.
View ArticleArticle / Updated 01-05-2022
After you’ve created an array in Java, you can put values into the array’s components. For example, imagine you are the owner of a motel. The guests in Room 6 are fed up with all those mint candies that you put on peoples’ beds. They check out, and Room 6 becomes vacant. You should put the value 0 into the 6 component. You can do it with this assignment statement: guestsIn[6] = 0; On one weekday, business is awful. No one’s staying at the motel. But then you get a lucky break. A big bus pulls up to the motel. The side of the bus has a sign that says “Loners’ Convention.” Out of the bus come 25 people, each walking to the motel’s small office, none paying attention to the others who were on the bus. Each person wants a private room. Only 10 of them can stay at the Java Motel, but that’s okay, because you can send the other 15 loners down the road to the old C-Side Resort and Motor Lodge. Anyway, to register ten of the loners into the Java Motel, you put one guest in each of your ten rooms. Having created an array, you can take advantage of the array’s indexing and write a for loop, like this: for (int roomNum = 0; roomNum < 10; roomNum++) { guestsIn[roomNum] = 1; } This loop takes the place of ten assignment statements because the computer executes the statement guestsIn[roomNum] = 1 ten times. The first time around, the value of roomNum is 0, so in effect, the computer executes guestsIn[<b>0</b>] = 1; In the next loop iteration, the value of roomNum is 1, so the computer executes the equivalent of the following statement: guestsIn[<b>1</b>] = 1; During the next iteration, the computer behaves as if it’s executing guestsIn[<b>2</b>] = 1; And so on. When roomNum gets to be 9, the computer executes the equivalent of the following statement: guestsIn[<b>9</b>] = 1; Notice that the loop’s counter goes from 0 to 9. Remember that the indices of an array go from 0 to one fewer than the number of components in the array. Looping with room numbers from 0 to 9 covers all the rooms in the Java Motel. When you work with an array, and you step through the array’s components using a for loop, you normally start the loop’s counter variable at 0. To form the condition that tests for another iteration, you often write an expression like roomNum < arraySize, where arraySize is the number of components in the array.
View ArticleArticle / Updated 01-05-2022
There are a few things beginning Java programmers should know about variables and recycling. When you assign a new value to smallLetter, the old value of smallLetter gets obliterated. smallLetter is used twice, and bigLetter is used twice. That’s why they call these things variables. First, the value of smallLetter is R. Later, the value of smallLetter is varied so that the value of smallLetter becomes 3. When the computer executes this second assignment statement, the old value R is gone. Is that okay? Can you afford to forget the value that smallLetter once had? Yes, sometimes, it’s okay. After you’ve assigned a value to bigLetter with the statement bigLetter = Character.toUpperCase(smallLetter); you can forget all about the existing smallLetter value. You don’t need to do this: <b>// This code is cumbersome.</b> <b>// The extra variables are unnecessary.</b> char <b>smallLetter1</b>, bigLetter1; char <b>smallLetter2</b>, bigLetter2; <b>smallLetter1</b> = 'R'; bigLetter1 = Character.toUpperCase(smallLetter1); System.out.println(bigLetter1); <b>smallLetter2</b> = '3'; bigLetter2 = Character.toUpperCase(smallLetter2); System.out.println(bigLetter2); You don’t need to store the old and new values in separate variables. Instead, you can reuse the variables smallLetter and bigLetter. This reuse of variables doesn’t save you from a lot of extra typing. It doesn’t save much memory space, either. But reusing variables keeps the program uncluttered. Sometimes, you can see at a glance that the code has two parts, and you see that both parts do roughly the same thing. In such a small program, simplicity and manageability don’t matter very much. But in a large program, it helps to think carefully about the use of each variable.
View ArticleArticle / Updated 11-23-2021
Eclipse normally looks on your computer for Java installations and selects an installed version of Java to use for running your Java programs. Your computer may have more than one version of Java, so you may want to double-check Eclipse's choice of the Java version. The following steps show you how: On Windows or Linux: In Eclipse's main menu, select Window→Preferences. On a Mac: In Eclipse's main menu, select Eclipse→Preferences. As a result, Eclipse's Preferences dialog appears. In the tree on the left side of the Preferences dialog, expand the Java branch. Within the Java branch, select the Installed JREs sub-branch. Look at the list of Java versions (Installed JREs) in the main body of the Preferences dialog. In the list, each version of Java has a check box. Eclipse uses the version whose box is checked. If the checked version isn't your preferred version (for example, if the checked version isn't version 8 or higher), you can make some changes. If your preferred version of Java appears in the Installed JREs list, put a check mark in that version's check box. If your preferred version of Java doesn't appear in the Installed JREs list, click the Add button. When you click the Add button, a JRE Type dialog appears. In the JRE Type dialog, double-click Standard VM. As a result, a JRE Definition dialog appears. What you do next depends on a few different things. Fill in the dialog's JRE Home field. How you do this depends on your operating system. On Windows, browse to the directory in which you've installed your preferred Java version. On your Windows computers, that directory is either C:Program FilesJavajre8, C:Program FilesJavajdk1.8.0, C:Program Files (x86)Javajre8, or something of that sort. On a Mac, use the Finder to browse to the directory in which you've installed your preferred Java version. Type the name of the directory in the dialog's JRE Home field. My Mac has one Java directory named /System/Library/Java/Java Virtual Machines/1.6.0.jdk/Contents/Home and another Java directory named /Library/Java/JavaVirtualMachines/jdk 1.8.0.jdk/Contents/Home. (The first is for Apple's old version of Java; the second is for Oracle's new Java version.) You might also find Oracle's Java in the /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home directory. Directories like /System and /Library don't normally appear in the Finder window. To browse to one of these directories (to the /Library directory, for example), choose Go→Go to Folder in the Finder's menu bar. In the resulting dialog, type /Library and then press Go. As you navigate to the directory containing your preferred Java version, you may encounter a JDK 1.8.0.jdk icon or some other item whose extension is .jdk. To see the contents of this item, control-click the item's icon and then select Show Package Contents. On Linux, browse to the directory in which you've installed your preferred Java version. When in doubt, search for a directory whose name starts with jre or jdk. You might have one more thing to do back in the JRE Definition dialog. Look at the JRE Definition dialog's JRE Name field; if Eclipse hasn't filled in a name automatically, type a name (almost any text) in the JRE Name field. Dismiss the JRE Definition dialog by clicking Finish. Eclipse's Preferences dialog returns to the foreground. The box's Installed JREs list contains your newly added version of Java. Put a check mark in the check box next to your newly added version of Java. You’re almost done. (You have a few more steps to follow.) Within the Java branch on the left side of the Preferences dialog, select the Compiler sub-branch. In the main body of the Preferences dialog, you see a Compiler Compliance Level drop-down list. In the Compiler Compliance Level drop-down list, select a number that matches your preferred Java version. For Java 7, you select compliance level 1.7. For Java 8, you select compliance level 1.8. Whew! Click the Preferences dialog's OK button to return to the Eclipse workbench.
View Article