(ebook) java 17 quick syntax reference: a pocket guide to the java se language, apis, and library by

Page 1


(Ebook)Java17QuickSyntaxReference:APocket GuidetotheJavaSELanguage,APIs,andLibrary byMikaelOlssonISBN9781484273708,1484273702

https://ebooknice.com/product/java-17-quick-syntaxreference-a-pocket-guide-to-the-java-se-language-apis-andlibrary-35397742

Start reading on any device today!

(Ebook) Java 17 Quick Syntax Reference: A Pocket Guide to the Java SE Language, APIs, and Library by Mikael Olsson ISBN 9781484273708, 1484273702

https://ebooknice.com/product/java-17-quick-syntax-reference-a-pocket-guide-tothe-java-se-language-apis-and-library-35397742

ebooknice.com

(Ebook) Java 17 Quick Syntax Reference by Mikael Olsson ISBN 9781484273708, 9781484273715, 1484273702, 1484273710

https://ebooknice.com/product/java-17-quick-syntax-reference-36311644

ebooknice.com

(Ebook) C++17 quick syntax reference: a pocket guide to the language, APIs and library by Olsson, Mikael ISBN 9781484235997, 9781484236000, 1484235991, 1484236009

https://ebooknice.com/product/c-17-quick-syntax-reference-a-pocket-guide-to-thelanguage-apis-and-library-18707160

ebooknice.com

(Ebook) C# 7 Quick Syntax Reference: A Pocket Guide to the Language, APIs, and Library by Mikael Olsson ISBN 9781484238172, 1484238176

https://ebooknice.com/product/c-7-quick-syntax-reference-a-pocket-guide-to-thelanguage-apis-and-library-11124196

ebooknice.com

(Ebook) C++20 Quick Syntax Reference : a pocket guide to the language, APIs, and library by Mikael Olsson ISBN 9781484259948, 1484259947

https://ebooknice.com/product/c-20-quick-syntax-reference-a-pocket-guide-to-thelanguage-apis-and-library-11324708

ebooknice.com

(Ebook) C++20 Quick Syntax Reference A Pocket Guide to the Language, APIs, and Library. by Mikael Olsson ISBN 9781484259955, 1484259955

https://ebooknice.com/product/c-20-quick-syntax-reference-a-pocket-guide-to-thelanguage-apis-and-library-11361766

ebooknice.com

(Ebook) C# 7 Quick Syntax Reference: A Pocket Guide to the Language, APIs, and Library by Mikael Olsson ISBN 9781484238165, 1484238168

https://ebooknice.com/product/c-7-quick-syntax-reference-a-pocket-guide-to-thelanguage-apis-and-library-55536142

ebooknice.com

(Ebook) C# 10 Quick Syntax Reference: A Pocket Guide to the Language, APIs, and Library by Mikael Olsson ISBN 9781484279809, 1484279808

https://ebooknice.com/product/c-10-quick-syntax-reference-a-pocket-guide-to-thelanguage-apis-and-library-38282522

ebooknice.com

(Ebook) C++17 quick syntax reference: apocket guide to the language, apis and library by Olsson, Mikael ISBN 9781484217269, 9781484235997, 1484217268, 1484235991

https://ebooknice.com/product/c-17-quick-syntax-reference-apocket-guide-to-thelanguage-apis-and-library-11863066

ebooknice.com

Java 17 Quick Syntax Reference

Mikael Olsson

Introduction

Java is a high-level object-oriented programming language developed by Sun Microsystems, which became part of Oracle Corporation in 2010. The language is very similar to C++ but has been simplified to make it easier to write bug-free code. Most notably, unlike C++, there are no pointers in Java—instead, all memory allocation and deallocation is handled automatically.

Despite simplifications like this, Java has considerably more functionality than C++, due to its large class library. Java programs also have high performance and can be made very secure, which has contributed to making Java the most popular general-purpose programming language in use today.

Another key feature of Java is that it is platform independent. This is achieved by only compiling programs halfway, into platform-independent instructions called bytecode. The bytecode is then interpreted, or run, by the Java Virtual Machine (JVM). That means any system that has this program and its accompanying libraries installed can run Java applications.

To allow Java to be used in a variety of environments, there are four different editions: Java ME, Java SE, Java EE, and Java FX. Each edition contains a JVM and a set of class libraries. Java SE (Standard Edition) provides the standard JVM along with the commonly used libraries for building applications, in particular desktop applications. Java ME (Micro Edition) is a small-footprint version of Java SE designed for running on small devices such as mobile phones. Java EE (Enterprise Edition) is an extended version of Java SE that includes libraries for building large-scale

Chapter 1 hello World

box, select the Java Application project under the Java with Ant category, and click Next. In this dialog box, set the project name to “MyProject” and the name of the main class to “myproject.MyApp”. Change the project’s location if you want, and click Finish to generate the project. The project’s only file, MyApp.java, will then open up, containing some default code. You can go ahead and remove all of that code so that you start with an empty source file.

Hello World

When you have your project and programming environment set up, the first application you will create is the Hello World program. This program will teach you how to compile and run Java applications, as well as how to output a string to a command window.

The first step in creating this program is to add a public class to your MyApp.java source file. The class must have the same name as the physical source file without the file extension—in this case, “MyApp.” It’s legal to have more than one class per file in Java, but only one public class is allowed, and its name must match the filename. Keep in mind that Java is case sensitive. The curly brackets following the class name delimit what belongs to the class and must be included. The brackets, along with their content, are referred to as a code block, or just a block.

public class MyApp {}

Java classes are organized into packages, which are similar to namespaces in other languages. A package statement needs to appear at the top of the file to designate which package a file belongs to. This name must match the directory the file is located in relative to the project’s source directory, so in this case, the package name is myproject.

package myproject;

public class MyApp {}

Chapter 1 hello World

Next, add the main method inside the class. This is the starting point of the application and must always be included in the same form as is shown in the following code. The keywords themselves will be examined in later chapters.

package myproject; public class MyApp { public static void main(String[] args) {} }

The last step in completing the Hello World program is to output the text by calling the print method. This method is located inside the System class and then another level down inside the out class. The method takes a single argument—the string to be printed—and it ends with a semicolon, as do all statements in Java.

package myproject; public class MyApp { public static void main(String[] args) { System.out.print("Hello World"); } }

Note that the dot operator (.) is used to access members of a class. Similar to print, there’s also the println method, which automatically adds a line break at the end of the printed string. The System class belongs to the java.lang package, which is always included in a Java project.

Chapter 2 Compile and r un

By doing this, the console will be able to find the Java compiler from any folder for the duration of this console session. The PATH variable can also be permanently changed.1 Next, navigate to the folder where the Java source file is located, and run the compiler by typing javac followed by the complete filename.

C:\MyProject\src\myproject> javac MyApp.java

The program will be compiled into a class file called MyApp.class. This class file contains bytecode instead of machine code, so to execute it, you need to call the Java Virtual Machine by typing java followed by the fully qualified class name, which includes the package name. This command needs to be executed from the parent folder, the project’s source folder. Notice that the .java extension is used when compiling a file, but the .class extension is not used when running it.

C:\MyProject\src> java myproject.MyApp

Alternatively, as of Java 11, you can both compile and run the source file by giving the complete filename to the java command:

java MyApp.java

Comments

Comments are used to insert notes into the source code and have no effect on the end program. Java has the standard C++ comment notation, with both single-line and multi-line comments.

// single-line comment

/* multi-line comment */

1 www.java.com/en/download/help/path.xml

Chapter 3 VariaBleS

Declaring Variables

To declare (create) a variable, you start with the data type you want it to hold followed by a variable name. The name can be anything you want, but it’s a good idea to give your variables names that are closely related to the values they will hold. The standard naming convention for variables is that the first word should be lowercase and any subsequent words initially capitalized.

int myInt;

Assigning Variables

To give the variable a value, you use the assignment operator (=) followed by the value. When a variable is initialized (assigned a value), it then becomes defined (declared and assigned).

myInt = 10;

The declaration and assignment can be combined into a single statement:

int myInt = 10;

If you need multiple variables of the same type, there is a shorthand way of declaring or defining them using the comma operator (,):

int myInt = 10, myInt2 = 20, myInt3;

Using Variables

Once a variable has been defined, you can use it by simply referencing the variable’s name—for example, to print it:

System.out.print(myInt);

Chapter 3 VariaBleS

Variable Scope

The scope of a variable refers to the code block within which it’s possible to use that variable without qualification. For example, a local variable is a variable declared within a method. Such a variable will only be available within the method’s code block, after it’s been declared. Once the scope (code block) of the method ends, the local variable will be destroyed.

public static void main(String[] args)

int localVar; // local variable

In addition to local variables, Java has field- and parameter-type variables, which later chapters will cover. But Java doesn’t have global variables, as, for example, C++ does.

Anonymous Block

You can restrict the scope of local variables using an anonymous (unnamed) code block. This construct is seldom used, because if a method is large enough to warrant the use of an anonymous block, a better choice is often to break up the code into separate methods.

public static void main(String[] args)

// Anonymous code block

int localVar = 10;

// localVar is unavailable from here

Type Inference

Beginning with Java 10, local variables can be declared with var to have the compiler automatically determine the type of the variable based on its assignment. The following two declarations are therefore equivalent:

var i = 5; // Implicit type int i = 5; // Explicit type

When to use var comes down to preference. In cases when the type of the variable is obvious from the assignment, use of var may be preferable to shorten the declaration and improve readability. The benefit becomes more apparent when using a non-primitive type as seen in this example.

// No type inference java.util.ArrayList a = new java.util.ArrayList();

// With type inference var a = new java.util.ArrayList();

Keep in mind that var can only be used when a local variable is both declared and initialized at the same time.

Chapter 4 OperatOrs

The result on the variable is the same whichever is used. The difference is that the post-operator returns the original value before it changes the variable, while the pre-operator changes the variable first and then returns the value.

int x, y;

x = 5; y = x++; // y=5, x=6

x = 5; y = ++x; // y=6, x=6

Comparison Operators

The comparison operators compare two values and return either true or false. They’re mainly used to specify conditions, which are expressions that evaluate to either true or false.

boolean b = (2==3); // equal to (false)

b = (2!=3); // not equal to (true)

b = (2>3); // greater than (false)

b = (2<3); // less than (true)

b = (2>=3); // greater than or equal to (false)

b = (2<=3); // less than or equal to (true)

Logical Operators

The logical operators are often used together with the comparison operators. Logical and (&&) evaluates to true if both the left and right side are true, and logical or (||) is true if either the left or right side is true. For inverting a Boolean result, there is a logical not (!) operator. Note that for both logical and and logical or, the right-hand side won’t be evaluated if the result is already determined by the left-hand side.

boolean b = (true && false); // logical and (false)

b = (true || false); // logical or (true)

b = !(true); // logical not (false)

CHAPTER 5 String

The String class in Java is a data type that can hold string literals. String is a reference data type, as are all non-primitive data types. This means that the variable contains an address to an object in the memory and not the object itself. A String object is created in the memory, and the address to the object is returned to the variable. As seen in the following code, string literals are delimited by double quotes:

String a = "Hello";

String literals are stored in the so-called String pool, maintained by the String class. For performance reasons, any string literal that is equal to a previously created string will refer to the same String object in the pool. This works because strings in Java are immutable and therefore cannot be changed without creating a new String object.

String a1 = "Hello";

String a2 = "Hello"; // refers to same object as a1

Combining Strings

The plus sign is used to combine two strings. Known as the concatenation operator (+) in this context, it has an accompanying assignment operator (+=) that appends one string to another and creates a new string.

String a = "Hello";

String b = " World";

© Mikael Olsson 2022 M. Olsson, Java 17 Quick Syntax Reference, https://doi.org/10.1007/978-1-4842-7371-5_5

CHapter 5 StriNg

String c = a+b; // "Hello World" a += b; // "Hello World"

Note that although a statement may be divided into multiple lines, a string must be on a single row unless it’s split up using the concatenation operator:

String x = "Hello " + "World";

Escape Characters

For adding new lines to the string itself, there is the escape character (\n). This backslash notation is used to write special characters, such as backslash and double quotes. Among the special characters is also a Unicode character notation for writing any character. All the escape characters can be seen in the following table.

Character Meaning

\n Newline

\t Horizontal tab

\b Backspace

\r Carriage return

\uFFFF

Unicode character(four-digit hex number)

\f Form feed

\’ Single quote

\” Double quotes \\ Backslash

CHapter 5 StriNg

You can convert a StringBuffer object back into a regular string with the toString method, which returns a string representation of the object. It exists for every class in Java, because it’s defined by Object, which is inherited by all classes.

String s = sb.toString();

Text Blocks

A text block is a multi-line string delimited by three double quotes ("""). It provides a simplified way to write a string that spans more than one line without having to specify escape characters, such as newlines or quotes.

String textBlock = """ line 1 line 2""";

The line break after the opening delimiter is mandatory, so a text block must span more than one line. Any line break used within a text block will automatically be interpreted as a newline character, so the previous text block is equivalent to the following string:

String s = "line 1\nline 2";

Whitespace that indents one line of text relative to other lines will be kept. However, any initial whitespace used to indent all lines will be removed.

String html = """ <div> <p>Hi</p> </div>""";

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.