0% found this document useful (0 votes)
4 views

Java 1 Basic syntax and semantics Software Development Poul Klausen instant download

The document is an introduction to 'Java 1: Basic Syntax and Semantics' by Poul Klausen, which serves as a foundational guide for beginners in Java programming. It covers essential topics such as commands, data types, program control, and the use of the NetBeans IDE, emphasizing practical exercises to enhance learning. The book aims to equip readers with the skills to write simple console applications and understand the programming process in Java.

Uploaded by

lugoofelito
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java 1 Basic syntax and semantics Software Development Poul Klausen instant download

The document is an introduction to 'Java 1: Basic Syntax and Semantics' by Poul Klausen, which serves as a foundational guide for beginners in Java programming. It covers essential topics such as commands, data types, program control, and the use of the NetBeans IDE, emphasizing practical exercises to enhance learning. The book aims to equip readers with the skills to write simple console applications and understand the programming process in Java.

Uploaded by

lugoofelito
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Java 1 Basic syntax and semantics Software

Development Poul Klausen install download

https://ebookmeta.com/product/java-1-basic-syntax-and-semantics-
software-development-poul-klausen/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Exploring the Syntax and Semantics of South Asian


Languages 1st Edition Reena Ashem

https://ebookmeta.com/product/exploring-the-syntax-and-semantics-
of-south-asian-languages-1st-edition-reena-ashem/

Java 17 Quick Syntax Reference 3rd Edition Mikael


Olsson

https://ebookmeta.com/product/java-17-quick-syntax-reference-3rd-
edition-mikael-olsson/

NoSQL and SQL Data Modeling: Bringing Together Data,


Semantics, and Software First Edition Hills

https://ebookmeta.com/product/nosql-and-sql-data-modeling-
bringing-together-data-semantics-and-software-first-edition-
hills/

Religion in America The Basics 2nd Edition Michael


Pasquier

https://ebookmeta.com/product/religion-in-america-the-basics-2nd-
edition-michael-pasquier/
The Sun Dragon First Edition,New Edition Jay Annabelle

https://ebookmeta.com/product/the-sun-dragon-first-editionnew-
edition-jay-annabelle/

Candlelight Promise A Kwanzaa Kisses Holiday Romance


1st Edition Lia Violet

https://ebookmeta.com/product/candlelight-promise-a-kwanzaa-
kisses-holiday-romance-1st-edition-lia-violet/

Selling and Sales Management, 11e 11th Edition David


Jobber

https://ebookmeta.com/product/selling-and-sales-
management-11e-11th-edition-david-jobber/

Trauma and Motherhood in Contemporary Literature and


Culture

https://ebookmeta.com/product/trauma-and-motherhood-in-
contemporary-literature-and-culture/

Modified Posterior Approach to the Hip Joint 2nd


Edition K. Mohan Iyer

https://ebookmeta.com/product/modified-posterior-approach-to-the-
hip-joint-2nd-edition-k-mohan-iyer/
Resurrected as a Drow 2 1st Edition Logan Jacobs

https://ebookmeta.com/product/resurrected-as-a-drow-2-1st-
edition-logan-jacobs/
Poul Klausen

Java 1: Basic syntax and


semantics
Software Development
Java 1: Basic syntax and semantics: Software Development

1st edition

© 2017 Poul Klausen & bookboon.com

ISBN 978-87-403-1689-6

Peer review by Ove Thomsen, EA Dania

Contents
Foreword 6
1 Introduction 8
2 Hello World 11

2.1 NetBeans 11

2.2 The source code 15


2.3 Run the program 16

2.4 The NetBeans project 17

2.5 Gedit 19

2.6 Something about comments 21

2.7 Example: Kings 22

Exercise 1 23

Exercise 2 23

3 Commands and console programs 24

3.1 Commands 24

3.2 Example: PrintAddress 27

Problem 1 28

3.3 Console programs 29

Problem 2 32

4 Variables and data types 33

Exercise 3 38

4.1 Operators 38

Exercise 4 44
Exercise 5 45

4.2 Literals 46

4.3 Objects 49

Exercise 6 59

Problem 3 59

4.4 Example: Cubes 63

Exercise 7 65

4.5 Arrays 67

Exercise 8 71

4.6 Example: CupProgram 72

4.7 Multidimensional arrays 76

Exercise 9 78

5 Program control 79

5.1 The if statement 79

Exercise 10 81

Problem 4 82

Problem 5 83
5.2 do and while statements 84

Exercise 11 85

Problem 6 87

5.3 The for statement 88

Exercise 12 92

Exercise 13 92

Problem 7 94

5.4 The switch statement 94

Exercise 14 96

5.5 Return statement 97

5.6 Break and continue 97

Problem 8 101

Problem 9 102

6 ArrayList 104
7 Comparison and sorting 107
8 Files 114

8.1 Text files 114


Excercise 15 118

8.2 Serialization of objects 119

Exercise 16 121

9 Final example 123

9.1 Design 126

9.2 Programming and test 130

Appendix A 131
Foreword
This book is the first in a series of books on software development.
The programming language is Java, and the language and its syntax
and semantics fills obviously much, but the books have also largely
focus on the process and how to develop good and robust
applications. The subject of the current book is an introduction to
the programming language Java with an emphasis on basic language
syntax and semantics, but it is also a book about what programming
in general is and how to practically write and test simple programs.
The book requires no knowledge about programming or the
language Java, and the goal is to show how to get started writing
computer programs. After reading the book and worked through the
book’s exercises and problems, the reader should be able to write
simple console applications in the language Java.

As the title says this series of books deals with software


development, and the goal is to teach the reader how to develop
applications in Java. It can be learned by reading about the subject
and by studying complete sample programs, but most importantly by
yourself to do it and write your own programs from scratch.
Therefore, an important part of the books is exercises and problems,
where the reader has to write programs that correspond to the
substance being treated in the books. All books in the series is built
around the same skeleton and will consist of text and examples and
exercises and problems that are placed in the text where they
naturally belongs. The difference between exercises and problems is
that the exercises largely deals with repetitions of the substance that
is presented in the text, and furthermore it is relatively accurately
described what to do. Problems are in turn more loosely described,
and are typically a little bigger and there is rarely any clear best
solution. These are books to be read from start to finish, but the
many code examples, including exercises and problems plays a
central role, and it is important that the reader predict in detail
studying the code to the many examples and also solves the
exercises and problems or possibly just studying the recommended
solutions.

All books ends with one or two larger sample programs, which focus
primarily is on process and an explanation of how the program is
written. On the other hand appears the code only to a limited extent
– if at all – and the reader should instead study the finished program
code perhaps while testing the program. In addition to show the
development of programs that are larger than the examples, which
otherwise is presented, the aim of the concluding examples also is to
show program examples from varying fields of application.

Most books also ends with an appendix dealing with a subject that
would not be treated in the books. It may be issues on the
installation of software or other topics in computer technology, which
are not about software development, but where it is necessary to
have an introductory knowledge. If the reader already is familiar
with the subject, the current appendix can be skipped.
The programming language is, as mentioned Java, and besides the
books use the following products:

NetBeans as IDE for application development

MySQL to the extent there is a need for a database server (from


the book Java 6 onwards)

GlassFish as a web server and application server (from the book


Java 11 onwards)

It is products that are free of charge and free to install, and there is
even talk about products, where the installation is progressing all by
itself and without major efforts and challenges. In addition, there
are on the web detailed installation instructions for all the three
products. The products are available on Windows and Linux, and it
therefore plays no special role if you use Linux or Windows.

All sample programs are developed and tested on machines running


Linux. In fact, it plays no major role, as both Java and other
products work in exactly the same way whether the platform is one
or the other. Some places will be in the books where you could see
that the platform is Linux, and this applies primarily commands that
concerning the file system. Otherwise it has no meaning to the
reader that the programs are developed on a Linux machine, and
they can immediately also run under Windows unless a program
refers to the file system where it may be necessary to change the
name of a file.
Finally a little about what the books are not. It is not “how to write”
or for that matter reference manuals in Java, but it is as the title
says books on software development. It is my hope that the reader
when reading the books and through the many examples can find
inspiration for how to write good programs, but also can be used as
a source collection with a number of examples of solutions to
concrete everyday programming problems that you regularly face as
a software developer.
1 Introduction
A computer program is a series of commands executed in a certain
order, and together they solve a specific task. A program is written
as a text document that contains all the necessary commands. This
document is called the program code or source code. The individual
commands must be written in a very precise way for the computer
to understand them, and it is here that programming languages
comes into the picture. A programming language lays down precise
rules for how the commands should be entered. There are many
programming languages, and although they are different, each with
their advantages and disadvantages, the similarities outweigh the
differences, and once you have learned a language, it is easy to
learn the next. The following are used throughout the Java
programming language, which is a widely used languages on many
platforms. How the individual commands and orders exactly must be
written is called the language’s syntax. What the individual
commands are doing or performing is called the language’s
semantics.

As mentioned above, a program is written as a text document (in


practice several or many), and it is simply a document of commands.
Commands are also called statements. These commands or
statements being only text, the machine can not immediately
perform the comands, but they must be translated into an internal
format that the computer understands. This process is called
translation or compilation and is performed by a program that can
convert statements written in a particular programming language to
the computer’s internal commands. The program is usually called a
compiler. During the translation the program is checked for errors,
and if there are errors, you get an error message, and the errors
must then be corrected before the program is translated again. Not
all errors are found during translation, but only syntax errors, which
covers the issue where a statement is not written in accordance with
the programming language’s rules. A translated program can easily
contain errors, for example a miscalculation.

To write a program you must of course learn the programming


language that is selected, but also you must learn how the solution
of a task can be formulated by statements in the language. It is the
latter that is the most difficult, and there is rarely a clear solution. A
solution of a problem by means of a program is also called an
algorithm. Programming is largely a matter of writing algorithms,
something that I will return to several times.

When you have to write software, you need a tool that can be used
to enter the program code, and in principle you could use a simple
input program (a text editor) and then the compiler, but in practice
you will always use a specific development tool, as it makes the job
much easier. In the following I will everywhere use NetBeans, a
development tool for a wide variety of tasks, including writing code
in Java. It is an integrated software package, which includes all the
tools necessary for the development of a number of different types
of programs.

Java is an object oriented programming language. The fundamental


architectural element in a program is a class, and from the
programmer’s point of view a Java program consists of a family of
classes that collectively define all the application’s features and
functionality. Writing a program is thus to define – design – and
write the code to the program’s classes. Nothing in Java exists
outside of a class. A program will also always apply other classes
that are not written by the programmer, but classes coming from the
Java API, and thus is available for the programmer as finished
components. One of the program’s classes have a special role as the
program’s “entry point” and the place where the program starts and
this class should be written with a special naming, but it is almost
the only formal requirements for the architecture of a Java program.

Java is technically both a platform and a programming language.


Seen as a programming language, it is a high-level language, which
is characterized by

it is a simple language

it is an object-oriented language

the language is architecture neutral

Java programs are portable

it supports development of multithreaded applications


it supports the development of distributed applications

it supports the development of programs with strong security

development of effective programs

development of robust programs

development of maintenance-friendly and dynamic programs

All Java code are as mentioned written as plain text files – which
filename must have the extension .java – and then these files are
translates to .class files. The translation is performed by the Java
compiler called javac. Java class files do not contain machine code
for a particular platform, but rather so-called bytecode, which is the
machine code for the Java Virtual Machine, which is a virtual
computer, commonly referred to as VM or JVM. The program
(consisting of a set of class files) can then be carried out by the
virtual machine, which is a program that is running on a particular
machine. Since Java and thus the virtual machine is available for
many different operating systems, the same class files can run on
many machines for example Windows, Solaris, Linux, etc.

With a platform wee understand the hardware and software, where


a program is running, and in relation to an usual PC you can think of
Windows, Linux and Mac machines. Compared to this is a Java
platform a software-only solution that runs on a different hardware
based platform. The Java Platform consists in principle of two parts:

JVM, the Java Virtual Machine


an API, the Java Application Programming Interface

where the last is a large collection of ready to use software


components that a program can use. They are grouped into libraries
called packages, which consists of classes and interfaces.

The result of the above technology is that Java programs, in


principle, is a bit slower than programs translated into an actual
physical machine. However, since Java was born there has been an
incredible number of improvements and optimizations of both the
compiler and the virtual machine, so the difference in performance is
negligible if at all measurable.
2 Hello World
The subject of this chapter is to show how to write and run a Java
program using NetBeans and the aim is solely to get started. There are
several kinds of programs, or you can say that the programs can be
categorized in several ways, but in the first books I will look at three
types of programs:

commands, which is a program that is typically performed from a


command window (a Terminal ) where you enters the program’s
name that may be followed by one or more arguments

consol applications, which also is performed at a command prompt,


but here the program runs in a dialogue with the user, where the
user must enter values when the program is executed

GUI-programs, where the program opens one or more windows with


components as buttons and input fields used by the user to interact
with the program

This division is only for practical reasons, as I will sometimes


characterize the program examples in relation to this, but common to the
three types of programs is that they are standalone applications that run
on a single machine and without using resources on other machines.

I’ll start with the classic Hello World program, a program that prints a
text on the screen. It is an example of a command, but it is also an
example of a program that has absolutely no practical interest. Although
it is a simple program, it will nevertheless treat a number of basic
principles that apply to all Java programs.
2.1 NetBeans
As mentioned a Java program is written as text files, which will then be
translated. When the files are translated without errors the program can
be executed by the virtual machine. In practice is always used a
development tool, which is a program or software package that
integrates all the functions that a developer needs. Such a tool is usually
called an IDE (Integrated Development Environment), and there are
several, but I will everywhere use NetBeans, which contains everything
that is needed, and the following requires that both Java and NetBeans
are installed on the machine. Do not have it, you can start by reading
Appendix A which explains how to download and install both Java and
NetBeans.

To write the first Java program, open NetBeans and create a new
project. In the menu, choose

File | New Project (see below)

A NetBeans project creates all the necessary files required to develop


and test the program and eliminates a variety of configurations that are
otherwise necessary. Using NetBeans you can build and run the program
just by clicking the menu. To create the project, you must note that in
this case,

Java is marked in Categories

Java Application is selected in Projects

but otherwise I have not done anything in the first window.


When you then click Next you get the following window:

Here I:
Entered HelloWorld as Protect Name

Selected /home/pa/doc/noter/note01 for Project Location

Regarding the latter, it is just a question that I have decided that the
project should be created in the /home/pa/doc/notes/note01 direcory. I
have also decided that the project should be called HelloWorld. NetBeans
will then create a folder

/home/pa/doc/noter/note01/HelloWorld

and all project files are placed by NetBeans in this folder. You should
note that there is a checkmark in the Create Main Class, which is
important.

When you then click Finish, the project is created and NetBeans displays
multiple windows:
Projects window, where all the project’s components are organized in
a hierarchy

Source Editor, where there is an open file called HelloWorld.java

Navigater, which can be used to quickly find a specific item

Source Editor contains the program’s code, and as you can see,
NetBeans automatically creates a skeleton for a program. Actually, it’s a
full-fledged program – it performs nothing not yet. The program code
consists of Java statements and comments. Comments are removed by
the compiler and does not affect the finished program. They are inserted
solely for the sake of us people who should read and understand the
program code.

2.2 The source code


Below I’ve shown the finished program after I have changed or removed
the comments that NetBeans has generated and written a single
statement:

There is only one comment back, which is at the top and says something
about what the program does. The rest of the code is Java statements. A
Java program consists of classes, and in this case there is one class
called HelloWorld and thus has the name that I chose as project name.
The class consists of a method called main(), which has a single
statement – not created by NetBeans, but as I entered. It is a statement
that prints a text on the screen.

The code is simple, and so far you just accept that it should be written,
as shown above, but there is however a few things that you should note.

Java is case-sensitive, so everywhere you must distinguish between


uppercase and lowercase letters.
Every Java program consists as already mentioned by at least one class
here called HelloWorld. A class consists of variables and methods. In this
case, the class has only one method called main(), which is the method
that is called when the program starts. A method consists of statements
that can be perceived as commands that perform one or other on the
machine. That a method is called means that the methods statements is
performed. Note that the method main() must be prefixed by the words
public static void. The explanation will follow. In this case, main() has
only a single statement, that write a text on the screen.
System.out.println() is actually a method in a class PrintStream, that
among other things, represents the screen. When the program is
running, nothing happens than the println() statement in main() is
performed that prints a text on the screen.

Note that in Java, each statement ends with a semicolon – above there
is a semicolon after System.out.println(). It tells the compiler where a
statement ends.

In Java classes are grouped in so-called packages. A class’s full name


consists of the package that the class it is grouped under, as well as the
class name. NetBeans automatically define a package for a program that
is the application name written in lowercase, and the first statement is a
package statement indicating the class’s package. A package statement
must be the first statement in the file that contains a class, but can be
prefixed by a comment. Note that in Java you generally has to place
each class in its own file, but more on that later.

2.3 Run the program


When the program is written as above (without errors), you can from the
menu in NetBeans choose

NetBeans will automatically translate the program, and if it not contains


errors, the program will be performed:

If the program contains errors, the result could be the following:

The program then is not performed, and the translator instead offers an
error message, and the error must then be corrected before trying to run
the program again.

2.4 The NetBeans project


If you open Files you can as shown below find the class file, which is the
translated program:
HelloWorld.class is an example of a complete Java program that can run
on a specific machine. Apparently, the program is tied closely to
NetBeans and performed using NetBeans, but it is not the case. In the
menu in NetBeans choose

and the program is translated again, and if you opens Files you will
discover that that there is created another folder called dist, which
contains two files (see below). Here is HelloWorld.jar a package (actually
a compressed zip file) containing the program files – only the translated
class files and other ancillary files that are necessary for the program to
run. In this case, there are actually only two.
If you copy the file HelloWorld.jar to a folder – for example temp – and if
you open a Terminal, stand in this folder and perform the following
command:

the program is performed:

Here the command java is a message to Linux to start the Java runtime
system and execute the program HelloWorld.

2.5 gedit
Above I have written and performed a Java program using NetBeans,
and in the following, all programs will be developed in this way.
NetBeans is a large and complex program, and until this place, you have
seen only a very small fraction of what the program can. The program is
relatively user-friendly, and I will not give any general description of the
program and its possibilities, but I will mention important features as I
need them in the individual examples. NetBeans is similar to all other
IDEs for software development, so the forces you use to learn more
about the program, is definitely not wasted. Using an IDE for developing
applications provides in practice such large benefits that it makes no
sense to develop programs in other ways, but in principle you can, and I
will in this section show how to write the program Hello World without
NetBeans.

I start by creating a directory named Hello in my home directory. Then I


open gedit and enter the code below. It is important to enter the code
exactly as shown below, and especially you should be aware that it is
case-sensitive. You should also be aware that you do not insert extra
spaces. Note also that the text is displayed in several colors. This is
because gedit know Java, and thus highlights reserved words.

When the program is written, I save it in the folder Hello and call it
HelloWorld.java. Again, please note upper and lower case and the
filename must have the extension java written in lower case. Then I
open a Terminal and set the current directory to the folder Hello. Here I
performs the following command:

javac is the name of the compiler, and the result is that the program is
being translated, and creates a file with the translated program called
HelloWorld.class:

Then you can execute the program as follows:

As mentioned, I practically always use NetBeans, and even if the above


is not of great practical interest, it may nevertheless serve to illustrate
what NetBeans is doing. It is basically an advanced editor program that
help you when you enter code and point out incorrect entries. Moreover
NetBeans calls both the javac compiler and the runtime system java.
NetBeans will provide support to the programmer and support the
development of large and complex applications. Therefore even small
NetBeans projects contains many directories and files, and it can hide
what really is the program itself. This example can show how little it
really is.

2.6 Something about comments


As you have seen, NetBeans inserts comments in the program’s code.
They will as mentioned be ignored by the compiler and are inserted for
the sake of the people who must read and understand the code.

There are three types of comments. The first starts with /* and ends
with */ and everything in between these character combinations is
considered as a comment, for example

which is the comment that NetBeans inserts at the beginning of a new


source file. Another kind of comments start with the characters /** and
ends with */, for example

Again, everything between the start and end character combinations is


comments, but there can be inserted special symbols that are
interpreted by a tool to generate html documentation of the program
code, but about that later. The last type of comment has the form
That comment can be inserted anywhere, and all after the characters //
to the end of the line are considered as a comment.

This is the syntax for inserting comments in the code, but a whole other
thing is what you should write. Also I come back to that later, but
generally you have to write what you think might be valuable at a later
reading of the code. What it is, is certainly not unique, and it can be
good inspiration to examine what comments others have inserted into
programs.

2.7 Example: Kings


The example is a program called Kings, in principle it is written in the
same way as HelloWorld, but the program prints the following text:

The final code is shown below:


The only difference compared to HelloWorld is that this time there are
several System.out.println() statements.

Exercise 1
Write a program, as you can call Digits, that on the screen prints the
following table:

Exercise 2
Write a program that you can call Label, that prints your name, your
address and your email address, for example
3 Commands and console
programs
In the previous section I divided the programs into three categories,
and in this chapter I will look at commands and console programs. In
principle there is no big difference, and the division alone has to do
with how the user is transferring data to the program. Both
HelloWorld and the example Kings from the previous chapter are
examples of commands.

3.1 Commands
Every Java program must have a main() method that has the
following signature:

For the moment you should ignore the meaning of the words public,
static and void and just accept that they should be there, but the
main() method is the place where the program starts. After the
method name is a parameter in parentheses, indicating arguments
from the command line that can be transferred to the program.
Consider the following program:
args is an array, as I explains later, but the arguments that are
transferred on the command line, are in the program referred to as

and so on. An argument is a text string, and arguments are


separated by spaces. If, for example you copy the file Command.jar
to the temp folder, the program can be perform as follows:

There are two arguments, called respectively Svend and Knud, and
the program prints the two arguments of the screen. If you execute
the program in the following way:
the result is the same. This time there is three arguments, but only
the first two are used in the program. If, however, the application
performs without having two arguments, you get an error:

The reason is that the second argument does not exist, and therefore
fails the statement:

The example shows, what I will understand by a command. Another


question is how to test the application from NetBeans when you has
to transferre arguments. This can be done through the menu to
choose

Here you must select the category Run, where you will be able to
enter the arguments:
Note that contains the argument spaces, it is necessary to specify
them in quotes.

3.2 Example: PrintAddress


The following program will print the name and address of a person,
but so that the values to be printed are transferred on the command
line. The program is therefore a command. The program is called
PrintAddress, and threre must be transfered four arguments on the
command line. Arguments on the command line are separated by
spaces, and if an argument contains spaces, it is necessary to put the
argument in quotes. Then the runtime system will perceive it as one
argument. An example of running the program could, for example be
as shown below:
For writing the program I have in NetBeans created a project called
PrintAddress. The program code can then be written as follows:

The statements in the main() method is all System.out.println()


statements that prints a line on the screen. The first only prints a
text, while the second prints a blank line. The third prints a text
followed by the value of args[0], which is the person’s name. Note
particularly the plus operator, which means string concatenation,
wherein the text is added after the other. The last two
System.out.println() statements works in principle in the same way.

A program like the above are not robust, as it will fail if not
transferred the right number of arguments. You should also note that
the program does not test the arguments (which incidentally is also
not so easy), but simply prints the arguments as they are.

Problem 1
You should write a program for a library that can print a recall of a
book. When the program is executed, you must on the command line
transfer five arguments:

borrower’s name

borrower’s address

borrower’s zipcode and town

ISBN of the book

the books title

An example of an execution of the program might be:


3.3 Console programs
Compared to a command a console program (in this books) is a
program that performs a dialogue with the user, where the user must
enter data.

Above I have shown a program that prints the name and address of a
person when the values are passed as arguments on the command
line. Below is the same program, but this time the user must enter
the values during running the program. There is thus a dialogue with
the user.
As you can see, the code has been substantially larger, and there is
also new things that has to be explained.

To enter text, you must have an object that represents the keyboard
and provides a service available for entering text. In addition I apply
a Scanner that use the objekt System.in that just represents the
keyboard. Scanner is a class that is not readily available, and
therefore there is added an import statement that refers to the
package containing the class Scanner. in is then an object that can
be used to enter a text. The next line prints a text on the screen,
telling the user to enter the name. It happens with
The text that the user enters, must be stored somewhere, and for
that purpose a variable is used. Variables are considered in the next
chapter, but a variable is a place where you can store a value. An
example could be the statement

Here, the text that the user enters is stored in the variable name. The
next statements are identical in principle and are used for entering
other values. The last statements are used to print the result and is
similar in principle to the previous version of the program, but the
arguments args[0], args[1], … are replaced with variables. If you run
the program (from NetBeans), the result could be as shown below:

Today it is rarely – if ever – developing console applications, and


when is a need for a program with a user dialogue (and it is of
course often), you write a Windows or GUI program. Console
programs may, however, for testing and learning be useful, and
therefore it is excellent to know how to write a simple console
program.
Problem 2
You must solve the same task as in problem 1, but instead of
transferring values as arguments on the command line, you must
enter information about

borrower’s name

borrower’s address

borrower’s zipcode and town

ISBN of the book

the books title

when then the program is running in a dialogue with the user. The
program should print the same recall as in problem 1.
4 Variables and data types
Programs has to deal with data, and for that they need a way where
to save or store data. To that purpose programs use variables that
are items, where the program may store a value. You must note that
I have already used variables associated with data entry. A variable is
characterized by

a name

a type

operators

Variables must have a name, so you can refer to them in the


program. Java is similar to other modern programming languages
relatively flexible in terms of naming variables, but the following shall
(should) be met:

a variable name must start with a letter, a dollar sign ‘$’ or an


underscore ‘_’

a variable name should always start with a lowercase letter, and


one should avoid ‘$’ and only occasionally use ‘_’

then have to follow any number of characters consisting of letters,


digits, $ and _

a name must not contain spaces


the name of a variable must not be a reserved word, that is a
word that has specific meaning in Java

In addition a variable name should tell something about what it is


used for. Use whole words instead of cryptic abbreviations. It will
make the code easier to read and understand. If you have long
names consisting of several words, you can increase readability by
letting a word (except the first) start with a capital letter such as
customerAddress. Alternatively, is there anyone who writes
customer_address, but generally avoid very long names.

If you do not break these rules, you have never problems with names
of variables, but some other characters are actually allowed.

Variables has a type that indicates which values can be stored in


them, and how much a variable is filling in the machine’s memory.
The type determines simultaneously the operations that can be
performed on a variable, that is what to do with it.

Variables must be created or declared before they can be used. This


is done by a statement of the form:

type name = value;

That is, to write the type first, then the variable name and finally
assign it a value, for example
Here is declared a variable called number, that has type int and the
value 23. Variables should always be initialized, else you can get a
translation error.

When variables must be declared, it is because the compiler must


allocate space in the machine’s memory, and that when the name
appears somewhere in the code, the compiler must know what the
name mean to check if the variable is used in the proper context. If
not, the compiler will come up with an error message. The program
can only be used when it is compiled without errors.

Java has the following built-in primitive or simple data types:

byte, which is a data type for an integer. A variable occupies 8


bits, and may contain values from -128 to 127 (both inclusive).

short, which is a data type for integers. A variable takes up 16 bits


and may contain values from -32,768 to 32,767 (both inclusive).

int, which is a data type for an integer. A variable occupies 32 bits


and can contain values from -2147483648 to 2147483647 (both
inclusive). It is the default type for an integer.

long, which is a data type for an integer. A variable occupies 64


bits and can contain values from -9,223,372,036,854,775,808 to
9223372036854775807 (both inclusive).

float, which is a data type for floating point numbers and can thus
be used for decimal numbers. A variable occupies 32 bits and can
represent decimal numbers with 7–8 significant digits. It is
important to note that the value is always a rounded result.
double, which is a data type for floating point numbers and can
thus be used for decimal numbers. A variable occupies 64 bits and
can represent decimal numbers with 14 significant digits. It is
important to note that the value is always a rounded result. This
type is the default type for a floating point.

boolean, which is a data type with only two values: false or true.
The type is important to be able to write conditions and is used
specially for program control.

char, used for characters, and a variable of the type char takes up
16 bits. Values are numeric codes with values from 0 to 65535
(both inclusive), and each character is represented by a numeric
codes. For example has a large A the code 65.

The smallest unit you can use on a digital computer is a bit, and the
whole computer’s memory consists of a number of devices that can
store one bit. One bit can represent one of two values, commonly
referred to as 0 and 1, and the contents of the computer’s memory is
always a large number of 0s and 1s. In practice, you cat not directly
refer to the individual bits, but they are organized in groups of 8 bits,
and such a group is called a byte. A byte is a pattern consisting of 8
bits, for example

What that means depends on how a program uses the pattern. Since
each of the 8 places in a byte, may have two values, a byte therefore
can represent different values. As is clear from the above the simple
data types are different in how many bits they use to a variable of
that type. For example uses an int 32 bits (or 4 bytes), and this
means that one can represent different integers that is interpreted as
the numbers starting from -2147483648 to and including
2147483647.

In addition to the eight primitive data types mentioned above, there


is, as already mentioned a type String which can contain any text
string. For example you can write

The statement creates a variable of the type String. You should note
that you specify the value in quotes. The type String is not a primitive
type, but it is instead a class, but for now you can ignore it, and
variables of the type String is used in principle in the same way as
other variables.

Primitive variables are assigned a default value of the compiler. The


type boolean have the default value false, a char has a space as the
default value, while the other primitive types have the default value
0. A String (which is not a primitive type) has no value, which is
defined as null.

As an example, the following statements creates three variables, all


of the type int:
The first two variables are initialized with numbers, while the last is
initialized to the sum of the first two. The last statement prints the
values of the three variables.

Consider as an example the following program, which is a command


to be performed on the command line with three arguments which
must be integers, and the program prints the sum of the three
numbers:

If you execute the program with arguments 13, 17 and 19, the result
will be:

Arguments for a command or data that is entered into a console


application, has always the type String, and they can not be directly
used in the calculations. It is first necessary to convert the values
Discovering Diverse Content Through
Random Scribd Documents
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
back
back
back
back
back
back
back
back
back

You might also like