Java is a mature programming language that has been born for more than 20 years, ranking among the top three programming languages for years, so now I will tell you how to learn Java

So, do you want to program in Java? Oh, good. You came to the right place. The Java series provides a self-guided introduction to Java programming, starting with the basics and covering all the core concepts you need to know to become an effective Java developer. This series is technical, with plenty of code examples to help you grasp the concepts as we go along. I assume you already have some programming experience, just not Java.

The first article introduced the Java platform and explained the differences between its three versions: Java SE, Java EE, and Java ME. You’ll also learn about the role of the Java Virtual Machine (JVM) in deploying Java applications. I’ll help you set up the Java Development Kit (JDK) on your system so you can develop and run Java programs, and I’ll help you get started with the architecture of a typical Java application. Finally, you’ll learn how to compile and run a simple Java application.

What is Java?

You can think of Java as a general-purpose, object-oriented language that looks a lot like C and C++, but is easier to use and allows you to create more robust programs. Unfortunately, this definition doesn’t give you much insight into Java. In 2000, Sun Microsystems (the founder of the Java platform) described Java this way:

Java is a simple, object-oriented, web-savvy, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, dynamic computer language.

Let’s consider each of these definitions separately.

Learning Java from scratch how to get a fast job

Java is a simple language

Java was originally modeled after C and C++, removing some potentially confusing features. Pointers, multiple implementation inheritance, and operator overloading are some C/C++ features that do not belong in Java. A feature not mandatory in C/C++, but essential to Java, is a garbage collection facility that automatically recyls objects and arrays.

Java is an object-oriented language

Java’s object-oriented focus allows developers to adapt Java to solve problems, rather than forcing us to manipulate problems to meet language constraints. This is different from structured languages such as C. For example, Java lets you focus on savings account objects, while C requires you to consider savings account states (such as balances) and actions (such as deposits and withdrawals) separately.

Java is a web-savvy language

Java’s rich network library makes it easy to cope with transmission control Protocol/Internet Protocol (TCP/IP) network protocols such as HTTP (Hypertext Transfer Protocol) and FTP (File Transfer Protocol), and simplifies the task of establishing network connections. In addition, Java programs can access objects on a TCP/IP network through a Unified Resource Locator (URL) just as easily as they can from a local file system.

Java is an interpreted language

At run time, Java programs execute indirectly on the underlying platform (such as Windows or Linux) via the virtual machine (which is the software representation of the hypothetical platform) and the associated execution environment. The virtual machine interprets Java program bytecodes (instructions and related data) into platform-specific instructions. Interpretation is the act of figuring out what the bytecode instructions mean and then choosing the equivalent “canned” platform-specific instructions to perform. The virtual machine then executes those platform-specific instructions.

Explanation makes debugging defective Java programs easier because more compile-time information is available at run time. Interpretation can also speed up development by delaying the linking steps between parts of a Java program until runtime.

Java is a robust language

Java programs must be reliable because they are used in consumer and mission-critical applications, from Blu-ray players to vehicle navigation or air control systems. Language features that help make Java robust include declarations, compile-time and run-time duplicate type checking (to prevent version mismatch problems), real arrays with automatic boundary checking, and ellipsis Pointers. (See “Basic Java Language Features” to get started with Java language types, literals, variables, and so on.)

Another aspect of Java robustness is that loops must be controlled by Boolean expressions rather than integer expressions, where 0 is false and non-zero values are true. For example, Java does not allow C-style loops, such as while (x) x++; Because the loop may not end up where it’s supposed to. Instead, you must explicitly provide a Boolean expression, such as while (x! = 10) x++; (This means that the loop will run until x equals 10).

Java is a secure language

Java programs for networking/distributed environments. Because Java programs can be migrated to and executed on various platforms on the network, it is important to protect those platforms from malicious code that can spread viruses, steal credit card information, or perform other malicious actions. Java language features that support robustness, such as omitted Pointers, are used with security features, such as the Java sandbox security model and public key encryption. Together, these features prevent viruses and other dangerous code from wreaking havoc on unsuspecting platforms.

In theory, Java is safe. In practice, various security vulnerabilities have been detected and exploited. As a result, Sun Microsystems and Oracle at the time continue to release security updates today.

Java is an architecture-neutral language

Network connectivity has a platform based on a variety of microprocessors and operating systems with different architectures. You can’t expect Java to generate platform-specific instructions and have them “understood” by the various platforms that are part of the network. Instead, Java generates platform-independent bytecode instructions that each platform can easily interpret (through its JVM implementation).

Java is a portable language

Schema neutrality contributes to portability. However, Java portability goes beyond platform-independent bytecode instructions. Consider that integer types cannot vary in size. For example, 32-bit integer types must always be signed and occupy 32 bits, no matter where the 32-bit integer is processed (for example, platforms with 16-bit registers, platforms with 32-bit registers, or platform 64-bit registers). Java’s libraries also help with portability. When necessary, they provide types that link Java code to platform-specific functionality in the most portable way possible.

Java is a high-performance language

The level of performance generated by interpretation is usually more than adequate. For very high performance application scenarios, Java uses just-in-time compilation, which analyzes interpreted sequences of bytecode instructions and compiles frequently interpreted sequences into platform-specific instructions. Subsequent attempts to interpret these bytecode instruction sequences result in the execution of equivalent platform-specific instructions, thus improving performance.

Java is a multithreaded language

To improve the performance of programs that must perform multiple tasks simultaneously, Java supports the concept of threaded execution. For example, a program that manages a graphical user interface (GUI) while waiting for input from a network connection uses another thread to perform the wait instead of using the default GUI thread for both tasks. This keeps the GUI responsive. Java’s synchronization primitives allow threads to safely communicate data between them without corrupting the data.

Java is a dynamic language

Because the interconnections between program code and libraries occur dynamically at run time, there is no need to link them explicitly. Thus, when a program or one of its libraries evolves (for example, to fix a bug or improve performance), the developer simply distributes the updated program or library. Although dynamic behavior reduces the amount of code distributed when a version change occurs, this distribution strategy can also lead to version conflicts. For example, a developer removes a class type from a library, or renames it. Existing programs that rely on class types will fail when a company distributes updated libraries. To greatly reduce this problem, Java supports a type of interface that acts like a contract between two parties.

Unraveling this definition will tell us a lot about Java. Most importantly, it reveals that Java is both a language and a platform. Later in the tutorial, you will learn more about the components of the Java platform, namely the Java Virtual Machine and the Java execution environment.

Three versions of Java: Java SE, Java EE, and Java ME

Sun Microsystems released the Java 1.0 Software Development Kit (JDK) in May 1995. The first JDK was used to develop desktop applications and applets, and Java has since evolved to include enterprise server and mobile device programming. Storing all the necessary libraries in a single JDK would have made the JDK too large to distribute, especially since distribution in the 1990s was limited by small CDS and slow network speeds. Since most developers don’t need every API (desktop application developers rarely need access to enterprise Java apis), Sun divides Java into three main versions. These eventually became known as Java SE, Java EE, and Java ME:

  • Java Platform, Standard Edition (Java SE)The Java platform for developing client-side applications (running on the desktop) and applets (running in a Web browser). Please note that applets are no longer officially supported for security reasons.
  • Java Platform, Enterprise Edition (Java EE )The Java platform, built on Top of Java SE, is designed to develop enterprise-oriented server applications. Server-side applications include Java servlets, which are Java programs that are similar to applets but run on the server rather than the client. Servlets conform to the Java Servlet API.
  • Java Platform, Micro Edition (Java ME)Also built on Java SE. It is the Java platform for developing MIDlets (Java programs running on mobile information devices) and Xlets (Java programs running on embedded devices).

Java SE is the foundation platform for Java and the focus of the Java 101 series. The code samples will be based on the latest Java version as of this writing

Java platform and JVM

Java is both a programming language and a platform for running compiled Java code. The platform consists primarily of JVMS, but also includes an execution environment that enables JVMS to execute on the underlying (native) platform. The JVM includes several components for loading, validating, and executing Java code. Figure 1 shows how Java programs execute on this platform.

Figure 1. Java application architecture: The JVM provides a class loader, a bytecode validator, and an interpreter/just-in-time compiler for loading, validating, and executing class files.

At the top of the diagram is a series of program class files, one of which is represented as the main class file. Java programs contain at least the main class file, which is the first class file to load, validate, and execute.

The JVM delegates class loading to its classloader component. Class loaders load class files from a variety of sources, such as file systems, networks, and archive files. They insulate the JVM from the complexities of class loading.

The loaded Class files are stored in memory and represented as objects created from the Class Class. Once loaded, the bytecode validator validates the various bytecode instructions to ensure that they are valid and do not compromise security.

If the bytecode of the class file is invalid, the JVM terminates. Otherwise, its interpreter component interprets the bytecode one instruction at a time. Interprets bytecode instructions and executes their native equivalents.

Some sequences of bytecode instructions are executed more frequently than others. When the interpreter detects this, the JVM’s just-in-time (JIT) compiler compiles the bytecode sequence into native code to speed up execution.

During execution, the interpreter will typically encounter a request to execute bytecode (belonging to a program or library) from another class file. When this happens, the class loader loads the class file, and the bytecode validator validates the bytecode of the loaded class file before execution. Also during execution, bytecode instructions may ask the JVM to open a file, display something on the screen, make sounds, or perform other tasks that require cooperation with the native platform. The JVM responds by interacting with the native platform to perform tasks using its Java Native Interface (JNI) bridging technology.

Java standard class library

Java includes a large class file runtime library for storing compiled classes and other types. I call it the standard class library. You’ll encounter standard Class library types throughout the Java 101 series

Java installation and setup

The Java platform is distributed as the Java runtime environment (JRE), which contains the JVM, standard class libraries, and a number of other projects. You will need the JRE and JDK to develop and run Java programs. The JDK downloaded from Oracle includes the JRE and the basic development tools needed to start developing, debugging, and monitoring applications using Java.

Platform compatibility

The JDK is available for 32-bit / 64-bit Linux, 64-bit Mac OS X, 64-bit Solaris SPARC, 64-bit Solaris, and 32-bit / 64-bit Windows platforms.

After downloading and installing the JDK, you should update the PATH environment variable to reference the JDK subdirectory of the bin installation directory so that you can execute JDK tools from any directory on the file system. If you need to update the instructions, PATH can find them here. (Note that my examples are based on using the command line in conjunction with command-line Java tools, but you can also use the Java IDE if you prefer.)

Directory tips!

By pointing your JAVA_HOME environment variable to the JDK installation directory, you can enable any java-dependent external software you may install later to locate your JDK installation.

The JDK installation directory contains various files and subdirectories, including the following three important subdirectories:

  • Bin contains various JDK tools, such as the Java compiler (JavAC), Java application launcher (Java), and Java Shell (jshell). (Note that the Java compiler and JIT compiler are two different compilers.)
  • The JRE contains a private JDK copy of the Java Runtime Environment, which allows you to run Java programs without downloading and installing a separate JRE.
  • Lib contains the library files used by the JDK tools. For example, tools.jar contains class files for the Java compiler — a Java application. (The Javac tool is not a compiler, but a native platform-specific convenience for starting the JVM and running java-based compilers.)

Once you’ve installed the JDK and configured your development environment, you’re ready to write your first Java application.

Accessing Java Documents

Oracle’s Java Platform Standard Edition (Java SE) page provides access to a large number of online Java SE documentation for the latest Java versions. This document includes API references for all standard library types. The API reference is generated by the JDK’s Javadoc tool.

Write your first Java application

One application is minimally implemented as declaring a single class main() method, as follows:

class X
{
   public static void main(String[] args)
   {}}Copy the code

Think of classes as placeholders to declare where methods and data items are stored. The class declaration begins with the reserved word class, followed by a mandatory name, represented by X, a placeholder for the actual name (for example, Account). The name is followed by the method body and the data item location; The body is separated by open curly braces ({) and close curly braces (}) characters.

Think of methods as named blocks of code that process input and return output. Main () receives an array of objects that String describes its input; The array is called args. Each object identifies a string, and a sequence of double-quoted characters (in this case) represents a command line argument, such as the file name passed to the application as one of its arguments. Main () does not return output, so it is assigned the void reserved word as its return type.

What’s in a name?

There is nothing special about my choice. You can name the array Args, arguments, or even something_else. However, ARGS is commonly used.

In addition, the header of main() is assigned public, static so that the Java application launcher can call it. After the method header is a piece of code; Like class bodies, method bodies are separated by curly brace characters.

That’s all you need to know (especially) about classes and methods for main() to write your first Java application. In future articles, you’ll learn more about these language features (as well as strings, arrays, return types, and so on).

Say hello to

It is traditional to introduce a computer language by showing a program that prints the famous “Hello, world” message. You can see this in Listing 1.

Listing 1. helloworld.java (version 1)

class HelloWorld
{
   public static void main(String[] args)
   {
      System.out.println("hello, world"); }}Copy the code

The class name of the application is HelloWorld. Its main() method executes system.out.println (“hello, world”); Sends the contents of the “hello, world” string to the standard output stream, usually the command line.

Store Listing 1 in a file named Helloworld.java. Then, on the command line, execute the following command to compile the source file:

javac HelloWorld.java
Copy the code

Note that Javac requires a. Java file extension; Otherwise, it generates an error message. If the source code compiles without errors, you should observe helloWorld.class in the current directory.

Helloworld.class contains the equivalent of helloWorld.java. To run such a file through the Java application launcher tool, run the following command:

java HelloWorld
Copy the code

Note that Java does not allow you to include a.class file extension; If you do, it will generate an error message.

Assuming you have written the program correctly, you should observe the following output:

hello, world
Copy the code

If you see this output, congratulate yourself: you just compiled and ran your first Java application! There will be more examples in the rest of this series.

Personalization Hello

Listing 1 can be improved by personalizing the application. For example, we might want to print Hello, Java instead of Hello, world. Listing 2 enhances the original program:

Listing 2. helloworld.java (version 2)

class HelloWorld
{
   public static void main(String[] args)
   {
      System.out.println("hello, " + args[0]); }}Copy the code

Listing 2 shortenes “hello, world” to “hello, “and appends + args[0] to the first string of the ARgs array to the message. Then print the result.

“Hello,” + args[0] is an expression that appends a string from the first element of the ARgs array to Hello,.

Compile Listing 2 (javac Helloworld.java) and run the application with a single command-line argument, as follows:

java HelloWorld Java
Copy the code

You should observe the following output:

hello, Java
Copy the code

Java exception

Now suppose you execute HelloWorld without any command-line arguments, such as Java HelloWorld. In this case, you will receive an exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at HelloWorld.main(HelloWorld.java:5)
Copy the code

What you see is an error message that refers to an exception in your code. Specifically, because there are no command-line arguments, args[0] contains nothing. It is illegal to attempt to access a string that does not exist in args[0].

As you develop Java applications, you will encounter many such messages. Instead of being intimidated, treat these messages as tips to correct the problem.

Start using Java Shell (jShell)

Java SE 9 introduces the Java Shell (JShell) as an alternative to the Java compiler (JavAC) and Java Application launcher (Java) tools. This interactive tool is handy for learning the Java language and apis and prototyping Java code.

With JShell, you don’t have to write an entire application, compile it, and then run it just to try out the language features or apis. Instead, you can type and immediately execute a snippet (one or more lines of Java code) and observe the results.

Here’s how jshell executes from the command line:

C:\temp>jshell
Copy the code

The tool responds with prologue text and prompts:

|  Welcome to JShell -- Version 12
|  For an introduction type: /help intro

jshell>
Copy the code

You can then type snippets or commands at the prompt. To distinguish a command from a code snippet, you must use the forward slash (/) character before the command name. For example, try to see what happens when you type /help.

In Listing 1, you see a classic HelloWorld application. This is the Jshell equivalent:

jshell> System.out.println("hello, world")
hello, world

jshell>
Copy the code

In this case, all we need to do is specify system.out.println (“hello, world”.) (We don’t need a semicolon in this case. Terminator.) As soon as we press Enter, jshell executes the code and displays the output.

When we are ready to exit jshell, we simply type /exit at the prompt and press Enter. The Java shell will immediately return to the operating system command prompt.

There is still a lot to learn about Jshell

From what has been discussed above

We’ve covered a lot of ground in this tutorial. You’ve learned that Java is a language and platform, and that there are three versions of Java. You know how the JVM executes Java class files. You’ve seen the differences between the JRE and JDK, and how to set up the JDK on your system. You’ve taken an in-depth look at Java application architecture and seen how to compile source code and execute class files using Javac and Java, as well as the newer JShell utilities.

Although Java is an object-oriented language, not all of its functionality is object-oriented. In the next tutorial, you’ll learn how to use identifiers, types, literals, and variables in Java programs. You’ll also learn why and how to document your code, and you’ll see how Java’s support for Unicode affects source code and compilation.

Before you can learn Java, you have to know what the language is and whether you like it or are just interested in it. If you want to learn the language, take a look at my learning path, which also provides some learning materials on how to learn Java from scratch quickly