Java For Dummies, 8th Edition book cover

Java For Dummies, 8th Edition

By: Barry Burd Published: 03-28-2022

If you want to learn to speak the world's most popular programming language like a pro, Java For Dummies, 8th Edition is your ideal companion. This updated volume includes the new switch statement syntax, and with a focus on reusing existing code, it quickly and easily shows you how to create basic Java objects, work with Java classes and methods, understand the value of variables, and more.

Articles From Java For Dummies, 8th Edition

page 1
page 2
page 3
25 results
25 results
Java For Dummies Cheat Sheet

Cheat 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 Sheet
Using Streams and Lambda Expressions in Java

Article / Updated 05-10-2017

Java has fancy methods that make optimal use of streams and lambda expressions. With streams and lambda expressions, you can create an assembly line. The assembly-line solution uses concepts from functional programming. The assembly line consists of several methods. Each method takes the data, transforms the data in some way or other, and hands its results to the next method in line. Here’s an assembly line. Each box represents a bunch of raw materials as they're transformed along an assembly line. Each arrow represents a method (or, metaphorically, a worker on the assembly line). For example, in the transition from the second box to the third box, a worker method (the filter method) sifts out sales of items that aren't DVDs. Imagine Lucy Ricardo standing between the second and third boxes, removing each book or CD from the assembly line and tossing it carelessly onto the floor. The parameter to Java's filter method is a Predicate — a lambda expression whose result is boolean. The filter method sifts out items that don't pass the lambda expression's true / false test. Some Functional Programming Methods Method Name Member Of Parameter(s) Result Type Result Value stream Collection (for example, an ArrayList, object) (none) Stream A stream that spits out elements of the collection filter Stream Predicate Stream A new stream containing values for which the lambda expression returns true map Stream Function Stream A new stream containing the results of applying the lambda expression to the incoming stream reduce Stream BinaryOperator The type used by the BinaryOperator The result of combining all the values in the incoming stream In the transition from the third box to the fourth box, a worker method (the map method) pulls the price out of each sale. From that worker's place onward, the assembly line contains only price values. To be more precise, Java's map method takes a Function such as (sale) -> sale.getPrice() and applies the Function to each value in a stream. So the map method takes an incoming stream of sale objects and creates an outgoing stream of price values. In the transition from the fourth box to the fifth box, a worker method (the reduce method) adds up the prices of DVD sales. Java's reduce method takes two parameters: The first parameter is an initial value. In the image above, the initial value is 0.0. The second parameter is a BinaryOperator. In the image above, the reduce method's BinaryOperator is (price1, price2) -> price1 + price2 The reduce method uses its BinaryOperator to combine the values from the incoming stream. The initial value serves as the starting point for all the combining. So, the reduce method does two additions. For comparison, imagine calling the method reduce(10.0, (value1, value2) -> value1 * value2) with the stream whose values include 3.0, 2.0, and 5.0. The resulting action is shown below You might have heard of Google's MapReduce programming model. The similarity between the programming model's name and the Java method names map and reduce is not a coincidence. Taken as a whole, the entire assembly line up the prices of DVDs sold. The code above contains a complete program using the streams and lambda expressions the first image above. import java.text.NumberFormat; import java.util.ArrayList; public class TallySales { public static void main(String[] args) { ArrayList<Sale> sales = new ArrayList<>(); NumberFormat currency = NumberFormat.getCurrencyInstance(); fillTheList(sales); double total = sales.stream() .filter((sale) -> sale.getItem().equals("DVD")) .map((sale) -> sale.getPrice()) .reduce(0.0, (price1, price2) -> price1 + price2); System.out.println(currency.format(total)); } static void fillTheList(ArrayList<Sale> sales) { sales.add(new Sale("DVD", 15.00)); sales.add(new Sale("Book", 12.00)); sales.add(new Sale("DVD", 21.00)); sales.add(new Sale("CD", 5.25)); } } The code requires Java 8 or later. If your IDE is set for an earlier Java version, you might have to tinker with the IDE's settings. You may even have to download a newer version of Java. The boldface is one big Java assignment statement. The right side of the statement contains a sequence of method calls. Each method call returns an object, and each such object is the thing before the dot in the next method call. That's how you form the assembly line. For example, near the start of the boldface code, the name sales refers to an ArrayList object. Each ArrayList object has a stream method. In the code above, sales.stream() is a call to that ArrayList object's stream method. The stream method returns an instance of Java's Stream class. (What a surprise!) So sales.stream() refers to a Stream object. Every Stream object has a filter method. So sales.stream().filter⁣((sale) -> sale.getItem().equals("DVD")) is a call to the ⁣Stream object's filter method. The pattern continues. The Stream object's map method returns yet another Stream object — a Stream object containing prices. To that Stream of prices you apply the reduce method, which yields one double value — the total of the DVD prices.

View Article
Command Line Arguments in Java

Article / Updated 05-10-2017

Once upon a time, most Java programmers used a text-based development interface. They typed a command in a plain-looking window, usually with white text on a black background. The plain-looking window goes by the various names, depending on the kind of operating system that you use. In Windows, a text window of this kind is a command prompt window. On a Macintosh and in Linux, this window is the terminal. Some versions of Linux and UNIX call this window a shell. Anyway, back in ancient times, you could write a program that sucked up extra information when you typed the command to launch the program. In the image above, the programmer types java MakeRandomNumsFile to run the MakeRandomNumsFile program. But the programmer follows java MakeRandomNumsFile with two extra pieces of information: MyNumberedFile.txt and 5. When the MakeRandomNumsFile program runs, the program sucks up two extra pieces of information and uses them to do whatever the program has to do. The program sucks up MyNumberedFile.txt 5, but on another occasion the programmer might type SomeStuff 28 or BunchONumbers 2000. The extra information can be different each time you run the program. The next question is, “How does a Java program know that it’s supposed to snarf up extra information each time it runs?” Since you first started working with Java, you’ve been seeing this String args[] business in the header of every main method. Well, it’s high time you found out what that’s all about. The parameter args[] is an array of String values. These String values are called command line arguments. Some programmers write public static void main(String args[]) and other programmers write public static void main(String[] args) Either way, args is an array of String values. Using command line arguments in a Java program This bit of code shows you how to use command line arguments. This is how you generate a file of numbers import java.util.Random; import java.io.PrintStream; import java.io.IOException; public class MakeRandomNumsFile { public static void main(String args[]) throws IOException { Random generator = new Random(); if (args.length < 2) { System.out.println("Usage: MakeRandomNumsFile filename number"); System.exit(1); } PrintStream printOut = new PrintStream(args[0]); int numLines = Integer.parseInt(args[1]); for (int count = 1; count <= numLines; count++) { printOut.println(generator.nextInt(10) + 1); } printOut.close(); } } If a particular program expects some command line arguments, you can’t start the program running the same way you’d start most of the other normal programs. The way you feed command line arguments to a program depends on the IDE that you’re using — Eclipse, NetBeans, or whatever. Allmycode.com has instructions for feeding arguments to programs using various IDEs. When the code begins running, the args array gets its values. With the run shown in the image above, the array component args[0] automatically takes on the value "MyNumberedFile.txt", and args[1] automatically becomes "5". So the program’s assignment statements end up having the following meaning: PrintStream printOut = new PrintStream("MyNumberedFile.txt"); int numLines = Integer.parseInt("5"); The program creates a file named MyNumberedFile.txt and sets numLines to 5. So later in the code, the program randomly generates five values and puts those values into MyNumberedFile.txt. One run of the program gives you this. After running the code, where can you find the new file (MyNumberedFile.txt) on your hard drive? The answer depends on a lot of different things. If you use an IDE with programs divided into projects, then the new file is somewhere in the project’s folder. One way or another, you can change Listing 11-7 to specify a full path name — a name like "c:\\Users\\MyName\\Documents\\MyNumberedFile.txt" or "/Users/MyName/Documents/MyNumberedFile.txt". In Windows, file path names contain backslash characters. And in Java, when you want to indicate a backslash inside a double-quoted String literal, you use a double backslash instead. That’s why "c:\\Users\\MyName\\Documents\\MyNumberedFile.txt" contains pairs of backslashes. In contrast, file paths in the Linux and Macintosh operating systems contain forward slashes. To indicate a forward slash in a Java String, use only one forward slash. Notice how each command line argument is a String value. When you look at args[1], you don’t see the number 5 — you see the string "5" with a digit character in it. Unfortunately, you can’t use that "5" to do any counting. To get an int value from "5", you have to apply the parseInt method. The parseInt method lives inside a class named Integer. So, to call parseInt, you preface the name parseInt with the word Integer. The Integer class has all kinds of handy methods for doing things with int values. In Java, Integer is the name of a class, and int is the name of a primitive (simple) type. The two things are related, but they’re not the same. The Integer class has methods and other tools for dealing with int values. Checking for the right number of command line arguments What happens if the user makes a mistake? What if the user forgets to type the number 5 on the first line when you launch MakeRandomNumsFile? Then the computer assigns "MyNumberedFile.txt" to args[0], but it doesn’t assign anything to args[1]. This is bad. If the computer ever reaches the statement int numLines = Integer.parseInt(args[1]); the program crashes with an unfriendly ArrayIndexOutOfBoundsException. What do you do about this? You check the length of the args array. You compare args.length with 2. If the args array has fewer than two components, you display a message on the screen and exit from the program. Despite the checking of args.length, the code still isn’t crash-proof. If the user types five instead of 5, the program takes a nosedive with a NumberFormatException. The second command line argument can’t be a word. The argument has to be a number (and a whole number, at that). You can add statements to to make the code more bulletproof. When you’re working with command line arguments, you can enter a String value with a blank space in it. Just enclose the value in double quote marks. For instance, you can run the code above with arguments "My Big Fat File.txt" 7.

View Article
How to Add Searching Capability with Java

Article / Updated 05-09-2017

You’re sitting behind the desk at the Java Motel. Look! Here comes a party of five. These people want a room, so you need software that checks whether a room is vacant. If one is, the software modifies the GuestList.txt file by replacing the number 0 with the number 5. As luck would have it, the software is on your hard drive. The software is shown here. import static java.lang.System.out; import java.util.Scanner; import java.io.File; import java.io.IOException; import java.io.PrintStream; public class FindVacancy { public static void main(String args[]) throws IOException { int guests[] = new int[10]; int roomNum; Scanner diskScanner = new Scanner(new File("GuestList.txt")); for (roomNum = 0; roomNum < 10; roomNum++) { guests[roomNum] = diskScanner.nextInt(); } diskScanner.close(); roomNum = 0; while (roomNum < 10 && guests[roomNum] != 0) { roomNum++; } if (roomNum == 10) { out.println("Sorry, no v cancy"); } else { out.print("How many people for room "); out.print(roomNum); out.print("? "); Scanner keyboard = new Scanner(System.in); guests[roomNum] = keyboard.nextInt(); keyboard.close(); PrintStream listOut = new PrintStream("GuestList.txt"); for (roomNum = 0; roomNum < 10; roomNum++) { listOut.print(guests[roomNum]); listOut.print(" "); } listOut.close(); } } } The motel starts with two vacant rooms — Rooms 3 and 8. (Remember, the rooms start with Room 0.) The first time that you run the code, the program tells you that Room 3 is vacant and puts five people into the room. The second time you run the code, the program finds the remaining vacant room (Room 8) and puts a party of ten in the room. (What a party!) The third time you run the code, you have no more vacant rooms. When the program discovers this, it displays the message Sorry, no v cancy, omitting at least one letter in the tradition of all motel neon signs. A run of the code writes a brand-new GuestList.txt file. This can be confusing because each Java IDE has its own way of displaying the GuestList.txt file’s content. Some IDEs don’t automatically display the newest GuestList.txt file, so after running the code, you may not immediately see a change. Even if you don’t see a change, consecutive runs change the GuestList.txt file. Poke around within your favorite IDE to find out how to make the IDE refresh the GuestList.txt file’s display. The condition roomNum < 10 && guests[roomNum] != 0 can be really tricky. If you move things around and write guests[roomNum] != 0 && roomNum < 10, you can get yourself into lots of trouble. For details, see allmycode.com.

View Article
How to Use Subclasses in Java

Article / Updated 05-09-2017

You can use subclasses in Java. Creating subclasses is fine, but you gain nothing from these subclasses unless you write code to use them. So here, you explore code that uses subclasses. Now the time has come for you to classify yourself as either a type-F person, a type-P person, or a type-T person. A type-F person wants to see the fundamentals. (The letter F stands for fundamentals.) “Show me a program that lays out the principles in their barest, most basic form,” says the type-F person. A type-F person isn’t worried about bells and whistles. The bells come later, and the whistles may never come. If you’re a type-F person, you want to see a program that uses the FullTimeEmployee and PartTimeEmployee subclasses and then moves out of your way so that you can get some work done. A type-P person wants practical applications. (The letter P stands for practical.) Type-P people need to see ideas in context; otherwise, the ideas float away too quickly. “Show me a program that demonstrates the usefulness of the FullTimeEmployee and PartTimeEmployee subclasses,” says the type-P person. “I have no use for your stinking abstractions. I want real-life examples, and I want them now!” A type-T person wants to test the code in the FullTimeEmployee and PartTimeEmployee subclasses. Testing the code means putting the code through its paces — checking the output's accuracy when the input is ordinary, when the input is unexpected, and even when the input is completely unrealistic. What's more, the type-T person wants to use a standard, easily recognizable outline for the testing code so that other programmers can quickly understand the test results. The type-T person creates JUnit tests that use the FullTimeEmployee and PartTimeEmployee subclasses. The code below, which is for the type-F crowd, is lean and simple and makes good bedtime reading. If you're a type-P or type-T person, please visit allmycode.com. The site contains examples to satisfy type-P and type-T readers. This code shows you a bare-bones program that uses the subclasses FullTimeEmployee and PartTimeEmployee. Here’s the program’s output. public class DoPayrollTypeF { public static void main(String args[]) { FullTimeEmployee ftEmployee = new FullTimeEmployee(); ftEmployee.setName("Barry Burd"); ftEmployee.setJobTitle("CEO"); ftEmployee.setWeeklySalary(5000.00); ftEmployee.setBenefitDeduction(500.00); ftEmployee.cutCheck(ftEmployee.findPaymentAmount()); System.out.println(); PartTimeEmployee ptEmployee = new PartTimeEmployee(); ptEmployee.setName("Steve Surace"); ptEmployee.setJobTitle("Driver"); ptEmployee.setHourlyRate(7.53); ptEmployee.cutCheck(ptEmployee.findPaymentAmount(10)); } } To understand this code, you need to keep an eye on three classes: Employee, FullTimeEmployee, and PartTimeEmployee. The first half of the code deals with a full-time employee. Notice how many methods are available for use with the ftEmployee variable? For instance, you can call ftEmployee.setWeeklySalary because ftEmployee has type FullTimeEmployee. You can also call ftEmployee.setName because the FullTimeEmployee class extends the Employee class. Because cutCheck is declared in the Employee class, you can call ftEmployee.cutCheck. But you can also call ftEmployee.findPaymentAmount because a findPaymentAmount method is in the FullTimeEmployee class. Making types match Look again at the first half of the code. Take special notice of that last statement — the one in which the full-time employee is actually cut a check. The statement forms a nice, long chain of values and their types. You can see this by reading the statement from the inside out: Method ftEmployee.findPaymentAmount is called with an empty parameter list. That’s good because the findPaymentAmount method takes no parameters. The findPaymentAmount method returns a value of type double. The double value that ftEmployee.findPaymentAmount returns is passed to method ftEmployee.cutCheck. That’s good because the cutCheck method takes one parameter of type double. Check out the fanciful graphical illustration. Always feed a method the value types that it wants in its parameter list. The second half of the story In the second half of the code, the code creates an object of type PartTimeEmployee. A variable of type PartTimeEmployee can do some of the same things a FullTimeEmployee variable can do. But the PartTimeEmployee class doesn’t have the setWeeklySalary and setBenefitDeduction methods. Instead, the PartTimeEmployee class has the setHourlyRate method. So the next-to-last line is a call to the setHourlyRate method. The last line of the code is by far the most interesting. On that line, the code hands the number 10 (the number of hours worked) to the findPaymentAmount method. Compare this with the earlier call to findPaymentAmount — the call for the full-time employee in the first half of the code. Between the two subclasses, FullTimeEmployee and PartTimeEmployee, are two different findPaymentAmount methods. The two methods have two different kinds of parameter lists: The FullTimeEmployee class’s findPaymentAmount method takes no parameters. The PartTimeEmployee class’s findPaymentAmount method takes one int parameter. This is par for the course. Finding the payment amount for a part-time employee isn’t the same as finding the payment amount for a full-time employee. A part-time employee’s pay changes each week, depending on the number of hours the employee works in a week. The full-time employee’s pay stays the same each week. So the FullTimeEmployee and PartTimeEmployee classes both have findPaymentAmount methods, but each class’s method works quite differently.

View Article
Defining a Class in Java (What It Means to Be an Account)

Article / Updated 05-09-2017

Java lets you define a class. What does that mean? Think of it this way. What distinguishes one bank account from another? If you ask a banker this question, you hear a long sales pitch. The banker describes interest rates, fees, penalties — the whole routine. Don’t worry, for this example, you don’t need to know all of that. Instead, you want to know how my account is different from your account. After all, my account is named Barry Burd, trading as Burd Brain Consulting, and your account is named Jane Q. Reader, trading as Budding Java Expert. My account has $24.02 in it. How about yours? When you come right down to it, the differences between one account and another can be summarized as values of variables. Maybe there’s a variable named balance . For me, the value of balance is 24.02 . For you, the value of balance is 55.63 . The question is, when writing a computer program to deal with accounts, how do I separate my balance variable from your balance variable? The answer is to create two separate objects. Let one balance variable live inside one of the objects and let the other balance variable live inside the other object. While you’re at it, put a name variable and an address variable in each of the objects. And there you have it: two objects, and each object represents an account. More precisely, each object is an instance of the Account class. So far, so good. However, you still haven’t solved the original problem. In your computer program, how do you refer to my balance variable, as opposed to your balance variable? Well, you have two objects sitting around, so maybe you have variables to refer to these two objects. Create one variable named myAccount and another variable named yourAccount. The myAccount variable refers to my object (my instance of the Account class) with all the stuff that’s inside it. To refer to my balance, write myAccount.balance To refer to my name, write myAccount.name Then yourAccount.balance refers to the value in your object’s balance variable, and yourAccount.name refers to the value of your object’s name variable. To tell Java how much I have in my account, you can write myAccount.balance = 24.02; To display your name on the screen, you can write out.println(yourAccount.name); What it means to be an account. public class Account { String name; String address; double balance; } The Account class defines what it means to be an Account. In particular, this code tells you that each of the Account class’s instances has three variables: name, address, and balance. This is consistent with the information in the image above.1. Java programmers have a special name for variables of this kind (variables that belong to instances of classes). Each of these variables — name, address, and balance — is called a field. A variable declared inside a class but not inside any particular method is a field. The variables name, address, and balance are fields. Another name for a field is an instance variable. Can you really define a complete Java class with only four lines of code (give or take a curly brace)? You certainly can. A class is a grouping of existing things. In the Account class, those existing things are two String values and a double value. The field declarations have default access, which means that a word wasn’t added before the type name String. The alternatives to default access are public, protected, and private access: public String name; protected String address; private double balance; Professional programmers shun the use of default access because default access doesn't shield a field from accidental misuse. But, you learn best when you learn about the simplest stuff first, and in Java, default access is the simplest stuff.

View Article
How to Create Inner Classes in Java

Article / Updated 05-09-2017

Here’s big news! In Java, you can define a class inside of another class! Here, the GameFrame class contains a class named MyActionListener. import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; class GameFrame extends JFrame { private static final long serialVersionUID = 1L; int randomNumber = new Random().nextInt(10) + 1; int numGuesses = 0; JTextField textField = new JTextField(5); JButton button = new JButton("Guess"); JLabel label = new JLabel(numGuesses + " guesses"); public GameFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); add(textField); add(button); add(label); button.addActionListener(new MyActionListener()); pack(); setVisible(true); } class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String textFieldText = textField.getText(); if (Integer.parseInt(textFieldText) == randomNumber) { button.setEnabled(false); textField.setText(textField.getText() + " Yes!"); textField.setEnabled(false); } else { textField.setText(""); textField.requestFocus(); } numGuesses++; String guessWord = (numGuesses == 1) ? " guess" : " guesses"; label.setText(numGuesses + guessWord); } } } The MyActionListener class above is an inner class. An inner class is a lot like any other class. But within an inner class’s code, you can refer to the enclosing class’s fields. For example, several statements inside MyActionListener use the name textField, and textField is defined in the enclosing GameFrame class. Notice that the code above uses the MyActionListener class only once. (The only use is in a call to button.addActionListener.) So, do you really need a name for something that’s used only once? No, you don’t. You can substitute the entire definition of the inner class inside the call to button.addActionListener. When you do this, you have an anonymous inner class. This is how it works. import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; class GameFrame extends JFrame { private static final long serialVersionUID = 1L; int randomNumber = new Random().nextInt(10) + 1; int numGuesses = 0; JTextField textField = new JTextField(5); JButton button = new JButton("Guess"); JLabel label = new JLabel(numGuesses + " guesses"); public GameFrame() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); add(textField); add(button); add(label); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String textFieldText = textField.getText(); if (Integer.parseInt(textFieldText) == randomNumber) { button.setEnabled(false); textField.setText(textField.getText() + " Yes!"); textField.setEnabled(false); } else { textField.setText(""); textField.requestFocus(); } numGuesses++; String guessWord = (numGuesses == 1) ? " guess" : " guesses"; label.setText(numGuesses + guessWord); } }); pack(); setVisible(true); } } Inner classes are good for things like event handlers, such as the actionPerformed method. The most difficult thing about an anonymous inner class is keeping track of the parentheses, the curly braces, and the indentation Some humble advice: start by writing code without any inner classes. Later, when you become bored with ordinary Java classes, experiment by changing some of your ordinary classes into inner classes.

View Article
How to Use the serialVersionUID in Java

Article / Updated 05-09-2017

A serialVersionUID is a number that helps Java avoid version conflicts when you send an object from one place to another. For example, you can send the state of your JFrame object to another computer’s screen. Then the other computer can check the frame's version number to make sure that no funny business is taking place. So, when would you bother to change a class’s serialVersionUID number? If version number 1 is nice, is version number 2 even better? The answer is complicated, but the bottom line is, don’t change the serialVersionUID number unless you make incompatible changes to the class’s code. By “incompatible changes,” this means changes that make it impossible for the receiving computer’s existing code to handle your newly created objects. For more details about the serialVersionUID and what constitutes an incompatible code change, check out Oracle. Every major Java IDE has visual tools to help you design a GUI interface. Eclipse has WindowBuilder IntelliJ IDEA has GUI Designer NetBeans has GUI Builder With any of these tools, you drag components from a palette onto a frame. (The components include buttons, text fields, and other goodies.) Using the mouse, you can move and resize each component. As you design the frame visually, the tools creates the frame’s code automatically. Each component on the frame has a little spreadsheet showing the component’s properties. For example, you can change the text on a button’s face by changing the text entry in the button’s spreadsheet. When you right-click or control-click the picture of a component, you get the option of jumping to the component’s actionPerformed method. In the actionPerformed method, you add Java code, such as button.setText("You clicked me!"). Tools like WindowBuilder, GUI Designer, and GUI Builder make the design of GUI interfaces quicker, more natural, and more intuitive. Since 1998, Swing has been Java’s primary framework for developing GUI applications. But late in 2011, Oracle added a newer framework — JavaFX — to Java’s core. JavaFX provides a richer set of components than Swing. But for simple applications, JavaFX is more difficult to use. If you’re interested in reading more about JavaFX, visit Oracle's Getting Started with JavaFX page.

View Article
How to Use Abstract Methods in Java

Article / Updated 05-08-2017

Both interfaces and abstract classes have abstract methods in Java. But the abstract methods play slightly different roles in these two kinds of reference types. How can you keep it all straight in your mind? The first thing to do is to remember that no one learns about object-oriented programming concepts without getting lots of practice in writing code. If you've r you're confused, that may be a good thing. It means you've understood enough to know how complicated this stuff is. The more code you write, the more comfortable you'll become with classes, interfaces, and all these other ideas. The next thing to do is to sort out the differences in the way you declare abstract methods. Here’s the story. Using (or Not Using) Abstract Methods In an Ordinary (Non-Abstract) Class In an Interface In an Abstract Class Are abstract methods allowed? No Yes Yes Can a method declaration contain the abstract keyword? No Yes Yes Can a method declaration contain the default keyword (meaning "not abstract")? No Yes No With neither the abstract nor the default Not abstract Abstract Not abstract Both interfaces and abstract classes have abstract methods. So you may be wondering how you should choose between declaring an interface and declaring an abstract class. In fact, you might ask three professional programmers how interfaces and abstract classes differ from one another. If you do, you may get five different answers. (Yes, five answers; not three answers.) Interfaces and abstract classes are similar beasts, and the new features in Java 8 made them even more similar than in previous Java versions. But the basic idea is about the relationships among things. Extending a subclass represents an is a relationship. Implementing an interface represents a can do relationship. If you want more tangible evidence of the difference between an interface and an abstract class, consider this: A class can implement many interfaces, but a class can extend only one other class, even if that one class is an abstract class. So, after you've declared public class Dog extends HousePet you can't also make Dog extend a Friend class. But you can make Dog implement a Befriendable interface. And then you can make the same Dog class implement a Trainable interface. And, if you want an even more tangible difference between an interface and an abstract class, here’s one for you: An interface can't contain any non-static, non-final fields. So there. Interfaces and abstract classes are different from one another. But if you're new at the game, you shouldn't worry about the difference. Just read as much code as you can, and don't get scared when you see an abstract method. That's all there is to it.

View Article
How to Use a Java try Statement with Resources

Article / Updated 05-08-2017

Imagine a Java program that gets input from two different files or from a Scanner and a disk file. To make sure that you clean up properly, you put close method calls in a finally clause. import java.io.File; import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner scan1 = null; Scanner scan2 = null; try { scan1 = new Scanner(new File("File1.txt")); scan2 = new Scanner(new File("File2.txt")); // Do useful stuff } catch (IOException e) { // Oops! } finally { scan1.close(); scan2.close(); System.out.println("Done!"); } } } In theory, the computer always executes scan1.close() and scan2.close() no matter what goes wrong during execution of the try clause. But that’s theory. In reality, another programmer (not you, of course) might modify the code by closing scan1 in the middle of the try clause: try { scan1 = new Scanner(new File("File1.txt")); scan2 = new Scanner(new File("File2.txt")); // Do useful stuff but also … scan1.close(); scan1 = null; } catch (IOException e) { // Oops! } finally { scan1.close(); scan2.close(); System.out.println("Done!"); } Now you have a real predicament. Inside the finally clause, the value of scan1 is null. The call to scan1.close() fails, so the program throws a NullPointerException and stops running before reaching the call to scan2.close(). In the worst of circumstances, scan2 isn't closed and your program has File2.txt locked up so that no other program can use the file. When a program uses several resources (many files, a database and a file, or whatever) the buildup of try statements becomes quite complicated. You can make try statements within catch clauses and all kinds of crazy combinations. But Java has a better way to solve the problem: In Java 7 (and later versions of Java), you can create a try-with-resources statement. This code shows you how. import java.io.File; import java.io.IOException; import java.util.Scanner; public class NewMain { public static void main(String args[]) { try (Scanner scan1 = new Scanner(new File("File1.txt")); Scanner scan2 = new Scanner(new File("File2.txt"))) { // Do useful stuff } catch (IOException e) { // Oops!v } System.out.println("Done!"); } } In this code, the declarations of scan1 and scan2 are in parentheses after the word try. The parenthesized declarations tell Java to close scan1 and scan2 automatically after execution of the statements in the try clause. You can declare several resources inside one try statement’s parentheses. When you do, Java closes all the resources automatically after execution of the try clause’s statements. You can add catch clauses and a finally clause, if you want. You can access all kinds of resources (files, databases, connections to servers, and others) and have peace of mind knowing that Java will sever the connections automatically. Life is good.

View Article
page 1
page 2
page 3