Java For Dummies book cover

Java For Dummies

Author:

Overview

Learn to write practical, reusable code with the straight forward tutorials and tips in the newest edition of this For Dummies bestseller

Do you speak Java? No, we’re not talking about your morning cup ‘o joe. We mean the world’s most popular programming language that runs on almost any computer!

If you’re looking to get started—or up your game—with Java, then Java For Dummies is the guide you need.In this book, you’ll:

  • Take control of your program flow
  • Program with classes, objects, and methods
  • Use Java's functional programming features
  • Explore Java 17, the latest long-term support release

This up-to-date handbook covers the latest developments in Java, including the new ‘switch’ statement syntax. So, if you’re ready to dive into one of the most practical (and coolest!) programming languages around, it’s time you picked upJava For Dummies.

Learn to write practical, reusable code with the straight forward tutorials and tips in the newest edition of this For Dummies bestseller

Do you speak Java? No, we’re not talking about your morning cup ‘o joe. We mean the world’s most popular programming language that runs on almost any computer!

If you’re looking to get started—or up your game—with Java, then Java For Dummies is the guide you need.In this book, you’ll:

  • Take control
of your program flow
  • Program with classes, objects, and methods
  • Use Java's functional programming features
  • Explore Java 17, the latest long-term support release
  • This up-to-date handbook covers the latest developments in Java, including the new ‘switch’ statement syntax. So, if you’re ready to dive into one of the most practical (and coolest!) programming languages around, it’s time you picked upJava For Dummies.

    Java For Dummies Cheat Sheet

    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.

    Articles From The Book

    24 results

    Java Articles

    The Atoms: Java’s Primitive Types

    The words int and double are examples of primitive types (also known as simple types) in Java. The Java language has exactly eight primitive types. As a newcomer to Java, you can pretty much ignore all but four of these types. (As programming languages go, Java is nice and compact that way.) The types that you shouldn’t ignore are int, double, char, and boolean.

    The char type

    Several decades ago, people thought computers existed only for doing big number-crunching calculations. Nowadays, nobody thinks that way. So, if you haven’t been in a cryogenic freezing chamber for the past 20 years, you know that computers store letters, punctuation symbols, and other characters. The Java type that’s used to store characters is called char. The code below has a simple program that uses the char type. This image shows the output of the program in the code below. public class CharDemo { public static void main(String args[]) { char myLittleChar = 'b'; char myBigChar = Character.toUpperCase(myLittleChar); System.out.println(myBigChar); } } In this code, the first initialization stores the letter b in the variable myLittleChar. In the initialization, notice how b is surrounded by single quote marks. In Java, every char literally starts and ends with a single quote mark.

    In a Java program, single quote marks surround the letter in a char literal.

    Character.toUpperCase. The Character.toUpperCase method does just what its name suggests — the method produces the uppercase equivalent of the letter b. This uppercase equivalent (the letter B) is assigned to the myBigChar variable, and the B that’s in myBigChar prints onscreen. If you’re tempted to write the following statement, char myLittleChars = 'barry'; //Don't do this please resist the temptation. You can’t store more than one letter at a time in a char variable, and you can’t put more than one letter between a pair of single quotes. If you’re trying to store words or sentences (not just single letters), you need to use something called a String.

    If you’re used to writing programs in other languages, you may be aware of something called ASCII character encoding. Most languages use ASCII; Java uses Unicode. In the old ASCII representation, each character takes up only 8 bits, but in Unicode, each character takes up 8, 16, or 32 bits. Whereas ASCII stores the letters of the Roman (English) alphabet, Unicode has room for characters from most of the world’s commonly spoken languages.

    The only problem is that some of the Java API methods are geared specially toward 16-bit Unicode. Occasionally, this bites you in the back (or it bytes you in the back, as the case may be). If you’re using a method to write Hello on the screen and H e l l o shows up instead, check the method’s documentation for mention of Unicode characters. It’s worth noticing that the two methods, Character.toUpperCase and System.out.println, are used quite differently in the code above. The method Character.toUpperCase is called as part of an initialization or an assignment statement, but the method System.out.println is called on its own.

    The boolean type

    A variable of type boolean stores one of two values: true or false. The code below demonstrates the use of a boolean variable. public class ElevatorFitter2 { public static void main(String args[]) { System.out.println("True or False?"); System.out.println("You can fit all ten of the"); System.out.println("Brickenchicker dectuplets"); System.out.println("on the elevator:"); System.out.println(); int weightOfAPerson = 150; int elevatorWeightLimit = 1400; int numberOfPeople = elevatorWeightLimit / weightOfAPerson; <strong> boolean allTenOkay = numberOfPeople >= 10;</strong> System.out.println(allTenOkay); } } In this code, the allTenOkay variable is of type boolean. To find a value for the allTenOkay variable, the program checks to see whether numberOfPeople is greater than or equal to ten. (The symbols >= stand for greater than or equal to.) At this point, it pays to be fussy about terminology. Any part of a Java program that has a value is an expression. If you write weightOfAPerson = 150; then 150 ,is an expression (an expression whose value is the quantity 150). If you write numberOfEggs = 2 + 2; then 2 + 2 is an expression (because 2 + 2 has the value 4). If you write int numberOfPeople = elevatorWeightLimit / weightOfAPerson; then elevatorWeightLimit / weightOfAPerson is an expression. (The value of the expression elevatorWeightLimit / weightOfAPerson depends on whatever values the variables elevatorWeightLimit and weightOfAPerson have when the code containing the expression is executed.)

    Any part of a Java program that has a value is an expression.

    In the second set of code, numberOfPeople >= 10 is an expression. The expression’s value depends on the value stored in the numberOfPeople variable. But, as you know from seeing the strawberry shortcake at the Brickenchicker family’s catered lunch, the value of numberOfPeople isn’t greater than or equal to ten. As a result, the value of numberOfPeople >= 10 is false. So, in the statement in the second set of code, in which allTenOkay is assigned a value, the allTenOkay variable is assigned a false value.

    In the second set of code, System.out.println() is called with nothing inside the parentheses. When you do this, Java adds a line break to the program’s output. In the second set of code, System.out.println() tells the program to display a blank line.

    Java Articles

    Using Streams and Lambda Expressions in Java

    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. 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); <strong> </strong> <strong>double total = sales.stream()</strong> <strong>.filter((sale) -> sale.getItem().equals("DVD"))</strong> <strong>.map((sale) -> sale.getPrice())</strong> <strong>.reduce(0.0, (price1, price2) -> price1 + price2);</strong> 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.

    Java Articles

    Command Line Arguments in Java

    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.