Date post: | 14-Apr-2018 |
Category: |
Documents |
Upload: | gteodorescu |
View: | 242 times |
Download: | 2 times |
of 683
7/27/2019 ZetCode Java tutorial.doc
1/681
ZetCode Java tutorial
This is a Java tutorial. In this tutorial you will learn the Java language. The tutorial is suitablefor beginners.
Java
Java is a modern, high-level, general-purpose, object-oriented programming language. Thedesign goals of the language were software robustness, durability and programmer
productivity. It can be used to create console applications, GUI applications, webapplications, both on PCs or embedded systems.
Java language
In this part of the Java tutorial, we will introduce the Java programming language.
Goal
The goal of this tutorial is to get you started with the Java programming language. Thetutorial covers the core of the Java language. This tutorial uses command line compilers to
build applications.
Java
Java is a high-level, general-purpose, object-oriented programming language. The maindesign goals of the language were robustness, portability, high performance and security.Java is a multithreaded and distributed programming language. It can be used to createconsole applications, GUI applications, web applications, both on PCs or embedded systems.
Java is a programming language created by Sun Microsystems in 1991. The first publiclyavailable version of Java was released in 1995. Today, the language is developed by Oraclecorporation.
Java excels in creating portable mobile applications, programming various appliances and increating enterprise applications.
Popularity
There are currently several widely used programming languages. Java belongs to the mostpopular languages today. Several surveys put it into the top three languages in the world.
Java platforms
Java has four programming platforms:
Java Platform, Standard Edition (Java SE) Java Platform, Enterprise Edition (Java EE)
1
7/27/2019 ZetCode Java tutorial.doc
2/681
Java Platform, Micro Edition (Java ME)
JavaFX
All Java platforms consist of a Java Virtual Machine (JVM) and an application programminginterface (API). The Java Virtual Machine is a program, for a particular hardware and
software platform, that runs Java applications. An API is a collection of software componentsthat we can use to create other software components or applications.
Java SEis used for developing desktop applications. Java SE's API provides the corefunctionality of the Java programming language. It consists of a virtual machine,development tools, deployment technologies, and other class libraries and toolkits used inJava applications.Java EEis built on top of the Java SE platform. The Java EE platform
provides an API and runtime environment for developing and running web applications andlarge-scale, multi-tiered, scalable, reliable, and secure enterprise applications. Java MEis asubset of the Java SE. It provides an API and a small-footprint virtual machine for runningJava applications on small devices, like mobile phones.JavaFXis a platform for creating rich
internet applications using a lightweight user-interface API.
In our tutorial, we use the Java SE platform to create simple console applications.
JDK
Strictly speaking, Java SE is a platform specification. Java Platform, Standard EditionDevelopment Kit (JDK) is an official implementation of the Java SE by Oracle. There arealso other implementations. For example free and open source OpenJDK or IBM's J9.
$ ls jdk1.7.0_02/bin db jre LICENSE README.html src.zipCOPYRIGHT include lib man release THIRDPARTYLICENSEREADME.txt
After we dowload and unpack the Oracles's JDK, we can see the contents of the JDK in theour jdk1.7.0_02 directory. The development tools are located in the bin/ subdirectory. TheJava javac compiler and the java application launcher are located in this subdirectory. The
jre/ subdirectory contains the JVM, class libraries and other files that help execute Javaprograms. The lib/ subdirectory has some additional class libraries and support files. The db/subdirectory contains the Java DB, which is the Oracle's distribution of the Apache Derbydatabase. In the include/ subdirectory we can find header files that support native-code
programming. The src.zip file contains source files for all classes that make up the Java coreAPI.
JVM
Java virtual machine (JVM) is a program that can execute Java bytecode. The JVM isincluded in the JDK. Java source code is written in files with the .java extension. ThejavacJava compiler will compile the Java source code into the Java bytecode; the compiled fileshave the .class extension. This bytecode is executed by JVM. Thejava tool is a launcher forJava applications. Oracle's JVM is called HotSpot. HotSpot is a Java virtual machine fordesktops and servers. It has advanced techniques such as just-in-time compilation and
adaptive optimization designed to improve performance.
2
7/27/2019 ZetCode Java tutorial.doc
3/681
Compiling a simple program
In order to develop Java applications, we need to dowloand a JDK. Oracle's official JDK canbe downloaded from this dowload page.
$ mkdir -p com/zetcode
Inside the current working directory, we create a com/zetcode/ subdirectory. Java source filesare organized in modules called packages. The packages must match the directory structure.
$ touch com/zetcode/SimpleExample.java
A SimpleExample.java source file is created in the com/zetcode/ subdirectory. Java sourcefiles have a .java extension.
package com.zetcode;
public class SimpleExample {
public static void main(String[] args) {
System.out.println("This is simple Java example.");}
}
This is a source code for a simple Java example. This example prints a message to theconsole.
package com.zetcode;
The package name must correspond to the directory structure in which the source file islocated.
public class SimpleExample {
The public class name is required to match the file name.
$ javac com/zetcode/SimpleExample.java
Using the javac compiler, we compile the source code.
$ ls com/zetcode/SimpleExample.class SimpleExample.java
The compiler generetes a Java bytecode, which is executed by the Java Virtual Machine. Thebytecode has a .class extension.
$ java com.zetcode.SimpleExampleThis is simple Java example.
With the java application launcher, we execute the program. It starts a Java runtime
environment, loading a specified class, and invoking that class's main method. The .class
3
http://www.oracle.com/technetwork/java/javase/downloads/index.htmlhttp://www.oracle.com/technetwork/java/javase/downloads/index.html7/27/2019 ZetCode Java tutorial.doc
4/681
extension is excluded; it is assumed. The program name is a fully qualified name of theprogram - com.zetcode.SimpleExample. It includes the name of the program and its package.
Sources
The following sources were used to create this tutorial:
Oracle's Java tutorial
Java Platform, Standard Edition 7 API Specification
The Java Language Specification
In this part of the Java tutorial, we have introduced the Java language.
Lexical structure
Computer languages, like human languages, have a lexical structure. A source code of a Javaprogram consists of tokens. Tokens are atomic code elements. In Java we have comments,identifiers, literals, operators, separators and keywords.
Java programs are composed of characters from the Unicode character set.
Comments
Comments are used by humans to clarify source code. There are three types of comments inJava.
Comment type Meaning
// comment Single-line comments
/* comment */ Multi-line comments
/** documentation */ Documentation comments
If we want to add some small comment we can use single-line comments. For morecomplicated explanations, we can use multi-line comments. The documentation commentsare used to prepare automatically generated documentation. This is generated with the
javadoc tool.
package com.zetcode;
/*This is Comments.javaAuthor: Jan BodnarZetCode 2013
*/
public class Comments {
// Program starts herepublic static void main(String[] args) {
System.out.println("This is Comments.java");}
4
http://docs.oracle.com/javase/tutorial/http://docs.oracle.com/javase/7/docs/api/http://docs.oracle.com/javase/specs/http://docs.oracle.com/javase/tutorial/http://docs.oracle.com/javase/7/docs/api/http://docs.oracle.com/javase/specs/7/27/2019 ZetCode Java tutorial.doc
5/681
}
Comments are ignored by the Java compiler.
/*This is Comments.java
/* Author: Jan Bodnar */ZetCode 2013
*/
Comments cannot be nested. The above code does not compile.
White space
White space in Java is used to separate tokens in the source file. It is also used to improvereadability of the source code.
int i = 0;
White spaces are required in some places. For example between the int keyword and the
variable name. In other places, white spaces are forbidden. They cannot be present in variableidentifiers or language keywords.
int a=1;int b = 2;int c = 3;
The amount of space put between tokens is irrelevant for the Java compiler.
Identifiers
Identifiers are names for variables, methods, classes or parameters. Identifiers can havealphanumerical characters, underscores and dollar signs ($). It is an error to begin a variablename with a number. White space in names is not permitted.
Identifiers are case sensitive. This means, that Name, name or NAME refer to three differentvariables. Identifiers also cannot match language keywords.
There are also conventions related to naming of identifiers. The names should be descriptive.We should not use cryptic names for our identifiers. If the name consists of multiple words,each subsequent word is capitalized.
String name23;int _col;short car_age;
These are valid Java identifiers.
String 23name;int %col;
short car age;
5
7/27/2019 ZetCode Java tutorial.doc
6/681
These are invalid Java identifiers.
The following program demonstrates that the variable names are case sensitive. Event thoughthe language permits this, it is not a recommended practice to do.
package com.zetcode;
public class CaseSensitiveIdentifiers {
public static void main(String[] args) {
String name = "Robert";String Name = "Julia";
System.out.println(name);System.out.println(Name);
}}
Name and name are two different identifiers. In Visual Basic, this would not be possible. Inthis language, variable names are not case sensitive.
$ java com.zetcode.CaseSensitiveIdentifiersRobertJulia
Literals
A literalis a textual representation of a particular value of a type. Literal types include
boolean, integer, floating point, string, null, or character. Technically, a literal will beassigned a value at compile time, while a variable will be assigned at runtime.
int age = 29;String nationality = "Hungarian";
Here we assign two literals to variables. Number 29 and string "Hungarian" are literals.
package com.zetcode;
public class Literals {
public static void main(String[] args) {
int age = 23;String name = "James";boolean sng = true;String job = null;double weight = 68.5;char c = 'J';
System.out.format("His name is %s%n", name);System.out.format("His is %d years old%n", age);
if (sng) {
System.out.println("He is single");} else {
6
7/27/2019 ZetCode Java tutorial.doc
7/681
System.out.println("He is in a relationship");
}
System.out.format("His job is %s%n", job);System.out.format("He weighs %f kilograms%n", weight);
System.out.format("His name begins with %c%n", c);}}
In the above example, we have several literal values. 23 is an integer literal. "James" is astring literal. The true is a boolean literal. The null is a literal that represents a missing
value. 68.5 is a floating point literal. 'J' is a character literal.
$ java com.zetcode.LiteralsHis name is JamesHis is 23 years oldHe is single
His job is nullHe weighs 68.500000 kilogramsHis name begins with J
This is the output of the program.
Operators
An operatoris a symbol used to perform an action on some value. Operators are used inexpressions to describe operations involving one or more operands.
+ - * / % ^ & | ! ~= += -= *= /= %= ^= ++ --== != < > &= >>=
7/27/2019 ZetCode Java tutorial.doc
8/681
int[] array = new int[5] { 1, 2, 3, 4, 5 };
The square brackets [] are used to denote an array type. They are also used to access ormodify array elements. The curly brackets {} are also used to initiate arrays. The curly
brackets are also used enclose the body of a method or a class.
int a, b, c;
The comma character separates variables in a single declaration.
Keywords
A keyword is a reserved word in Java language. Keywords are used to perform a specific taskin the computer program. For example, define variables, do repetitive tasks or perform logicaloperations.
Java is rich in keywords. Many of them will be explained in this tutorial.
abstract continue for new switchassert default goto packagesynchronizedboolean do if private thisbreak double implements protected throwbyte else import public throwscase enum instanceof return transientcatch extends int short trychar final interface static voidclass finally long strictfp volatileconst float native super while
In the following small program, we use several Java keywords.
package com.zetcode;
public class Keywords {
public static void main(String[] args) {
for (int i = 0; i
7/27/2019 ZetCode Java tutorial.doc
9/681
Class names begin with an uppercase letter
Method names begin with a lowercase letter
The public keyword precedes the static keyword when both are used
The parameter name of the main() method is called args
Constants are written in uppercase
Each subsequent word in an identifier name begins with a capital letter
In this part of the Java tutorial, we covered some basic lexis for the Java language.
Basics
In this part of the Java tutorial, we will cover basic programming concepts of the Javalanguage. We begin with some simple programs. We will work with variables, constants and
basic data types. We will read and write to the console. We will mention variableinterpolation.
We start with a very simple code example. The following code is put into Simple.java file.The naming is important here. A public class of a Java program must match the name of thefile.
package com.zetcode;
public class Simple {
public static void main(String[] args) {
System.out.println("This is Java");}
}
Java code is strictly organized from the very beginning. A file of a Java code may have oneor more classes, out of which only one can be declared public.
package com.zetcode;
Packages are used to organize Java classes into groups, which usually share similarfunctionality. Packages are similar to namespaces and modules in other programminglanguages. For a simple code example, a package declaration may be omitted. This will
create a so called default package. However, in this tutorial we will use a package for allexamples. Another important thing is that a directory structure must reflect the packagename. In our case the source file Simple.java with a package com.zetcode must be placed intoa directory named com/zetcode/. The package statement must be the first line in the source
file.
public class Simple {
...}
A class is a basic building block of a Java program. The public keyword gives unrestrictedaccess to this class. The above code is a class definition. The definition has a body that starts
9
7/27/2019 ZetCode Java tutorial.doc
10/681
with a left curly brace { and ends with a right curly brace }. Only one class can be declaredpublic in one source file. Also note the name of the class. Its name must match the file
name. The source file is called Simple.java and the class Simple. It is a convention that thenames of classes start with an uppercase letter.
public static void main(String[] args) {...
}
The main() is a method. A method is a piece of code created to do a specific job. Instead of
putting all code into one place, we divide it into pieces called methods. This bringsmodularity to our application. Each method has a body in which we place statements. The
body of a method is enclosed by curly brackets. The specific job for the main() method is tostart the application. It is the entry point to each console Java program. The method isdeclared to be static. This static method can be called without the need to create an instance
of the Java class. First we need to start the application and after that, we are able to create
instances of classes. The void keyword states that the method does not return a value.Finally, the public keyword makes the main() method available to the outer world without
restrictions. These topics will be later explained in more detail.
System.out.println("This is Java");
In the main() method, we put one statement. The statement prints the "This is Java" string tothe console. Each statement must be finished with a semicolon (;) character. This statement isa method call. We call the println() method of the System class. The class represents the
standard input, output, and error streams for console applications. We specify the fullyqualified name of the println() method.
$ pwd/home/janbodnar/programming/java/basics/simple$ javac com/zetcode/Simple.java
Java source code is placed into files with the .java extension. The javac tool is the Javacompiler. We compile the Java source into Java classes. Note the directory structure. Thestructure must match the Java package.
$ ls com/zetcode/Simple.class Simple.java Simple.java~
After we compile the source, we get a Java class file with the .class extension. It contains aJava bytecode which can be executed on the Java Virtual Machine (JVM). Simple.class is aJava program which can be executed with the java tool.
$ java com.zetcode.SimpleThis is Java
We execute the program with the java tool. The java tool launches a Java application. It doesthis by starting a Java runtime environment, loading a specified class, and invoking thatclass's main method. The parameter to the java tool is the fully qualified name of the Javaclass. Note that the .class extension is omitted.
10
7/27/2019 ZetCode Java tutorial.doc
11/681
Reading values
The second example will show, how to read a value from a console.
package com.zetcode;
import java.util.Scanner;
public class ReadLine {
public static void main(String[] args) {
System.out.print("Write your name:");
Scanner sc = new Scanner(System.in);String name = sc.nextLine();
System.out.println("Hello " + name);
}}
A prompt is shown on the terminal window. The user writes his name on the terminal and thevalue is read and printed back to the terminal.
import java.util.Scanner;
The Java standard library has a huge collection of classes available for programmers. Theyare organized inside packages. The Scanner class is one of them. When we import a class
with the import keyword, we can refer later to the class without the full package name.
Otherwise we must use the fully qualified name. The import allows a shorthand referring forclasses. This is different from some other languages. For instance in Python, the importkeyword imports objects into the namespace of a script. In Java, the import keyword only
saves typing by allowing to refer to types without specifying the full name.
System.out.print("Write your name:");
We print a message to the user. We use the print() method which does not start a new line.
The user then types his response next to the message.
Scanner sc = new Scanner(System.in);
A new instance of the Scanner class is created. New objects are created with the new
keyword. The constructor of the object follows the new keyword. We put one parameter to
the constructor of the Scanner object. It is the standard input stream. This way we are ready
to read from the terminal. The Scanner is a simple text scanner which can parse primitive
types and strings.
String name = sc.nextLine();
Objects have methods which perform certain tasks. The nextLine() method reads the next
line from the terminal. It returns the result in a String data type. The returned value is stored
in the name variable which we declare to be ofString type.
11
7/27/2019 ZetCode Java tutorial.doc
12/681
System.out.println("Hello " + name);
We print a message to the terminal. The message consists of two parts. The "Hello " stringand the name variable. We concatenate these two values into one string using the + operator.This operator can concatenate two or more strings.
$ java com.zetcode.ReadLineWrite your name:Jan BodnarHello Jan Bodnar
This is a sample execution of the second program.
Command line arguments
Java programs can receive command line arguments. They follow the name of the programwhen we run it.
package com.zetcode;
public class CommandLineArgs {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);}
}}
Command line arguments can be passed to the main() method.
public static void main(String[] args)
The main() method receives a string array of command line arguments. Arrays are
collections of data. An array is declared by a type followed by a pair of square brackets []. Sothe String[] args construct declares an array of strings. The args is an parameter to the
main() method. The method then can work with parameters which are passed to it.
for (String arg : args) {
System.out.println(arg);}
We go through the array of these arguments with a for loop and print them to the console.The for loop consists of cycles. In this case, the number of cycles equals to the number of
parameters in the array. In each cycle, a new element is passed to the arg variable from theargs array. The loop ends when all elements of the array were passed. The for statement has a
body enclosed by curly brackets {}. In this body, we place statements that we want to beexecuted in each cycle. In our case, we simply print the value of the arg variable to theterminal. Loops and arrays will be described in more detail later.
$ java com.zetcode.CommandLineArgs 1 2 3 4 51
12
7/27/2019 ZetCode Java tutorial.doc
13/681
2345
We provide four numbers as command line arguments and these are printed to the console.
When we launch programs from the command line, we specify the arguments right after thename of the program. In Integraged Development Environments (IDE) like Netbeans, wespecify these parameters in a dialog. In Netbeans, we rigth click on the project and selectProperties. From the Categories list, we select the Run option. In the Arguments edit control,we write our arguments.
Figure: Command line arguments
Variables
A variable is a place to store data. A variable has a name and a data type. A data typedetermines what values can be assigned to the variable. Integers, strings, boolean values etc.
Over the time of the program, variables can obtain various values of the same data type.Variables in Java are always initialized to the default value of their type before any referenceto the variable can be made.
package com.zetcode;
public class Variables {
public static void main(String[] args) {
String city = "New York";String name = "Paul"; int age = 34;
String nationality = "American";
System.out.println(city);System.out.println(name);System.out.println(age);System.out.println(nationality);
city = "London";System.out.println(city);
}}
In the above example, we work with four variables. Three of the variables are strings. The
age variable is an integer. The int keyword is used to declare an integer variable.
13
7/27/2019 ZetCode Java tutorial.doc
14/681
String city = "New York";
We declare a city variable of the string type and initialize it to the "New York" value.
String name = "Paul"; int age = 34;
We declare and initialize two variables. We can put two statements into one line. Since eachstatement is finished with a semicolon, the Java compiler knows that there are two statementsin one line. But for readability reasons, each statement should be on a separate line.
System.out.println(city);System.out.println(name);System.out.println(age);System.out.println(nationality);
We print the values of the variables to the terminal.
city = "London";System.out.println(city);
We assign a new value to the city variable and later print it.
$ java com.zetcode.VariablesNew YorkPaul34AmericanLondon
This is the output of the example.
Constants
Unlike variables, constants cannot change their initial values. Once initialized, they cannot bemodified. Constants are created with the final keyword.
package com.zetcode;
public class Constants {
public static void main(String[] args) {final int WIDTH = 100;final int HEIGHT= 150;int var = 40;
var = 50;
//WIDTH = 110;}
}
In this example, we declare two constants and one variable.
final int WIDTH = 100;
14
7/27/2019 ZetCode Java tutorial.doc
15/681
final int HEIGHT= 150;
We use the final keyword to inform the compiler that we declare a constant. It is a
convention to write constants in uppercase letters.
int var = 40;
var = 50;
We declare and initialize a variable. Later, we assign a new value to the variable. It is legal.
// WIDTH = 110;
Assigning new values to constants is not possible. If we uncomment this line, we will get acompilation error: "Uncompilable source code - cannot assign a value to final variableWIDTH".
String formatting
Building strings from variables is a very common task in programming. Java language hasthe System.format()method to format strings.
Some dynamic languages like Perl, PHP or Ruby support variable interpolation. Variableinterpolation is replacing variables with their values inside string literals. Java language doesnot allow this. It has string formatting insted.
package com.zetcode;
public class StringFormatting{
public static void main(String[] args){
int age = 34;String name = "William";
String output = String.format("%s is %d years old.", name, age);
System.out.println(output);}
}
In Java, strings are immutable. We cannot modify an existing string. We must create a newstring from existing strings and other types. In the code example, we create a new string. Wealso use values from two variables.
int age = 34;String name = "William";
Here we have two variables, one integer and one string.
String output = String.format("%s is %d years old.", name, age);
We use the format() method of the built-in String class. The %s and %d are control
characters which are later evaluated. The %s accepts string values, the %d integer values.
15
7/27/2019 ZetCode Java tutorial.doc
16/681
$ java com.zetcode.StringFormattingWilliam is 34 years old.
This is the output of the example.
This chapter covered some basics of the Java language.
Data types
In this part of the Java tutorial, we will talk about data types.
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients.Tools to work with various data types are essential part of a modern computer language. Adata type is a set of values and the allowable operations on those values.
Java programming language is a statically typed language. It means that every variable andevery expression has a type that is known at compile time. Java language is also a stronglytyped language, because types limit the values that a variable can hold or that an expressioncan produce, limit the operations supported on those values, and determine the meaning ofthe operations. Strong static typing helps detect errors at compile time. Variables indynamically typed languages like Ruby or Python can receive different data types over thetime. In Java, once a variable is declared to be of a certain data type, it cannot hold values ofother data types.
There are two fundamental data types in Java:primitive types and reference types. Primitivetypes are:
boolean
char
byte
short
int
long
float
double
There is a specific keyword for each of these types in Java. Primitive types are not objects inJava. Primitive data types cannot be stored in Java collections which work only with objects.They can be placed into arrays instead.
The reference types are:
class types
interface types
array types
There is also a special null type which represents a non-existing value.
In Ruby programming language, everything is an object. Even basic data types.
16
7/27/2019 ZetCode Java tutorial.doc
17/681
#!/usr/bin/ruby
4.times { puts "Ruby" }
This Ruby script prints four times "Ruby" string to the console. We call a times method onthe 4 number. This number is an object in Ruby.
Java has a different approach. It has primitive data types and wrapper classes. Wrapperclasses transform primitive types into objects. Wrapper classes are covered later in thischapter.
Boolean values
There is a duality built in our world. There is a Heaven and Earth, water and fire, jing andjang, man and woman, love and hatred. In Java the boolean data type is a primitive data type
having one of two values: true orfalse.
Happy parents are waiting a child to be born. They have chosen a name for both possibilities.If it is going to be a boy, they have chosen Robert. If it is going to be a girl, they have chosenVictoria.
package com.zetcode;
import java.util.Random;
public class BooleanType {
public static void main(String[] args) {
String name = "";Random r = new Random();boolean male = r.nextBoolean();
if (male == true) {
name = "Robert";}
if (male == false) {
name = "Victoria";
}
System.out.format("We will use name %s%n", name);
System.out.println(9 > 8);}
}
The program uses a random number generator to simulate our case.
Random r = new Random();boolean male = r.nextBoolean();
These two lines randomly choose a boolean value.
17
7/27/2019 ZetCode Java tutorial.doc
18/681
if (male == true) {
name = "Robert";}
If the boolean variable male equals to true, we set the name variable to "Robert". The if
keyword works with boolean values.
if (male == false) {
name = "Victoria";}
If the random generator chooses false than we set the name variable to "Victoria".
System.out.println(9 > 8);
Relational operators result in a boolean value. This line prints true to the console.
$ java com.zetcode.BooleanTypeWe will use name Roberttrue$ java com.zetcode.BooleanTypeWe will use name Victoriatrue$ java com.zetcode.BooleanTypeWe will use name Victoriatrue
Running the program several times.
Integers
Integers are a subset of the real numbers. They are written without a fraction or a decimalcomponent. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite.
In computer languages, integers are (usually) primitive data types. Computers can practicallywork only with a subset of integer values, because computers have finite capacity. Integersare used to count discrete entities. We can have 3, 4, 6 humans, but we cannot have 3.33humans. We can have 3.33 kilograms, 4.564 days, or 0.4532 kilomenters.
Type Size Range
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
char 16 bits 0 to 65,535
int 32 bits -2,147,483,648 to 2,147,483,647
long 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Table: Integer types in Java
These integer types may be used according to our needs. We can then use the byte type for a
variable that stores the number of children a woman gave birth to. The oldest verified person
18
7/27/2019 ZetCode Java tutorial.doc
19/681
died at 122, therefore we would probably choose at least the short type for the age variable.
This will save us some memory.
Integer literals may be expressed in decimal, hexadecimal, octal, or binary notations. If anumber has an ASCII letter L or l suffix, it is of type long. Otherwise it is of type int. The
capital letter L is preffered for specifying long numbers, since lowercase l can be easilyconfused with number 1.
int a = 34;byte b = 120;short c = 32000;long d = 45000;long e = 320000L;
We have five assignments. 34, 120, 32000 and 45000 are integer literals of type int. There
are no integer literals forbyte and short types. If the values fit into the destination type, the
compiler does not protest and performs a conversion automatically. Forlong numbers
smaller than Integer.MAX_VALUE, the L suffix is optional.
long x = 2147483648L;long y = 2147483649L;
Forlong numbers larger than Integer.MAX_VALUE, we must add the L suffix.
When we work with integers, we deal with discrete items. For instance, we can use integersto count apples.
package com.zetcode;
public class Apples {
public static void main(String[] args) {
int baskets = 16;int applesInBasket = 24;
int total = baskets * applesInBasket;
System.out.format("There are total of %d apples%n", total);}
}
In our program, we count the total amount of apples. We use the multiplication operation.
int baskets = 16;int applesInBasket = 24;
The number of baskets and the number of apples in each basket are integer values.
int total = baskets * applesInBasket;
Multiplying those values we get an integer too.
$ java com.zetcode.Apples
19
7/27/2019 ZetCode Java tutorial.doc
20/681
There are total of 384 apples
This is the output of the program.
Integers can be specified in four different notations in Java. Decimal, octal, hexadecimal and
binary. The binary notation was introduced in Java 7. Decimal numbers are used normally, aswe know them. Octal numbers are preceded with a 0 character and followed by octalnumbers. Hexadecimal numbers are preceded with 0x characters and followed byhexadecimal numbers. Binary numbers start with 0b and are followed by binary numbers.
package com.zetcode;
public class IntegerNotations {
public static void main(String[] args) {
int n1 = 31;
int n2 = 0x31;int n3 = 031;int n4 = 0b1001;
System.out.println(n1);System.out.println(n2);System.out.println(n3);System.out.println(n4);
}}
We have four integer variables. Each of the variables is assigned a value with a differentinteger notation.
int n1 = 31;int n2 = 0x31;int n3 = 031;int n4 = 0b1001;
The first is decimal, the second hexadecimal, the third octal and the fourth binary.
$ java com.zetcode.IntegerNotations314925
9
We see the output of the com.zetcode.IntegerNotations program.
Big numbers are difficult to read. If we have a number like 245342395423452, we find itdifficult to read it quickly. Outside computers, big numbers are separated by spaces orcommas. Since Java SE 1.7, it is possible to separate integers with an underscore.
The underscore cannot be used at the beginning or end of a number, adjacent to a decimalpoint in a floating point literal, and prior to an F or L suffix.
package com.zetcode;
20
7/27/2019 ZetCode Java tutorial.doc
21/681
public class UsingUnderscores {
public static void main(String[] args) {
long a = 23482345629L;long b = 23_482_345_629L;
System.out.println(a == b);}
}
This code sample demonstrates the usage of underscores in Java.
long a = 23482345629L;long b = 23_482_345_629L;
We have two identical long numbers. In the second one we separate every three digits in anumber. Comparing these two numbers we receive a boolean true. The L suffix tells the
compiler that we have a long number literal.
Java byte, short, int and long types are used do representfixed precision numbers. Which
means, that they can represent a limited amount of integers. The largest integer number that along type can represent is 9223372036854775807. If we deal with even larger numbers, wehave to use the java.math.BigInteger class. It is used to represet immutable arbitrary
precision integers. Arbitrary precision integers are only limited by the amount of computermemory available.
package com.zetcode;
import java.math.BigInteger;
public class VeryLargeIntegers {
public static void main(String[] args) {
System.out.println(Long.MAX_VALUE);
BigInteger b = new BigInteger("92233720368547758071");BigInteger c = new BigInteger("52498235605326345645");
BigInteger a = b.multiply(c);
System.out.println(a);}
}
With the help of the java.math.BigInteger class, we multiply two very large numbers.
System.out.println(Long.MAX_VALUE);
We print the largest integer value which can be represented by a long type.
BigInteger b = new BigInteger("92233720368547758071");BigInteger c = new BigInteger("52498235605326345645");
We define two BigInteger objects. They both hold larger values that a long type can hold.
21
7/27/2019 ZetCode Java tutorial.doc
22/681
BigInteger a = b.multiply(c);
With the multiply() method, we multiply the two numbers. Note that the BigInteger
numbers are immutable. The operation returns a new value which we assign to a newvariable.
System.out.println(a);
The computed integer is printed to the console.
$ java com.zetcode.VeryLargeIntegers92233720368547758074842107582663807707870321673775984450795
This is the example output.
Arithmetic overflowAn arithmetic overflow is a condition that occurs when a calculation produces a result that isgreater in magnitude than that which a given register or storage location can store orrepresent.
package com.zetcode;
public class Overflow {
public static void main(String[] args) {
byte a = 126;
System.out.println(a);a++;
System.out.println(a);a++;
System.out.println(a);a++;
System.out.println(a);}
}
In this example, we try to assign a value beyond the range of a data type. This leads to anarithmetic overflow.
$ java com.zetcode.Overflow126127-128-127
When an overflow occurs, the variable is reset to negative upper range value. In contrast,
Visual Basic programming language would throw an exception.
22
7/27/2019 ZetCode Java tutorial.doc
23/681
Floating point numbers
Real numbers measure continuous quantities, like weight, height, or speed. Floating pointnumbers represent an approximation of real numbers in computing. In Java we have two
primitive floating point types: float and double. The float is a single precision type which
store numbers in 32 bits. The double is a double precision type which store numbers in 64bits. These two types have fixed precision and cannot represent exactly all real numbers. Insituations where we have to work with precise numbers, we can use the BigDecimal class.
Floating point numbers with an F/f suffix are of type float, double numbers have D/d
suffix. The suffix fordouble numbers is optional.
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
package com.zetcode;
public class Sprinter {
public static void main(String[] args) {
float distance;float time;float speed;
distance = 0.1f;
time = 9.87f / 3600;
speed = distance / time;
System.out.format("The average speed of a sprinter is %f km/h%n",speed);
}}
In this example, it is necessary to use floating point values. The low precision of the floatdata type does not pose a problem in this case.
distance = 0.1f;
100m is 0.1km.
time = 9.87f / 3600;
9.87s is 9.87/60*60h.
speed = distance / time;
To get the speed, we divide the distance by the time.
$ java com.zetcode.SprinterThe average speed of a sprinter is 36.474163 km/h
23
7/27/2019 ZetCode Java tutorial.doc
24/681
This is the output of the com.zetcode.Sprinter program. A small rounding error in the numberdoes not affect our understanding of the sprinter's speed.
The float and double types are inexact.
package com.zetcode;
public class FloatingInPrecision {
public static void main(String[] args) {
double a = 0.1 + 0.1 + 0.1;double b = 0.3;
System.out.println(a);System.out.println(b);
System.out.println(a == b);
}}
The code example illustrates the inexact nature of the floating point values.
double a = 0.1 + 0.1 + 0.1;double b = 0.3;
We define two double values. The D/d suffix is optional. At first sight, they should be equal.
System.out.println(a);System.out.println(b);
Printing them will show a very small difference.
System.out.println(a == b);
This line will return false.
$ java com.zetcode.FloatingInPrecision0.300000000000000040.3false
There is a small margin error. Therefore, the comparison operator returns a boolean false.
When we work with money, currency, and generally in business applications, we need towork with precise numbers. The rounding errors of the basic floating point types are notacceptable.
package com.zetcode;
public class CountingMoney {
public static void main(String[] args) {
float c = 1.46f;float sum = 0f;
24
7/27/2019 ZetCode Java tutorial.doc
25/681
for (int i=0; i
7/27/2019 ZetCode Java tutorial.doc
26/681
}
The BigDecimal number is immutable, therefore a new object is always assigned to the sum
variable in every loop.
$ java com.zetcode.CountingMoney2146000.00
In this example, we get the precise value.
Java supports the scientific syntax of the floating point values. Also known as exponentialnotation, it is a way of writing numbers too large or small to be conveniently written instandard decimal notation.
package com.zetcode;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class ScientificNotation {
public static void main(String[] args) {
double n = 1.235E10;DecimalFormat dec = new DecimalFormat("#.00");
System.out.println(dec.format(n));
BigDecimal bd = new BigDecimal("1.212e-19");
System.out.println(bd.toEngineeringString());System.out.println(bd.toPlainString());
}}
We define two floating point values using the scientific notation.
double n = 1.235E10;
This is a floating point value of a double type, written in scientific notation.
DecimalFormat dec = new DecimalFormat("#.00");
System.out.println(dec.format(n));
We use the DecimalFormat class to arrange ourdouble value into standard decimal format.
BigDecimal bd = new BigDecimal("1.212e-19");
System.out.println(bd.toEngineeringString());System.out.println(bd.toPlainString());
The BigDecimal class takes a floating poing value in a scientific notation as a parameter. We
use two methods of the class to print the value in the engineering and plain strings.
26
7/27/2019 ZetCode Java tutorial.doc
27/681
$ java com.zetcode.ScientificNotation12350000000.00121.2E-210.0000000000000000001212
This is the example output.
Enumerations
Enumerated type (also called enumeration or enum) is a data type consisting of a set ofnamed values. A variable that has been declared as having an enumerated type can beassigned any of the enumerators as a value. Enumerations make the code more readable.Enumerations are useful when we deal with variables that can only take one out of a small setof possible values.
package com.zetcode;
public class Enumerations {
enum Days {
MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}
public static void main(String[] args) {
Days day = Days.MONDAY;
if (day == Days.MONDAY) {
System.out.println("It is Monday");}
System.out.println(day);
for (Days d : Days.values()) {
System.out.println(d);}
}}
In our code example, we create an enumeration for week days.
enum Days {
MONDAY,TUESDAY,WEDNESDAY,
THURSDAY,FRIDAY,SATURDAY,
27
7/27/2019 ZetCode Java tutorial.doc
28/681
SUNDAY}
An enumeration representing the days of a week is created with a enum keyword. Items of an
enumeration are constants. By convention, constants are written in uppercase letters.
Days day = Days.MONDAY;
We have a variable called day which is of enumerated type Days. It is initialized to Monday.
if (day == Days.MONDAY) {
System.out.println("It is Monday");}
This code is more readable than if comparing a day variable to some number.
System.out.println(day);
This line prints Monday to the console.
for (Days d : Days.values()) {
System.out.println(d);}
This loop prints all days to the console. The static values() method returns an array
containing the constants of this enum type, in the order they are declared. This method maybe used to iterate over the constants with the enhanced for statement. The enhanced for goes
through the array, element by element, and prints them to the terminal.
It is MondayMONDAYMONDAYTUESDAYWEDNESDAYTHURSDAYFRIDAYSATURDAYSUNDAY
This is the example output.
Strings and chars
A String is a data type representing textual data in computer programs. A string in Java is a
sequence of characters. A char is a single character. Strings are enclosed by double quotes.
Since strings are very important in every programming language, we will dedicate a wholechapter to them. Here we only drop a small example.
package com.zetcode;
public class StringsChars {
28
7/27/2019 ZetCode Java tutorial.doc
29/681
public static void main(String[] args) {
String word = "ZetCode";
char c = word.charAt(0);
char d = word.charAt(3);
System.out.println(c);System.out.println(d);
}}
The program prints Z character to the terminal.
String word = "ZetCode";
Here we create a string variable and assign it "ZetCode" value.
char c = word.charAt(0);
The charAt() method returns the char value at the specified index. The first char value of
the sequence is at index 0, the next at index 1, and so on.
$ java com.zetcode.StringsCharsZC
The program prints the first and the fourth character of the "ZetCode" string to the console.
Arrays
Array is a complex data type which handles a collection of elements. Each of the elementscan be accessed by an index. All the elements of an array must be of the same data type.
We dedicate a whole chapter to arrays; here we show only a small example.
package com.zetcode;
public class ArraysExample {
public static void main(String[] args) {
int[] numbers = new int[5];
numbers[0] = 3;numbers[1] = 2;numbers[2] = 1;numbers[3] = 5;numbers[4] = 6;
int len = numbers.length;
for (int i = 0; i < len; i++) {
System.out.println(numbers[i]);
29
7/27/2019 ZetCode Java tutorial.doc
30/681
}}
}
In this example, we declare an array, fill it with data and then print the contents of the arrayto the console.
int[] numbers = new int[5];
We create an integer array which can store up to 5 integers. So we have an array of fiveelements, with indexes 0..4.
numbers[0] = 3;numbers[1] = 2;numbers[2] = 1;numbers[3] = 5;numbers[4] = 6;
Here we assign values to the created array. We can access the elements of an array by thearray access notation. It consists of the array name followed by square brackets. Inside the
brackets we specify the index to the element that we want.
int len = numbers.length;
Each array has a length property which returns the number of elements in the array.
for (int i = 0; i < len; i++) {
System.out.println(numbers[i]);
}
We traverse the array and print the data to the console.
$ java com.zetcode.ArraysExample32156
This is the output of the com.zetcode.ArraysExample program.
In this part of the Java tutorial, we covered data types in Java.
Data types II
In this part of the Java tutorial, we will continue covering data types of Java.
Wrapper classes
Wrapper classes are object representations of primitive data types. Wrapper classes are usedto represent primitive values when an Object is required. For example, Java collections only
30
7/27/2019 ZetCode Java tutorial.doc
31/681
work with objects. They cannot take primitive types. Wrapper classes also include someuseful methods. For example, for doing data type conversions. Placing primitive types intowrapper classes is called boxing. The reverse process is called unboxing.
As a general rule, we use wrapper classes when we have some reason for it. Otherwise, we
use primitive types. Wrapper classes are immutable. Once they are created, they cannot bechanged. Primitive types are faster than boxed types. In scientific computing and other largescale number processing, wrapper classes may cause significant performance hit.
Primitive type Wrapper class Constructor arguments
byte Byte byte or String
short Short short or String
int Integer int or String
long Long long or String
float Float float, double or String
double Double double or Stringchar Character char
boolean Boolean boolean or String
Table: Primitive types and their wrapper class equivalentes
The Integer class wraps a value of the primitive type int in an object. It contains constants
and methods useful when dealing with an int.
package com.zetcode;
public class IntegerWrapper {
public static void main(String[] args) {
int a = 55;Integer b = new Integer(a);
int c = b.intValue();float d = b.floatValue();
String bin = Integer.toBinaryString(a);String hex = Integer.toHexString(a);String oct = Integer.toOctalString(a);
System.out.println(a);System.out.println(b);System.out.println(c);System.out.println(d);
System.out.println(bin);System.out.println(hex);System.out.println(oct);
}}
This example works with the Integer wrapper class.
int a = 55;
31
7/27/2019 ZetCode Java tutorial.doc
32/681
This line creates an integer primitive data type.
Integer b = new Integer(a);
An Integer wrapper class is created from the primitive int type.
int c = b.intValue();float d = b.floatValue();
The intValue() method converts the Integer to int. Likewise, the floatValue() returns a
float data type.
String bin = Integer.toBinaryString(a);String hex = Integer.toHexString(a);String oct = Integer.toOctalString(a);
These three methods return a binary, hexadecimal and octal representations of the integer.
$ java com.zetcode.IntegerWrapper55555555.01101113767
This is the program output.
Collections are powerful tools for working with groups of objects. Primitive data typescannot be placed into Java collections. After we box the primitive values, we can put theminto collections.
package com.zetcode;
import java.util.ArrayList;
public class Numbers {
public static void main(String[] args) {
ArrayList ls = new ArrayList();ls.add(new Integer(1342341));ls.add(new Float(34.56));ls.add(new Double(235.242));ls.add(new Byte("102"));ls.add(new Short("1245"));
for (Number n : ls) {
System.out.println(n.getClass());System.out.println(n);
}}
}
32
7/27/2019 ZetCode Java tutorial.doc
33/681
In the example, we put various numbers into an ArrayList. An ArrayList is a dynamic,
resizable array.
ArrayList ls = new ArrayList();
An ArrayList instance is created. In angle brackets we specify the type that the containerwill hold. The Number is an abstract base class for all five numeric primitive types in Java.
ls.add(new Integer(1342341));ls.add(new Float(34.56));ls.add(new Double(235.242));ls.add(new Byte("102"));ls.add(new Short("1245"));
We add five wrapper classes to the container.
for (Number n : ls) {
System.out.println(n.getClass());System.out.println(n);
}
We iterate through the container and print the class name and its value of each of theelements.
$ java com.zetcode.Numbersclass java.lang.Integer1342341class java.lang.Float
34.56class java.lang.Double235.242class java.lang.Byte102class java.lang.Short1245
The com.zetcode.Numbers program gives this output.
Boxing
Converting from primitive types to object types is called boxing. Unboxing is the oppositeoperation. It is converting of object types back into primitive types.
package com.zetcode;
public class BoxingUnboxing {
public static void main(String[] args) {
long a = 124235L;
Long b = new Long(a);
long c = b.longValue();System.out.println(c);
33
7/27/2019 ZetCode Java tutorial.doc
34/681
}}
In the code example, we box a long value into a Long object and vice versa.
Long b = new Long(a);
This line performs boxing.
long c = b.longValue();
In this line we do unboxing.
Autoboxing
Java SE 5 introduced autoboxing. Autoboxing is automatic conversion between primitive
types and their corresponding object wrapper classes. Autoboxing makes the programmingeasier. The programmer does not need to do the conversions manually.
Automatic boxing and unboxing is performed when one value is primitive type and other iswrapper class in:
assignments
passing parameters to methods
returning values from methods
comparison operations
arithmetic operations
Integer i = new Integer(50);
if (i < 100) {...
}
Inside the square brackets of the if expression, an Integer is compared with an int. The
Integer object is transformed into the primitive int type and compared with the 100 value.
Automatic unboxing is done.
package com.zetcode;
public class Autoboxing {
private static int cube(int x) {
return x * x * x;}
public static void main(String[] args) {
Integer i = 10;int j = i;
System.out.println(i);System.out.println(j);
34
7/27/2019 ZetCode Java tutorial.doc
35/681
Integer a = cube(i);System.out.println(a);
}}
Automatic boxing and automatic unboxing is demonstrated in this code example.
Integer i = 10;
The Java compiler performs automatic boxing in this code line. An int value is boxed into
the Integer type.
int j = i;
Here an automatic unboxing takes place.
Integer a = cube(i);
When we pass an Integer to the cube() method, automatic unboxing is done. When we
return the computed value, automatic boxing is perfomed, because an int is transformed
back to the Integer.
Java language does not support operator overloading. When we apply arithmetic operationson wrapper classes, automatic boxing is done by the compiler.
package com.zetcode;
public class Autoboxing2 {
public static void main(String[] args) {
Integer a = new Integer(5);Integer b = new Integer(7);
Integer add = a + b;Integer mul = a * b;
System.out.println(add);System.out.println(mul);
}
}
We have two Integer values. We perform addition and multiplication operations on these
two values.
Integer add = a + b;Integer mul = a * b;
Unlike languages like Ruby, C#, Python, D or C++, Java does not have operator overloadingimplemented. In these two lines, the compiler calls the intValue() methods and converts the
wrapper classes to ints and later wraps the outcome back to an Integer by calling the
valueOf() method.
35
7/27/2019 ZetCode Java tutorial.doc
36/681
Autoboxing and object interning
Object intering is storing only one copy of each distinct object. The object must be
immutable. The distinct objects are stored in an intern pool. In Java, when primitive valuesare boxed into a wrapper object, certain values (any boolean, any byte, any char from 0 to
127, and any short or int between -128 and 127) are interned, and any two boxingconversions of one of these values are guaranteed to result in the same object. According tothe Java language specification, these are minimal ranges. So the behaviour isimplementation dependent. Object intering saves time and space. Objects obtained fromliterals, autoboxing and Integer.valueOf() are interned objects while those constructed withnew operator are always distinct objects.
The object intering has some important consequences when comparing wrapper classes. The== operator compares reference identity of objects while the equals() method compares
values.
package com.zetcode;
public class Autoboxing3 {
public static void main(String[] args) {
Integer a = 5; // new Integer(5);Integer b = 5; // new Integer(5);
System.out.println(a == b);System.out.println(a.equals(b));System.out.println(a.compareTo(b));
Integer c = 155;Integer d = 155;
System.out.println(c == d);System.out.println(c.equals(d));System.out.println(c.compareTo(d));
}}
The example compares some Integer objects.
Integer a = 5; // new Integer(5);
Integer b = 5; // new Integer(5);
Two integers are boxed into Integer wrapper classes.
System.out.println(a == b);System.out.println(a.equals(b));System.out.println(a.compareTo(b));
Three different ways are used to compare the values. The == operator compares the referenceidentity of two boxed types. Because of the object interning, the operation results in true. Ifwe used the new operator, two distinct objects would be created and the == operator would
return false. The equals() method compares the two Integer objects numerically. It returnsa boolean true or false. (true in our case.) Finally, the compareTo()method also compares
36
7/27/2019 ZetCode Java tutorial.doc
37/681
the two objects numerically. It returns the value 0 if this Integer is equal to the argumentInteger; a value less than 0 if this Integer is numerically less than the argument Integer; and avalue greater than 0 if this Integer is numerically greater than the argument Integer.
Integer c = 155;
Integer d = 155;
We have another two boxed types. However, these values are greater than the maximumvalue interned (127), therefore two distinct objects are created. This time the == operatoryields false.
$ java com.zetcode.Autoboxing3truetrue0falsetrue
0
Output of the com.zetcode.Autoboxing3 program.
The null type
Java has a special null type. The type has no name. As a consequence, it is impossible to
declare a variable of the null type or to cast to the null type. The null represents a null
reference, one that does not refer to any object. The null is the default value of reference-
type variables. Primitive types cannot be assigned a null literal.
In different contexts, the null means an absense of an object, an unknow value, or anuninitialized state.
package com.zetcode;
import java.util.Random;
public class NullType {
private static String getName() {
Random r = new Random();
boolean n = r.nextBoolean();if (n == true) {
return "John";
} else {
return null;}
}
public static void main(String[] args) {
String name = getName();System.out.println(name);
37
7/27/2019 ZetCode Java tutorial.doc
38/681
System.out.println(null == null);
if ("John".equals(name)) {
System.out.println("His name is John");
}}}
We work with the null value in the program.
private static String getName() {
Random r = new Random();boolean n = r.nextBoolean();
if (n == true) {
return "John";
} else {
return null;}
}
In the getName() method we simulate the situation that a method can sometimes return a nullvalue.
System.out.println(null == null);
We compare a two null values. The expression returns true.
if ("John".equals(name)) {
System.out.println("His name is John");}
We compare the name variable to the "John" string. Notice that we call the equals() method
on the "John" string. This is because if the name variable equals to null, calling the methodwould lead to NullPointerException .
$ java com.zetcode.NullTypenulltrue$ java com.zetcode.NullTypenulltrue$ java com.zetcode.NullTypeJohntrueHis name is John
We execute the program three times.
38
7/27/2019 ZetCode Java tutorial.doc
39/681
Default values
Uninitialized fields are given default values by the compiler. Final fields and local variablesmust be initialized by developers.
The following table shows the default values for different types.
Data type Default value
byte 0
char '\u0000'
short 0
int 0
long 0L
float 0f
double 0d
Object null
boolean false
Table: Default values for uninitialized instance variables
The next example will print the default values of the uninitialized instance variables.
package com.zetcode;
public class DefaultValues {
static byte b;
static char c;static short s;static int i;static float f;static double d;static String str;static Object o;
public static void main(String[] args) {
System.out.println(b);System.out.println(c);System.out.println(s);
System.out.println(i);System.out.println(f);System.out.println(d);System.out.println(str);System.out.println(o);
}}
In the example, we declare eight member fields. They are not initialized. The compiler willset a default value for each of the fields.
static byte b;static char c;static short s;static int i;
39
7/27/2019 ZetCode Java tutorial.doc
40/681
...
The fields are declared static, because they are accessed from a static main() method.
$ java com.zetcode.DefaultValues0
000.00.0nullnull
This is the output of the com.zetcode.DefaultValues program.
Type conversions
We often work with multiple data types at once. Converting one data type to another one is acommon job in programming. The term type conversion refers to changing of an entity of onedata type into another. In this section, we will deal with conversions of primitive data types.Reference type conversions will be mentioned in a later chapter. The rules for conversionsare complex; they are specified in chapter 5 of the Java language specification.
There are two types of conversions: implicit and explicit. Implicit type conversion, alsoknown as coercion, is an automatic type conversion by the compiler. In explicit conversionthe programmer directly specifies the converting type inside a pair of round brackets. Explicitconversion is called type casting.
Conversions happen in different contexts: assignments, expressions or method invocations.
int x = 456;long y = 34523L;float z = 3.455f;double w = 6354.3425d;
In these four assignments, no conversion takes place. Each of the variables is assigned aliteral of the expected type.
int x = 345;long y = x;
float m = 22.3354f;double n = m;
In this code two conversions are performed by Java compiler implicitly. Assigning a variableof a smaller type to a variable of a larger type is legal. The conversion is considered safe, asno precision is lost. This kind of conversion is called implicit widening conversion.
long x = 345;int y = (int) x;
double m = 22.3354d;float n = (float) m;
40
7/27/2019 ZetCode Java tutorial.doc
41/681
Assigning variables of larger type to smaller type is not legal in Java. Even if the valuesthemselves fit into the range of the smaller type. In this case it is possible to loose precision.To allow such assignments, we have to use the type casting operation. This way the
programmer says that he is doing it on purpose and that he is aware of the fact that theremight be some precision lost. This kind of conversion is called explicit narrowing
conversion.
byte a = 123;short b = 23532;
In this case, we deal with a specific type of assignment conversion. 123 and 23532 are integerliterals, the a, b variables are ofbyte and short type. It is possible to use the casting
operation, but it is not required. The literals can be represented in their variables on the leftside of the assignment. We deal with implicit narrowing conversion.
private static byte calc(byte x) {
...}byte b = calc((byte) 5);
The above rule only applies to assignments. When we pass an integer literal to a method thatexpects a byte, we have to perform the casting operation.
Numeric promotions
Numeric promotion is a specific type of an implicit type conversion. It takes place inarithmetic expressions. Numeric promotions are used to convert the operands of a numeric
operator to a common type so that an operation can be performed.
int x = 3;double y = 2.5;double z = x + y;
In the third line we have an addition expression. The x operand is int, the y operand is
double. The compiler converts the integer to double value and adds the two numbers. The
result is a double. It is a case of implicit widening primitive conversion.
byte a = 120;a = a + 1; // compilation error
This code leads to a compile time error. In the right side of the second line, we have a bytevariable a and an integer literal 1. The variable is converted to integer and the values areadded. The result is an integer. Later, the compiler tries to assign the value to the a variable.Assigning larger types to smaller types is not possible without an explicit cast operator.Therefore we receive a compile time error.
byte a = 120;a = (byte) (a + 1);
This code does compile. Note the usage of round brackets for the a + 1 expression. The
(byte) casting operator has a higher precedence than the addition operator. If we want toapply the casting on the whole expression, we have to use round brackets.
41
7/27/2019 ZetCode Java tutorial.doc
42/681
byte a = 120;a += 5;
Compound operators perform implicit conversions automatically.
short r = 21;short s = (short) -r;
Applying the +/- unary operator on a variable a unary numberic promotion is performed. Theshort type is promoted to int type. Therefore we must use the casting operator for the
assignment to pass.
byte u = 100;byte v = u++;
In case of the unary increment ++, decrement -- operators, no conversion is done. The castingis not necessary.
Boxing, unboxing conversions
Boxing conversion converts expressions of primitive type to corresponding expressions ofwrapper type. Unboxing conversion converts expressions of wrapper type to correspondingexpressions of primitive type. Conversions from boolean to Boolean or from byte to Byte areexamples of boxing conversions. The reverse conversions, e.g. from Boolean to boolean orfrom Byte to byte are examples of unboxing conversions.
Byte b = 124;byte c = b;
In the first code line, automatic boxing conversion is performed by the Java compiler. In thesecond line, an unboxing conversion is done.
private static String checkAge(Short age) {...}String r = checkAge((short) 5);
Here we have boxing conversion in the context of a method invocation. We pass a short
type to the method which expects a Short wrapper type. The value is boxed.
Boolean gameOver = new Boolean("true");if (gameOver) {
System.out.println("The game is over");}
This is an example of an unboxing conversion. Inside the if expression, the booleanValue()
method is called. The method returns the value of a Boolean object as a boolean primitive.
String conversions
Performing string conversions between numbers and strings is very common inprogramming. The casting operation is not allowed, because the strings and primitive types
42
7/27/2019 ZetCode Java tutorial.doc
43/681
are fundamentally different types. There are several methods for doing string conversion.There is also an automatic string conversion for the + operator.
More about string conversions will be covered in the Strings chapter of this tutorial.
String s = (String) 15; // compilation errorint i = (int) "25"; // compilation error
It is not possible to cast between numbers and strings. Instead, we have various methods fordoing conversion between numbers and strings.
short age = Short.parseShort("35");int salary = Integer.parseInt("2400");float height = Float.parseFloat("172.34");double weight = Double.parseDouble("55.6");
The parse methods of the wrapper classes convert strings to primitive types.
Short age = Short.valueOf("35");Integer salary = Integer.valueOf("2400");Float height = Float.valueOf("172.34");Double weight = Double.valueOf("55.6");
The valueOf() method returns the wrapper classes from primitive types.
int age = 17;double weight = 55.3;String v1 = String.valueOf(age);String v2 = String.valueOf(weight);
The String class has a valueOf() method for converting various types to strings.
Automatic string conversions take place when using the + operator and one operator is astring, the other operator is not a string. The non-string operand to the + is converted to astring.
package com.zetcode;
public class AutomaticStringConversion {
public static void main(String[] args) {
String name = "Jane";short age = 17;
System.out.println(name + " is " + age + " years old.\n");}
}
In the example, we have a String data type and a short data type. The two types are
concatenated using the + operator into a sentence.
System.out.println(name + " is " + age + " years old.");
In the expression, the age variable is converted to a String type.
43
7/27/2019 ZetCode Java tutorial.doc
44/681
$ java com.zetcode.AutomaticStringConversionJane is 17 years old.
This is the example output.
In this part of the Java tutorial, we covered data types and their conversions.
Strings
In this part of the Java tutorial, we will work with string data in more detail.
Strings are very important data types in computer languages. That is why we dedicate awhole chapter to working with strings in Java.
In Java, a string is a sequence of unicode characters. Strings are objects. There are two basic
classes for working with strings:
String
StringBuilder
The String is an immutable sequence of characters. The StringBuilder is a mutable
sequence of characters. (There is also a StringBuffer class which can be used by multiple
threads. If we are not dealing with threads, we use the StringBuilder.)
Astring literala series of characters in the source code that is enclosed in double quotes. Forexample, "Java" is a string literal. Whenever Java compiler encounters a string literal in the
code, it creates a String object with its value.
String lang = "Java"; // same as String lang = new String("Java");
String literals are used by many programming languages. It is an established convention andit also saves typing.
Initializing strings
There are multiple ways of creating strings, both immutable and mutable. We will show afew of them.
package com.zetcode;
public class StringInit {
public static void main(String[] args) {
char[] cdb = {'M', 'y', 'S', 'q', 'l'};
String lang = "Java";String ide = new String("NetBeans");String db = new String(cdb);
System.out.println(lang);System.out.println(ide);
44
7/27/2019 ZetCode Java tutorial.doc
45/681
System.out.println(db);
StringBuilder sb1 = new StringBuilder(lang);StringBuilder sb2 = new StringBuilder();sb2.append("Fields");sb2.append(" of ");
sb2.append("glory");System.out.println(sb1);System.out.println(sb2);
}}
The example shows a few ways of creating String and StringBuilder objects.
String lang = "Java";
The most common way is to create a string object from a string literal.
String ide = new String("NetBeans");
In this line, we create a string using usual way of building objects with the new keyword.
String db = new String(cdb);
Here we create a string object from an array of characters.
StringBuilder sb1 = new StringBuilder(lang);
A StringBuilder object is created from a String.
StringBuilder sb2 = new StringBuilder();sb2.append("Fields");sb2.append(" of ");sb2.append("glory");
We create an empty StringBuilder object. We append three strings into the object.
$ java com.zetcode.StringInitJavaNetBeans
MySqlJavaFields of glory
Running the example gives this result.
Strings are objects
Strings are objects; they are not primitive data types. Strings are instances of the String or
StringBuilder class. Since they are objects, they have multiple methods available for doing
various work.
package com.zetcode;
45
7/27/2019 ZetCode Java tutorial.doc
46/681
public class StringObjects {
public static void main(String[] args) {
String lang = "Java";
String bclass = lang.getClass().toString();System.out.println(bclass);
String sup = lang.getClass().getSuperclass().toString();System.out.println(sup);
if (lang.isEmpty()) {
System.out.println("The string is empty");} else {
System.out.println("The string is not empty");
}int l = lang.length();System.out.println("The string has " + l + " characters");
}
}
In this program, we demonstrate that strings are objects. Objects must have a class name, aparent class and they must also have some methods that we can call.
String lang = "Java";
An object ofString type is created.
String bclass = lang.getClass().toString();
We determine the class name of the object to which the lang variable refers.
String sup = lang.getClass().getSuperclass().toString();
A parent class of our object is received. All objects have at least one parent the Object.
if (lang.isEmpty()) {
System.out.println("The string is empty");} else {
System.out.println("The string is not empty");}
Objects have various methods. One of the useful string methods is the isEmpty() method,
which determines whether the string is empty.
int l = lang.length();
The length() method returns the size of the string.
46
7/27/2019 ZetCode Java tutorial.doc
47/681
$ java com.zetcode.StringObjectsclass java.lang.Stringclass java.lang.ObjectThe string is not emptyThe string has 4 characters
Our string object is an instance of the String class. It has the Object parent class. The objectis not empty and it contains four characters.
Mutable & immutable strings
The String is a sequence of immutable characters, while the StringBuilder is a sequence
of mutable characters. The next example will show the difference.
package com.zetcode;
public class MutableImmutable {
public static void main(String[] args) {
String name = "Jane";String name2 = name.replace('J', 'K');String name3 = name2.replace('n', 't');
System.out.println(name);System.out.println(name3);
StringBuilder sb = new StringBuilder("Jane");System.out.println(sb);
sb.setCharAt(0, 'K');sb.setCharAt(2, 't');
System.out.println(sb);
}}
Both objects have methods for replacing characters in a string.
String name = "Jane";String name2 = name.replace('J', 'K');String name3 = name2.replace('n', 't');
Calling a replace() method on a String results in returning a new modified string. The
original string is not changed.
sb.setCharAt(0, 'K');sb.setCharAt(2, 't');
The setCharAt()method of a StringBuilder will replace a character at the given index
with a new character. The original string is modified.
$ java com.zetcode.MutableImmutableJane
KateJane
47
7/27/2019 ZetCode Java tutorial.doc
48/681
Kate
This is the output of the com.zetcode.MutableImmutable example.
Concatenating strings
Immutable strings can be added using the + operator or the concat() method. They will
form a new string which is a chain of all concatenated strings. Mutable strings have theappend() method which builds a string from any number of other strings.
package com.zetcode;
public class ConcatenateStrings {
public static void main(String[] args) {
System.out.println("Return" + " of " + "the king.");
System.out.println("Return".concat(" of ").concat("the king."));
StringBuilder sb = new StringBuilder();sb.append("Return");sb.append(" of ");sb.append("the king.");
System.out.println(sb);
}}
The example creates three sentences by adding strings.
System.out.println("Return" + " of " + "the king.");
A new string is formed by using the + operator.
System.out.println("Return".concat(" of ").concat("the king."));
The concat() method returns a string that represents the concatenation of this object's
characters followed by the string argument's characters.
StringBuilder sb = new StringBuilder();sb.append("Return");
sb.append(" of ");sb.append("the king.");
A mutable object of the StringBuilder type is created by calling the append() method
three times.
$ java com.zetcode.ConcatenateStringsReturn of the king.Return of the king.Return of the king.
This is the example output.
48
7/27/2019 ZetCode Java tutorial.doc
49/681
Using quotes
What if we wanted to display quotes, for example in a direct speech? In such a case, the innerquotes must be escaped.
package com.zetcode;
public class Quotes {
public static void main(String[] args) {
System.out.println("There are may stars");System.out.println("He said: \"Which one are you looking at?\"");
}}
We use the (\) character to escape additional quotes.
$ java com.zetcode.QuotesThere are may starsHe said: "Which one are you looking at?"
Here we see the output of the com.zetcode.Quotes program.
Multiline strings
It is not possible to create a multiline string in Java. In order to span a string on multiplelines, we need to do a concatenation operation.
package com.zetcode;
public class MultilineString {
static String lyrics = "I cheated myself\n" +"like I knew I would\n" +"I told ya, I was trouble\n" +"you know that I'm no good";
public static void main(String[] args) {
System.out.println(lyrics);}
}
One strophe spans four lines. The four strings are concatenated with the + operator.
$ java com.zetcode.MultilineStringI cheated myselflike I knew I wouldI told ya, I was troubleyou know that I'm no good
We see the output of the com.zetcode.MultilineString example.
49
7/27/2019 ZetCode Java tutorial.doc
50/681
String elements
A string is a sequence of characters. A character is a basic element of a string. The followingtwo examples will show some methods that work with characters of a string.
package com.zetcode;
public class StringElements {
public static void main(String[] args) {
char[] crs = {'Z', 'e', 't', 'C', 'o', 'd', 'e' };String s = new String(crs);
char c1 = s.charAt(0);char c2 = s.charAt(s.length()-1);
System.out.println(c1);
System.out.println(c2);
int i1 = s.indexOf('e');int i2 = s.lastIndexOf('e');
System.out.println("The first index of character e is " + i1);System.out.println("The last index of character e is " + i2);
System.out.println(s.contains("t"));System.out.println(s.contains("f"));
char[] elements = s.toCharArray();
for (char el : elements) {
System.out.println(el);}
}}
In the first example, we will work with an immutable string.
char[] crs = {'Z', 'e', 't', 'C', 'o', 'd', 'e' };String s = new String(crs);
A new immutable string is formed from an array of characters.
char c1 = s.charAt(0);char c2 = s.charAt(s.length()-1);
With the charAt() method, we get the first and the last char value of the string.
int i1 = s.indexOf('e');int i2 = s.lastIndexOf('e');
With the above methods, we get the first and the last occurence of the character 'e'.
System.out.println(s.contains("t"));
50
7/27/2019 ZetCode Java tutorial.doc
51/681
With the contains() method, we check if the string contains the 't' character. The method
returns a boolean value.
char[] elements = s.toCharArray();
for (char el : elements) {
System.out.println(el);}
The toCharArray()method creates a character array from the string. We go through the
array and print each of the characters.
$ java com.zetcode.StringElementsZeThe first index of character e is 1The last index of character e is 6truefalseZetCode
This is the example output.
In the second example, we will work with the elements of a StringBuilder class.
package com.zetcode;
public class StringBuilderElements {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Misty mountains");System.out.println(sb);
sb.deleteCharAt(sb.length()-1);
System.out.println(sb);
sb.append('s');System.out.println(sb);
sb.insert(0, 'T');sb.insert(1, 'h');sb.insert(2, 'e');sb.insert(3, ' ');System.out.println(sb);
sb.setCharAt(4, 'm');System.out.println(sb);
}}
51
7/27/2019 ZetCode Java tutorial.doc
52/681
A mutable string is formed. We modify the contents of the string by deleting, appending,inserting and replacing characters.
sb.deleteCharAt(sb.length()-1);
This line deletes the last character.
sb.append('s');
The deleted character is appended back to the string.
sb.insert(0, 'T');sb.insert(1, 'h');sb.insert(2, 'e');sb.insert(3, ' ');
We insert four characters at the beginning of the string.
sb.setCharAt(4, 'm');
Finally, we replace a character at index 4.
$ java com.zetcode.StringBuilderElementsMisty mountainsMisty mountainMisty mountainsThe Misty mountainsThe misty mountains
From the output we can see how the mutable string is changing.
Comparing strings
There are two basic methods for comparing strings. The equals() method compares the
contents of two strings and returns a boolean value indicating, whether the strings are equalor not. The equalsIgnoreCase() does the same thing, except that it ignores the case.
package com.zetcode;
public class ComparingStrings {
public static void main(String[] args) {
String a = "book";String b = "Book";
System.out.println(a.equals(b));System.out.println(a.equalsIgnoreCase(b));
}}
We compare two strings using the aforementioned methods.
String a = "book";String b = "Book";
52
7/27/2019 ZetCode Java tutorial.doc
53/681
We define two strings that we will compare.
System.out.println(a.equals(b));
The equals() method returns false. The two strings differ in the first character.
System.out.println(a.equalsIgnoreCase(b));
When we ignore the case, the strings are equal. The equalsIgnoreCase() method returns
true.
$ java com.zetcode.ComparingStringsfalsetrue
This is the output of the com.zetcode.ComparingStrings program.
If we are comparing a variable to a string, it is important to remember that the string is on theleft side of the comparing method. Otherwise we might get the NullPointerException .
import java.util.Random;
public class ComparingStrings2 {
public static String readString() {
Random r = new Random();boolean b = r.nextBoolean();
if (b == true) {
return "ZetCode";
} else {
return null;}
}
public static void main(String[] args) {
String d = readString();
if ("ZetCode".equals(d)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");}
}}
In the code example, we compare the strings properly, avoiding possible
NullPointerException .
public static String readString() {
53
7/27/2019 ZetCode Java tutorial.doc
54/681
Random r = new Random();boolean b = r.nextBoolean();
if (b == true) {
return "ZetCode";} else {
return null;}
}
The readString() method simulates the case where a method invocation can result in a nullvalue. This could happen, for instance, if we try to read a value from a database.
String d = readString();
The d variable can contain the null value.
if ("ZetCode".equals(d)) {
The above line is the correct way of comparing two strings where one string is a knownliteral. If we placed the d variable on the left side, this would lead to NullPointerException
if the d variable would contain the null value.
The equals() method compares the characters of two strings. The == operator tests for
reference equality. All string literals are interned automatically in Java. They are placedinside a string pool. This happens at compile time. If two variables contain two equal string
literals, they in fact refer to the same string object inside a string pool.
package com.zetcode;
public class ComparingStrings3 {
public static void main(String[] args) {
boolean a = "ZetCode" == "ZetCode";boolean b = "ZetCode" == new String("ZetCode");boolean c = "ZetCode" == "Zet" + "Code";boolean d = "ZetCode" == new String("ZetCode").intern();boolean e = "ZetCode" == " ZetCode ".trim();
System.out.println(a);System.out.println(b);System.out.println(c);System.out.println(d);System.out.println(e);
}}
In this code example, we compare string objects with the == operator.
boolean a = "ZetCode" == "ZetCode";
These strings literals are interned. Therefore, the identity comparison operator returns true.
54
7/27/2019 ZetCode Java tutorial.doc
55/681
boolean b = "ZetCode" == new String("ZetCode");
Strings created with the new operator are not interned. The comparison operator results in a
false value.
boolean c = "ZetCode" == "Zet" + "Code";
Strings are concatenated at compile time. The string literals result in the same object. Theresult is a true.
boolean d = "ZetCode" == new String("ZetCode").intern();
The intern() object puts the string o