Java Tutorials - Herong's Tutorial Examples
By Herong Yang
()
About this ebook
For latest updates and free sample chapters, visit https://www.herongyang.com/Java.
Read more from Herong Yang
EC Cryptography Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsXML Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsXSD Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsBlowfish Cipher Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsJDK Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsPerl Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsSOAP Web Service Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsJava Swing Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsWSDL Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsBitcoin Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsJava Tools Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsJVM Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratingsJDBC Tutorials - Herong's Tutorial Examples Rating: 0 out of 5 stars0 ratings
Related to Java Tutorials - Herong's Tutorial Examples
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5C Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsBeginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Programming Arduino: Getting Started with Sketches Rating: 4 out of 5 stars4/5Coding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsC# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratings
Reviews for Java Tutorials - Herong's Tutorial Examples
0 ratings0 reviews
Book preview
Java Tutorials - Herong's Tutorial Examples - Herong Yang
Java Tutorials
- Herong's Tutorial Examples
Iconv8.22, 2024
Herong Yang
Copyright © 1997-2024 Herong Yang. All rights reserved.
ISBN: 978-0-359-43966-9
This tutorial book is a collection of notes and sample codes written by the author while he was learning Java himself. Topics covered in the book include: Java language basics; execution environment; generic classes and parameterized type; generic methods and type argument inferences; enum types and constants; lambda expressions; annotation types and invocations; Java modules; execution threads and synchronization; memory management and garbage collection. Updated in 2024 (Version v8.22) with JDK 20.
Table of Contents
About This Book
JDK - Java Development Kit
Downloading and Installing JDK on Mac
Downloading and Installing JDK on Windows
Adding JDK bin
Directory to Path Setting
Downloading and Installing JDK on Linux
Writing My First Java Program
JDK Documentation Installation
Execution Process, Entry Point, Input and Output
Creating, Compiling and Executing Java Programs
main() Method - Java Execution Entry Point
Java Execution Console - in
, out
and err
Data Streams
Primitive Data Types and Literals
Data Types Supported in Java
Integer Data Types
Floating-Point Data Types
Logical (Boolean) Data Type
Literals of Primitive Types
Literal Formats for Integers
Literal Formats for Integers - Example
Literal Formats for Floating-Point
Literal Formats for Floating-Point - Example
Literal Formats for Characters
Literal Formats for Character - Example
Control Flow Statements
What Is Control Flow Statement
if-then
Statements
if-then-else
Statements
Nested if-then-else
Statements
switch
Statements
Fall-Through Behavior of switch
Statements
Basic for
Statements
Enhanced for
Statements
while
Statements
do
Statements
break
Statements
Labeled break
Statements
continue
Statements
Labeled continue
Statements
Bits, Bytes, Bitwise and Shift Operations
What Are Bits and Bytes
byte
Data Type and Implicit Casting
Operations on byte
Data Type Values
Bitwise Operations on byte
Values
Bitwise Operations on byte
Values - Example Program
Shift Operations - Left, Right or Unsigned Right
Managing Bit Strings in Byte Arrays
setBit() - Storing a Bit into a Byte Array
getBit() - Retrieving a Bit from a Byte Array
rotateLeft() - Left Rotating All Bits in a Byte Array
bitStringTest.java - Testing Program
Reference Data Types and Variables
Reference Types Supported in Java
Creating Class Type Objects
Class Type Variables Storing References
Interface Type Variables
Class and Interface Hierarchy
Supertype and Subtype
Explicit and Implicit Type Casting
Type Casting Example Program
Type Casting Compile and Runtime Error
Enum Types and Enum Constants
What Is an Enum Type
Use 'class' to Define Enumeration
Instance Variables for Enum Constants
java.lang.Enum Super Type
Enum Constant Inherited Methods
Enum Constant Implicit Methods
StringBuffer - The String Buffer Class
StringBuffer Class Properties and Methods
SimpleStringBuffer - My Implementation of String Buffer
Performance Comparison of String and StringBuffer
System Properties and Runtime Object Methods
JVM and OS System Properties
System.setProperty() - Setting Your Own Properties
Runtime.getRuntime() - Getting the Runtime Object
freeMemory() - Getting JVM Free Memory Information
Calculating Memory Usage of an Array
exec() - Executing Operating System Commands
Generic Classes and Parameterized Types
What Is a Generic Class
Using a Generic Class
Using a Generic Class - Example
Creating a Generic Class
Creating a Generic Class - Example
Bounded Type Parameters
Raw Type, Generic Type and Parameterized Type
Parameterized Type and Subtyping
Wildcard Parameterized Types
Wildcard Parameterized Type Test
Wildcard Parameterized Subtyping
Wildcard Parameterized Subtyping Example
Generic Methods and Type Inference
What Is a Generic Method
Comparing Generic Method with Non-Generic Method
Non-Generic Method Example - maxNonGeneric()
Generic Method Example - maxGeneric()
Generic Methods in java.util.Collections Class
Testing Generic Methods in Collections Class
What Is Type Argument Inference
Type Argument Inference by Parameter List
Type Argument Inference by Return Value
Generic Methods using Parameterized Types
Parameterized Type as Generic Method Return Type
Lambda Expressions and Method References
What Is Lambda Expression
LambdaCalculator.java - Lambda Expression Example
Lambda Expression Syntax Options
Lambda Expression as Method Reference
Method Reference Example - LambdaMethodRefernce.java
Lambda Expression Stream Pipeline Operations
Java Modules - Java Package Aggregationxhtml
What Is Java Module
Module Descriptor - module-info.java
Creating Hello World!
Module
jmod create
- Creating JMOD File
jlink --add-modules
- Creating Custom JRE
Running .\bin\java
Command in Custom JRE
Accessing Non-Exported Package in Module
Module Dependency and Package Accessibility
com.herongyang.base Module Implementation
com.herongyang.base Module Compilation
com.herongyang.math Module Implementation
geometryJRE and Module Deliverables
Getting com.herongyang.base Module Info
Testing Exported Package in Module
Testing Un-Exported Package in Module
Application using com.herongyang.math Module
Execution Threads and Multi-Threading Java Programs
What Are Processes and Threads
The Thread
Class - Creating Thread Objects With Thread Sub Classes
The Runnable
Interface - Creating Thread Objects with Runnable Objects
CPU Execution Time Shared by Multiple Threads
CPU Execution Time Shared by Multiple Threads - Test Output
Application Data Shared by Multiple Threads
Application Data Shared by Multiple Threads - Test Results
interrupt() - Method to Terminate Thread
ThreadGroup Class and system
ThreadGroup Tree
ThreadGroup
Class - Container of Threads and Thread Groups
Displaying the system
ThreadGroup Tree
Adding Threads and Thread Groups
Synchronization Technique and Synchronized Code Blocks
Why Synchronization Is Needed in Multi-Threading Applications
Synchronization Technique - Lock and Synchronized Code
synchronized
- How Java Supports Synchronization
BankingThread.java - Synchronization Sample Program
BankingThread.java - Synchronization Sample Program Output
Deadlock Condition Example Programs
What Is Deadlock
Deadlock Example - 5 Dining Philosophers
Deadlock Example - Transferring Funds
Garbage Collection and the gc() Method
Garbage Collection and Unused Objects
The Automated Garbage Collection Process
gc() - The Garbage Collection Method
Example Program of Using the gc() Method
Assert Statements and -ea" Optionxhtml
assert
Statements
JVM -ea
and -da
Options
Annotation Statements and Declarationsxhtml
What Is Annotation
Use interface
as Annotation
Default Values for Annotation Elements
Single-Element Annotation Invocation
No-Element (Marker) Annotation Invocation
getAnnotations() Method - Annotation APIs
Predefined Annotation Types
Java Related Terminologies
Archived Tutorials
Archived: Downloading and Installing JDK 13 on Mac
Archived: Downloading and Installing JDK 10
Archived: JDK 10 Documentation Installation
Archived: Downloading and Installing JDK 8
Archived: Downloading and Installing JDK 1.7
Archived: Downloading and Installing JDK 1.6
Archived: Downloading and Installing JDK 1.5
Archived: JDK 1.3 Bug - Memory Leak With Unstarted Threads
References
Keywords: Java, Language, Tutorial
Java Tutorials - Herong's Tutorial Examples
∟ About This Book
This section provides some detailed information about this book - Java Tutorials - Herong's Tutorial Examples.
Title: Java Tutorials - Herong's Tutorial Examples
Author: Herong Yang - Contact by email via herong_yang@yahoo.com.
Category: COMPUTERS / Programming Languages / Java
Version/Edition: v8.22, 2024
Number of pages in PDF format: 345
Description: This tutorial book is a collection of notes and sample codes written by the author while he was learning Java himself. Topics covered in the book include: Java language basics; execution environment; generic classes and parameterized type; generic methods and type argument inferences; enum types and constants; lambda expressions; annotation types and invocations; Java modules; execution threads and synchronization; memory management and garbage collection. Updated in 2024 (Version v8.22) with Java 20.
Keywords: Java, variable, type, expression, statement, method, class, package, module, thread, deadlock.
Cost/Price: Free in Web format
Copyright:
This book is under Copyright © 1997-2024 Herong Yang. All rights reserved.
Material in this book may not be published, broadcasted, rewritten or redistributed in any form.
The example codes is provided as-is, with no warranty of any kind.
Revision history:
Version v8.22, 2024. Updated with Java 20.
Version v8.10, 2018. Added Java Module tutorials.
Version v8.00, 2018. Updated with Java 10.
Version v7.00, 2014. Updated with Java 8.
Web version: https://www.herongyang.com/Java - Provides free sample chapters, latest updates and readers' comments. The Web version of this book has been viewed a total of:
1,843,942 times as of December 2023.
1,777,039 times as of December 2022.
1,714,845 times as of December 2021.
1,638,051 times as of December 2020.
1,569,354 times as of December 2019.
1,514,290 times as of December 2018.
1,455,289 times as of December 2017.
1,390,927 times as of December 2016.
1,309,223 times as of December 2015.
1,195,256 times as of December 2014.
1,058,373 times as of December 2013.
913,999 times as of December 2012.
797,813 times as of December 2011.
540,252 times as of December 2010.
309,845 times as of December 2009.
140,533 times as of December 2008.
PDF/EPUB version: https://www.herongyang.com/Java/PDF-Full-Version.html - Provides information on how to obtain the full version of this book in PDF, EPUB, or other format.
Java Tutorials - Herong's Tutorial Examples
∟ JDK - Java Development Kit
This chapter provides tutorial notes on installing JDK on your own Windows system to run Java programs. Topics include downloading and installing JDK; compiling and executing Java programs, installing JDK documentation.
Downloading and Installing JDK on Mac
Downloading and Installing JDK on Windows
Adding JDK bin
Directory to Path Setting
Downloading and Installing JDK on Linux
Writing My First Java Program
JDK Documentation Installation
Takeaways:
Downloading and installing JDK on Windows, Mac, or Linux computers is easy and fast.
Compiling and running the first Java program requires 2 commands: javac
and java
.
Java Tutorials - Herong's Tutorial Examples
∟ JDK - Java Development Kit
∟ Downloading and Installing JDK on Mac
This section describes how to download and install JDK 13 on a Mac computer
To learn Java, you need to have a copy of JDK (Java Development Kit) installed on your machine. If you are a Mac computer user, you can follow this tutorial to download and install JDK 20 on your Mac computer.
1. Go to Oracle Java SE download website at oracle.com/technetwork/java/javase/downloads.
2. Click JDK 20 > macOS
tab.
3. Click on the jdk-20_macos-x64_bin.dmg
link in the x64 DMG Installer
line to download the installation file to your Downloads
directory.
4. Double-click on the jdk-20_macos-x64_bin.dmg
file to install it.
To test the installation, open a command window to try the java command.
herong$ java -version
java version 20.0.1
2023-04-18
Java(TM) SE Runtime Environment (build 20.0.1+9-29)
Java HotSpot(TM) 64-Bit Server VM (build 20.0.1+9-29, mixed mode, sharing)
Cool, I have successfully installed JDK 20 on my macOS computer!
Java Tutorials - Herong's Tutorial Examples
∟ JDK - Java Development Kit
∟ Downloading and Installing JDK on Windows
This section describes how to download and install JDK on a Windows system.
To learn Java, you need to have JDK installed on your computer. If you are Windows user, you can follow what I did to download and install JDK 17 on your Windows computer.
1. Open the Java SE Download page with this URL: https://www.oracle.com/java/technologies/downloads/.
2. Click the Windows
tab under the Java SE Development Kit 17.0.1 downloads
. You will see a new page with a list of different download files of JDK 17.
3. Click the hyper link of https://download.oracle.com/java/17/latest/jdk-17_windows-x64_bin.exe
, next to x64 Installer 152 MB
.
4. Save jdk-17_windows-x64_bin.exe to a temporary directory.
5. Double-click on jdk-17_windows-x64_bin.exe to start the installation wizard.
6. Follow instructions on the installation wizard to finish the installation.
The picture below shows you how the JDK 17 Installation Screen looks like:
JDK 17 Installation ScreenJDK 17 Installation Screen
To test the installation, open a command window to try the java command. If you are getting the following output, your installation is good:
herong> \progra~1\java\jdk-17.0.1\bin\java -version
java version 17.0.1
2021-10-19 LTS
Java(TM) SE Runtime Environment (build 17.0.1+12-LTS-39)
Java HotSpot(TM) 64-Bit Server VM
(build 17.0.1+12-LTS-39, mixed mode, sharing)
Congratulations, you have successfully installed JDK on your Windows computer!
Java Tutorials - Herong's Tutorial Examples
∟ JDK - Java Development Kit
∟ Adding JDK bin
Directory to Path Setting
This section provides a tutorial on how to add JDK 'bin' directory to the 'path' system envirnoment variable.
In order to run Java compiler and JVM by typing their program file name without the directory path name, I updated the path
environment variable on my Windows computer:
Open Control Panel > System and Security > System
.
Click Advanced system settings
.
Click Environment Variables
.
Select System variables > Path
and click Edit
.
Add C:\Progra~1\java\jdk-17.0.1\bin;
to the beginning of the current path list.
Click OK
to save the change.
Then I ran the echo %path%
command in a new command window to confirm the change:
herong> echo %path%
C:\Progra~1\java\jdk-17.0.1\bin;
C:\Program Files\Common Files\Oracle\Java\javapath;
C:\ProgramData\Oracle\Java\javapath;
...
Now I should be able to run Java commands without the directory path name:
herong> java -version
java version 17.0.1
2021-10-19 LTS
...
herong> javac hello.java
herong> java Hello
Hello world!
Now I am ready to play with Java tools included in Oracle JDK package!
Adding JDK bin Directory to Path SettingAdding JDK bin
Directory to Path Setting
You can also set a new environment variable called java_home
to avoid typing the full path name to access Java tool program files:
herong> set java_home=C:\Progra~1\java\jdk-17.0.1
herong> %java_home%\bin\java -version
java version 17.0.1
2021-10-19 LTS
...
Java Tutorials - Herong's Tutorial Examples
∟ JDK - Java Development Kit
∟ Downloading and Installing JDK on Linux
This section provides a tutorial example on how to download and install JDK on Linux systems. The best way to install JDK on CentOS system is to the 'yum' package management tool.
Downloading and installing JDK on a Linux computer is more difficult for several reasons:
1. There are many variations and versions of Linux platforms running on different system architectures. So there is no single JDK package that works perfectly on all Linux platforms.
2. Oracle offers 3 binary packages for all Linux platforms with some installation instructions:
Package Platforms
------- -------
Linux Debian Package Debian
Linux RPM Package Red Hat and SuSE
Linux Compressed Archive Generic
3. OpenJDK offers a single generic binary package for all Linux platforms.
If you try to install the generic binary package on your specific Linux platform, you most likely will encounter some issues.
The best way to install JDK on your specific Linux platform is to use the package management tool on the system to search and automatically install the OpenJDK binary package that was built specifically for your platform.
Here is what did to on my CentOS system with the yum
package management tool to search for openJDK, logging in as root
:
herong# yum search openJDK
java-1.6.0-openjdk.i686 : OpenJDK Runtime Environment
java-1.6.0-openjdk-devel.i686 : OpenJDK Development Environment
java-1.6.0-openjdk-javadoc.i686 : OpenJDK API Documentation
java-1.6.0-openjdk-src.i686 : OpenJDK Source Bundle
...
java-1.8.0-openjdk.i686 : OpenJDK Runtime Environment
java-1.8.0-openjdk-devel.i686 : OpenJDK Development Environment
java-1.8.0-openjdk-javadoc.noarch : OpenJDK API Documentation
java-1.8.0-openjdk-src.i686 : OpenJDK Source Bundle
So the latest version for my platform is OpenJDK 1.8, divided into several parts. To install JDK with compiler and other tools, I need to install java-1.8.0-openjdk.i686 and java-1.8.0-openjdk-devel.i686:
herong# yum install java-1.8.0-openjdk
...
Installed:
java-1.8.0-openjdk.i686 1:1.8.0.232.b09-1.el6_10
herong# yum install java-1.8.0-openjdk
...
Installed:
java-1.8.0-openjdk-devel.i686 1:1.8.0.232.b09-1.el6_10
Now verify the installation:
herong# java -version
openjdk version 1.8.0_232
OpenJDK Runtime Environment (build 1.8.0_232-b09)
OpenJDK Server VM (build 25.232-b09, mixed mode)
herong# javac -version
javac 1.8.0_232
Finally, set the JAVA_HOME environment variable, so other applications can find where JDK is installed. This can be done with an export
command.
herong# export JAVA_HOME=/usr/lib/jvm/jre-1.8.0-openjdk.i386
Congratulations, you have successfully installed JDK on your Linux system!
Java Tutorials - Herong's Tutorial Examples
∟ JDK - Java Development Kit
∟ Writing My First Java Program
This section provides a tutorial example on how to write, compile, and execute the first Java program with JDK.
When JDK is installed on your machine, it provides two commands for you to compile and run Java programs.
javac class_name.java
- Compiles a Java program stored a file named with the program class name.
java -classpath . class_name
- Runs a compiled Java program. -classpath .
specifies the current directory as the class path.
Let's try these commands with a very simple Java program. Use NotePad to enter the following Java program into a file called Hello.java:
class Hello {
public static void main(String[] a) {
System.out.println(Hello world!
);
}
}
Then compile this program in a command window with the javac
command:
herong> javac Hello.java
To execute the program, use the java command:
herong> java Hello
Hello world!
Congratulations, you have successfully entered, compiled and executed your first Java program.
Java Tutorials - Herong's Tutorial Examples
∟ JDK - Java Development Kit
∟ JDK Documentation Installation
This section describes how to install JDK Documentation on your own local machine.
To learn Java more effectively, you definitely need to have a copy of the JDK Documentation installed on your computer. JDK Documentation provides you detailed information of all classes and methods used in JDK.
You can follow what I did to download and install JDK 17 Documentation.
1. Open the Java download home page with this URL: https://www.oracle.com/java/technologies/downloads/.
2. Click the Documentation Download
button near the bottom of the page. You will see Java SE Development Kit 17 Documentation
page showing up.
3. Click the hyper link of jdk-17.0.1_doc-all.zip
.
4. Save the download file jdk-17.0.1_doc-all.zip
to a temporary directory.
5. Double-click on jdk-17.0.1_doc-all.zip
to extract all files to "C:\Program Files\Java\jdk-17.0.1 directory.
6. To verify the installation, open the C:\Program Files\Java\jdk-17.0.1\docs\index.html
with a Web browser. You should see the JDK 17 Documentation starting page.
7. Click the java.logging
module on the JDK 17 Documentation page to see the API documentation of the java.logging module.
If you are a Mac user, you need to extract all files from jdk-17.0.1_doc-all.zip
to /Library/Java/JavaVirtualMachines/jdk-17.jdk directory. And open docs/index.html
from that directory in a Web browser.
If you are a Linux user, you can extract all files from jdk-17.0.1_doc-all.zip
to the ~/jdk directory. And open docs/index.html
from that directory in a Web browser.
Java Tutorials - Herong's Tutorial Examples
∟ Execution Process, Entry Point, Input and Output
This chapter provides tutorial notes and tutorial examples on Java program execution process. Topics include Java program creation, compilation and execution; the main() method - execution entry point; execution console, input and output data streams.
Creating, Compiling and Executing Java Programs
main() Method - Java Execution Entry Point
Java Execution Console - in
, out
and err
Data Streams
Takeaways:
3 steps are involved in building a Java application: creating source code, compiling source code and executing the compiled code.
public static void main(String[] a)
is the execution entry point when a class is launched in the Java Virtual Machine (JVM).
JVM provided 3 default I/O data streams to all applications: in
, out
and err
.
Java Tutorials - Herong's Tutorial Examples
∟ Execution Process, Entry Point, Input and Output
∟ Creating, Compiling and Executing Java Programs
This section describes the process of Java program creation, compilation and execution. JDK 'javac' and 'java' commands are also described.
There are 3 steps involved in building and running a Java program:
Creating Program Source Code: Creating one text file written Java language statements to define each Java class or other program unit. The text file is called source code file, which must have a file name identical to the name of the class defined in the file, and an extension of .java
. One of the source code files should define the main class which contains the main
method as the execution starting point. Other source code files define additional classes and other program units to support the main class.
Compiling Source Code: Converting all source code files of the program into bytecode files written in Java Virtual Machine (JVM) instructions. The bytecode file must have the same file name as the source code file, and an extension of .class
.
Executing the Java Program: Loading the bytecode file of the main class into JVM, and executing its JVM instructions starting from the main
method.
Creating a source code file can be done by a simple text editor, notepad, or a sophisticated Java development environment tool, like Eclipse, or Visual J++.
Compiling a source code file needs a Java compiler. The JDK package contains a Java compiler, which can be invoked by the command javac
. The javac
command takes source code file names as command line arguments. For example, entering the following command in command window will invoke the javac
compiler to compile the Hello.java
source code file:
herong> javac Hello.java
The javac
command also has several command options available:
-d: Specify the directory where the bytecode files generated by the compiler should be placed, if you don't want to place them in the current directory.
-classpath: Specify the directories where to search for classes or interfaces definitions in bytecode format, if the classes or interfaces are used in source code file.
-sourcepatch: Specify the directories where to search for classes or interfaces definitions in source code format, if the classes or interfaces are used in source code file.
For example, the following command:
herong> javac -d .\cls -classpath .\lib;.\cls \
-sourcepath .\src .\src\Hello.java
invokes the javac
compiler, and tells it to:
Compile the Hello.java
source code file in the .\src
directory.
Place the bytecode file, Hello.class
, in the .\cls
directory.
Search .\lib
and .\cls
directories for the definitions in bytecode format of classes or interfaces that are used in Hello.java
.
Search .\src
directory for the definitions in source code format of classes or interfaces that are used in Hello.java
.
Executing a Java program needs a JVM. The JDK also contains a JVM, called HotSpot, which can be invoked by the command java
. The java
command takes the name of the starting class as the command argument. For example, the following command:
herong> java -classpath .\lib;.\cls;. Hello
invokes HotSpot to:
Load Hello
class into HotSpot.
Execute the main() method of the Hello
class.
The -classpath
option specifies the class path, which contains directories where the JVM will search for the bytecode files of the starting class and other program units when needed.
Java Tutorials - Herong's Tutorial Examples
∟ Execution Process, Entry Point, Input and Output
∟ main() Method - Java Execution Entry Point
This section describes the Java program entry point, the main() method of the starting class. Command line arguments are passed as an string array parameter to the main() method.
As mentioned in the previous section, a Java application program must have a main class with a special method call main() as the execution entry point. The main() method must be defined as:
public static void main(String[] a) {
// statement block
}
Note that the main() method must be declared as public static void
.
The parameter of the main() method is an array of String
, which contains the additional arguments after the class name argument in the java
command line. Let's use the following Java program to illustrate how those arguments are passed into the main() method: