Getting Started with Java PDF
Document Details
Uploaded by DecentAmber4217
DHBW
Jeff Friesen
Tags
Summary
This textbook provides an introduction to Java programming, covering fundamental concepts and features, including Java's architecture and application development. It explains what Java is and what it entails, along with essential components.
Full Transcript
CHAPTER 1 Getting Started with Java Welcome to Java. This technology is widely used in the business world, and you probably want to learn it quickly so you can capture a job in one of these companies as a Java programmer. Although Java is vast and constantly evolving, there are various fundamental...
CHAPTER 1 Getting Started with Java Welcome to Java. This technology is widely used in the business world, and you probably want to learn it quickly so you can capture a job in one of these companies as a Java programmer. Although Java is vast and constantly evolving, there are various fundamental features that are timeless and easy to understand. After you master these fundamentals, you will have an easier time writing Java programs. This chapter launches you on a tour of Java’s fundamental features. You first receive an answer to the “What is Java?” question. Next, you learn about the Java Development Kit, which is the necessary software for developing Java programs on your computer. Moving on, you are introduced to your first Java program, which outputs a simple “hello, world” message. Finally, you discover application architecture. Note A program is a sequence of instructions for a computer to execute. An application is a program with a single entry point of execution. (In contrast, an applet – an old form of Java program that is no longer widely used – has multiple entry points.) For example, a Microsoft Windows program that is stored in an.exe file has a single entry point. When expressed in C language source code (textual instructions), the entry point is defined by a function (a named sequence of instructions) with the name main. What Is Java? Java is like a two-sided coin. From one side, it’s a computer programming language. Conversely, it’s a virtual platform (the hardware and software context in which a program runs) for running programs written in that language. 1 © Jeff Friesen 2024 J. Friesen, Learn Java Fundamentals, https://doi.org/10.1007/979-8-8688-0351-2_1 Chapter 1 Getting Started with Java Note Java has an interesting history. Check out Wikipedia’s “Java (programming language)” (http://en.wikipedia.org/wiki/Java_(programming_ language)#History) and “Java (software platform)” (http://en.wikipedia. org/wiki/Java_ (software_platform)#History) entries to learn more. Java Is a Programming Language Java is a programming language with many features that are identical to those found in the C and C++ languages. This is no accident. One of Java’s initial goals was to make it easy for C/C++ programmers to migrate to Java to quickly build up an initial pool of programmers that would help Java become successful. You will discover several similarities between these languages: The same single-line and multiline comments for documenting source code are found in Java and C/C++. Various identical reserved words are found in Java and C/C++, such as if, while, for, and switch. Various other reserved words are found in Java and C++ but not in C, such as try, catch, class, and public. Primitive types are shared between the three languages: character and integer are examples. Furthermore, reserved words for these types are shared between these languages: char and int are examples. Many of the same operators are shared between Java and C/C++. Arithmetic operators (such as * and +) and relational operators (such as == and >> (unsigned right shift) operator is exclusive to Java. Java provides labeled break and continue statements. These variants of their C/C++ counterparts, which don’t accept labels, are a safer alternative to C/C++’s goto statement, which Java doesn’t support. I discuss comments, reserved words, types, operators, and statements later in this book. The Java programming language is rigorously defined by various rules that describe its syntax (structure) and semantics (meaning). These rules are used by a compiler to verify correctness when translating a program’s source code into equivalent bytecode, which is a portable representation of the program’s executable code. This bytecode is stored in one or more class files, which are the Java equivalent of a Windows program’s executable (.exe) file. Java Is a Virtual Platform Java is a virtual platform that executes Java programs. Unlike real platforms that consist of a microprocessor (such as an Intel or AMD processor) and operating system (such as Windows 11), the Java platform consists of virtual machine and execution environment software. A virtual machine is a software-based processor with its own set of instructions. The Java Virtual Machine’s (JVM) associated execution environment consists of a huge library of prebuilt reference types (think Application Program Interfaces [APIs]) that Java programs can use to perform routine tasks (such as opening a file). The execution environment also contains “glue” code that connects the JVM to the underlying operating system via the Java Native Interface. (I don’t discuss the Java Native Interface in this book because I don’t consider it to be a fundamental feature.) 3 Chapter 1 Getting Started with Java Note The combination of bytecode and the virtual machine makes it possible to achieve portability: the same Java program runs on all platforms that support the virtual machine. It’s not necessary to recompile the program’s source code for each platform. A Java program is run by a special executable, which I call the program launcher. Because a program consists of one or more class files, the launcher receives the name of the main class file (the class file where execution begins). After loading the JVM into memory, it tells the JVM to use its class loader component to load the main class file into memory. The JVM then verifies that the class file’s bytecode is safe to run (e.g., no viruses) and runs it. Note The verifier and a security manager architecture make it possible to achieve security: a Java application will not be allowed to run when the verifier detects corrupt bytecode. Furthermore, when a security manager is installed, the application won’t be able to steal sensitive information, erase files, or otherwise harm a user’s computer. During execution, a class file might refer to another class file. When this happens, the JVM uses the class loader to load the referenced class file into memory and then verifies and (if okay to run) executes that class file’s bytecode. The Java Development Kit The Java Development Kit (JDK) provides the necessary software for creating Java applications, which are a category of Java programs with a single entry point of execution. They contrast with Java applets, another category of Java programs that run embedded in web pages. Applets are rarely used these days. Follow these steps to download the JDK: 1. Enter www.oracle.com/java/technologies/ in your browser. This takes you to the main page of Oracle’s Java site. 4 Chapter 1 Getting Started with Java 2. At the time of writing, the newest download is version 21.0.1. Click on the Java SE 21.0.1 link. (Java SE stands for Java Standard Edition. This is the foundation on which other editions are based and is the appropriate edition for this book. Another edition is Java EE, for Java Enterprise Edition. You would use this edition when developing complex business solutions involving web servers, database management systems, and client computers.) 3. In the JDK Development Kit 21.0.1 downloads section of the resulting Java Downloads page, you will see Linux, macOS, and Windows tabs. The JDK is available for all three operating systems. Choose whichever one is right for you. For example, I clicked the Windows tab because I was running Windows. I then had a choice between different kinds of installers. I chose the x64 installer whose file name ends with a.exe file extension. I found this the easiest way to install the JDK. Once you download the installer, such as jdk-21_windows-x64_bin.exe, run this program and follow the onscreen prompts to install the JDK. The JDK contains various tools for use in application development. Four of these tools are the Java compiler (javac.exe in the Windows download), the Java program launcher (java.exe in the Windows download), the Java documentation generator (javadoc.exe in the Windows download), and the Java archiver (jar.exe in the Windows download). You will only need to work with these tools in this book. The JDK’s compiler, program launcher, documentation generator, archiver, and other tools are designed to be run from the command line within the context of a console (an operating system–specific construct consisting of a window for viewing output and a command line for obtaining command-based input). To obtain a console on Windows operating systems, perform the following tasks: 1. Go to the Start menu and select Run. 2. In the Run dialog box, enter cmd in the text field and click the OK button. On the Windows operating system, you should observe a window similar to that shown in Figure 1-1. 5 Chapter 1 Getting Started with Java Figure 1-1. The upper portion of a console as seen on a Windows 8.1 machine Figure 1-1 reveals C:\Users\jeffrey>, which is a prompt for entering a command on my Windows 8.1 machine. The rectangular box to the right of > is the cursor, which indicates the current position for entering text on the command line. “hello, world” – Java Style Let’s create a simple application to get a taste of Java code. Traditionally, the first application does nothing but output the message hello, world on the console. Listing 1-1 presents the source code to a HelloWorld application that does just that. Listing 1-1. HelloWorld.java class HelloWorld { public static void main(String[] args) { System.out.println("hello, world"); } } Listing 1-1 declares a HelloWorld class (I explain classes in Chapter 6) that serves as a placeholder for the main() method (a named sequence of instructions that executes in the context of a class). Note Languages such as C use functions instead of methods. A function is a named sequence of instructions that executes outside of any context. 6 Chapter 1 Getting Started with Java The main() method serves as the entry point to the application. When the application runs, main()’s code is executed. The main() method header (public static void main(String[] args)) exhibits some interesting features: The method is marked public so that the Java program launcher can locate it. If public is absent, an error message is output when attempting to run the application. The method is marked static so that a HelloWorld object does not need to be created in order to call main(). The launcher calls main() directly. It knows nothing of objects. If static is absent, an error message is output when attempting to run the application. The method is declared with a parameter list consisting of String[] args, which identifies an array of string arguments that are passed after the application’s name (HelloWorld) on the command line when the application is run by the launcher. A string is a sequence of characters placed between double quotes ("). The method is declared with a void return type that signifies the method returns nothing. Don’t worry if concepts such as return type and parameter list are confusing. You’ll learn about these concepts later in this book. The main() method executes System.out.println("hello, world"); to output hello, world on the console’s window. I explore System.out and its System.err and System.in counterparts in Chapter 14. INDENTATION, OPEN BRACE CHARACTER PLACEMENT, AND CODE-SEPARATION STYLES Programmers often follow one style when indenting source code, another style when positioning a block’s open brace character, and a third style when using blank lines to separate segments of source code. (I briefly discuss blocks, which are sequences of code surrounded by { and } characters, in Chapter 4.) Listing 1-1 demonstrates the first two style categories. It shows my tendency to indent, by three spaces, all lines in a block. I find that doing so makes it easier to follow the organization of my source code when updating it as requirements change. 7 Chapter 1 Getting Started with Java Also, Listing 1-1 shows my tendency to align the open ({) and close (}) brace characters, so I can more easily locate the start and end of a block. Many programmers prefer the following brace character alignment instead: class HelloWorld { public static void main(String[] args) { System.out.println("hello, world"); } } Another style issue involves inserting blank lines to separate segments of code, where each segment consists of statements that work collectively on some aspect of the program. Here is a contrived example, involving a pair of classes, A and B: class A { void method1() { for (int i = 0; i < 10; i++) System.out.println(i); while (true) { //... do something here } } void method2() { for (int i = 0; i < 10; i++) System.out.println(i); while (true) { //... do something here } } } 8 Chapter 1 Getting Started with Java class B { void method1() { for (int i = 0; i < 10; i++) System.out.println(i); while (true) { //... do something here } } void method2() { for (int i = 0; i < 10; i++) System.out.println(i); while (true) { //... do something here } } } Each of classes A and B declares two methods: method1() and method2(). Furthermore, each of method1() and method2() declares a for statement followed by a while statement. Don’t worry about classes, methods, and statements. I cover classes and methods in Chapter 6 and cover statements in Chapter 4. For now, pay attention to the blank line styles in each of A and B. A’s style is to place a blank line between each method and between each group of related statements. B’s style is to eliminate the blank line from between the methods and from between the statements. Form your own styles for indentation, brace character placement, and code separation. Although these styles don’t impact the generated code, adhering to them religiously sets you apart from other programmers and can make your source code easier to read and maintain. I tend to vary my code-separation style, which you’ll discover throughout this book’s code listings. 9 Chapter 1 Getting Started with Java Compile the source code as follows (you must include the.java file extension): javac HelloWorld.java If everything goes well, you should observe a HelloWorld.class file in the current directory. Now, execute the following command to run HelloWorld.class (you must not include the.class file extension): java HelloWorld If all goes well, you should observe the following output: hello, world Congratulations! You’ve just run your first Java application. You should feel proud. Application Architecture An application consists of at least one class, and this class must declare a main() entry- point method, as you saw in Listing 1-1. However, many applications will consist of multiple classes. All of these classes might be declared in a single source file, or each class might be declared in its own source file. Consider Listing 1-2. Listing 1-2. Classes.java class A { static void a() { System.out.println("a() called"); } } class B { static void b() 10 Chapter 1 Getting Started with Java { System.out.println("b() called"); } } class C { public static void main(String[] args) { A.a(); B.b(); } } Listing 1-2 declares three classes (A, B, and C) in the same source file – Classes.java. Class C is the entry-point class because it declares the main() method. Compile Classes.java as follows: javac Classes.java You should observe A.class, B.class, and C.class class files in the current directory. Run this application as follows: java C You should observe the following output: a() called b() called If you try to execute A (java A) or B (java B), you’ll discover an error message because neither class declares the main() entry-point method. This brings up an interesting point. You could declare main() methods in A and B and run these classes as applications. However, this could get confusing. You might want to declare a main() method in each of A and B to test these classes, but there’s probably no other good reason to do so. It’s best to avoid confusion by declaring main() in the entry-point class only. 11 Chapter 1 Getting Started with Java What’s Next? Now that you’ve had a taste of Java, it’s time to build on that knowledge by exploring language features. Chapter 2 begins this process by focusing on the most basic language features: comments, identifiers (and reserved words), types, variables, and literals. 12