Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Lecture 2
Introduction to Java
Objectives
• Learn about the history of Java
• Describe the use of the Java Virtual Machine
• Describe the phases in the life cycle of a Java
program
• Introduce the Eclipse IDE
• Introduce the basic structure of a Java program
–
–
–
–
Classes
Input/Output
Primitive data types
Operators
History of Java
• What is Java?
– Java was developed by Sun Microsystems in 1991.
– It is based on C++ but is a more heavily object
oriented language.
– It was initially designed to program the proliferating
array of small internet connected consumer products
– today called the internet of things.
– It was adopted as a primary programming language
for the web as it gained popularity.
– One of its key features is that a compiled Java
program should (in theory) be able to run on any
device regardless of architecture.
Uses for Java
• Today Java is a widely used language for
enterprise programming.
• It is also used to program internet-based
applications on a variety of devices.
– Web content for computers
– Cell phones and tablets (particularly Android)
– Television boxes (cable, DVR, etc.)
– Networking devices (routers, switches, etc.)
Lifecycle of a Java Program
• A Java program is usually created using an IDE but just a
text file.
– Eclipse (what we will be using)
– NetBeans
– IntelliJ IDEA
• The text file must have the extension .java.
• You could compile the Java code using the command
line javac but we will use the IDE to help with this.
• The compiled code will result in a .class file.
• Multiple .class files can be aggregated together in a
.jar (Java Archive) file to distribute software – a
running program may use several classes.
Java Virtual Machine
• The reason compiled Java code can run on multiple
systems with different architectures is that the
compiled .class file contains byte code
(instructions) for a theoretical Java Virtual Machine
(JVM).
• A virtual machine is a software application that
simulates the operation of a computer but hides
the underlying hardware and software.
• The same JVM is implemented on many different
platforms and so all of them can run the same
.class file.
Java Virtual Machine
• Advantages of compiling for a virtual machine:
– The compiled code is portable.
– There is a level of security provided.
• A Java virus is (in theory) only infecting the virtual machine
which will be turned off and reset when the program ends.
– Faster than an interpreted language like Python.
• Code is already compiled.
• Disadvantages of compiling for a virtual machine:
– It is slower than a traditional compiled language like C++.
• Byte code must be translated to run on the physical hardware.
– It can only support features that are available on all of
the systems (lowest common denominator).
– It does not have access to low-level hardware.
Java Variants
• Java Enterprise Edition (Java EE) for developing
large-scale, distributed networking and web-based
applications.
• Java Micro Edition (Java ME) for developing
software for embedded devices.
–
–
–
–
TV set-top boxes
Smart watches
MP3 players
etc.
Java APIs
• There are existing Java Class Libraries that provide
existing classes that can be used to help develop
new code
• The libraries are also known as Java APIs
(Application Programming Interfaces).
– In addition to making programming easier, using APIs can
improve performance.
– We will use an API developed specifically for the LEGO
Mindstorms EV3 to manipulate motors and read sensors.
Lifecycle of Java Program
• Phase 1: Program Creation
– .java files are created using IDE or text editor.
• Phase 2: Compilation
– .java files are compiled using javac to create
.class files.
• Phase 3: Loading
– The .class files are loaded into the memory of the
JVM.
– Multiple .class files can be used to create a program.
– Loading may be done using local files but can also be
done remotely.
Lifecycle of Java Program
• Phase 4: Verification
– The byte code in the .class files is examined to make sure
it is valid and does not violate security restrictions (an
attempt to prevent viruses and worms).
• Phase 5: Execution
– The byte code is translated into machine language so
that it can run on the host machine.
– This is often a combination of an interpreter and a justin-time (JIT) compiler that compiles frequently used
“hot-spots” so they don’t need to be repeatedly
interpreted.
Eclipse
• The IDE we will use in this class is Eclipse.
• You can download the latest version of Eclipse
(Eclipse-Neon) for your system from
https://eclipse.org/downloads/
• You will also need to be sure that you have installed
compatible versions of the Java Developers Kit
(JDK) (the compiler) and Java Runtime
Environment (JRE) (the Java virtual machine).
– You can develop code without being able to run it.
– You can run code without being able to develop it.
First Program
• Our first program is called painter.
– The .java files for this program are on the Wikispaces
site for the class.
– Download these files and unpack them.
• When you first start up Eclipse it will ask you for a
workspace directory.
– This is the directory where your program files will be
stored.
– You may want to create a special directory for this
purpose.
Workspace Directory
• You can use the same workspace directory for all
your projects.
Main Window
• You will now see the main Eclipse window.
New Project
• To create a new project go to
File > New > Java
Project.
• Give the project a name and
select Finish.
Add Files
• Next you need to add the program files to the
project.
• Go to the Package Explorer and make sure that the
src folder it highlighted on the project where you
want to add the files.
Add Files
• Go to File >
Import… to get the
this dialog box.
• Select General and
then File System.
• Click on Next.
Add Files
• Navigate to the
directory where you
unpacked the
program files and
select all the .java
files.
• Click on Finish.
Add Files
• Back in the Package Explorer you should be able to
see the newly added files listed under scr >
(default package).
Editing Files
• You can click on any of these files to see its
contents.
Running Program
• You can run your program by
clicking on the green arrow
.
• You will get a dialog box asking
how to run the program – select
Java Application.
Running Program
• You can run your program by clicking on the green
arrow
.
• You should see a window open with your painter
program.
HelloWorld
• Let’s create a HelloWorld
project just as before.
• This time let’s create the
.java files ourselves.
– Highlight the src folder of
your newly created project.
– Select File > New > Class
– Name the class.
HelloWorld
• You should now be able to see the class file as part
of your project in the Package Explorer.
HelloWorld
• You enter the code for your program into the editor
pane of the window.
• Again, run the program as a Java Application.
HelloWorld
• You should see your output in the Console pane
of the window.
HelloWorld Details
• We can learn a lot about what goes into making a
Java program by examining HelloWorld.
– Comments are the same as C++.
// Hello World
/* This is a multiple
line comment */
– Brackets {} are used to denote blocks just as with C
and C++.
HelloWorld Details
public class HelloWorld {
• Every Java program must have at least one class.
• The public keyword indicates that the class
HelloWord will be stored in the file
HelloWorld.java.
– It is convention to capitalize the first letter of a class
name and to indicate words in the name by capitalizing
the them as well.
– Like C and C++, Java is case sensitive.
HelloWorld Details
public static void main(String[] args){
• Every Java function is actually a method of some class –
this includes the main function for your program.
• The public keyword means that this function can be
called from anywhere, not just by objects of the class.
• The static keyword means that this function belongs
to the class, not to individual objects.
– It is created when the class is loaded, not when an object is
declared.
– This means we can call the function without creating a
HelloWorld object.
HelloWorld Details
public static void main(String[] args){
• Every Java program (but not necessarily every
Java applet) needs a main function.
– main must be public and static.
• void indicates that our main function does not
have a return value.
• The parameter String[] args allows the
operating system to pass an array of strings to
the function.
– This is also required for main, even if you don’t plan
to use them.
HelloWorld Details
System.out.println("Hello World!");
• This calls the method (function) println
which belongs to the output stream out which
in turn belongs to the class System.
– Note that both out and println must be static
and public because we are accessing them without
creating a System object.
• Strings and semicolons are handled similarly to
C++.
– Note that strings are objects and so have methods.
Output
• Escape sequences are the same as in C and C++
–
–
–
–
–
\n – newline
\t – tab
\r – carriage return
\\ – backslash
\” – quote
• There is also a System.out.printf method which is
very similar to printf in C.
System.out.printf("%s\n%s", "Hello",
"World!");
• In a printf (but not println or print) it also
possible to use %n for a newline – this will be translated
to be whatever newline character the host system uses,
making the code more portable.
Input Example
• Here is an example of a program that reads input from the user.
import java.util.*;
// This program uses the Scanner class
public class Addition {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int n1, n2, sum;
System.out.print("Enter the first integer: ");
n1 = input.nextInt();
System.out.print("Enter the second integer: ");
n2 = input.nextInt();
sum = n1 + n2;
System.out.printf("The sum is %d%n", sum);
}
}
Input Example
• The import command is similar to an #include in
C or C++ with a few differences.
– It is actually part of the language (no precompiler).
– It imports classes, not just arbitrary blocks of code.
– Wild cards are permitted.
• import java.util.*; – this imports all the classes in the
java.util library.
• We need to create a Scanner object because there
are many different systems that may use our code and
not all will have keyboards.
– A Scanner object allows the program to read data.
– The data could come from many sources but we are specifying
that it comes from System.in (the keyboard on a
computer.)
Creating Objects
• Notice how we create an object of the Scanner class.
Scanner input = new Scanner(System.in);
– We are creating a new variable called input of type Scanner –
this is effectively a pointer to a Scanner object.
– We are reserving memory for the object using the new command.
– We explicitly call the constructor for the Scanner class and pass it
System.in to tell it where the input will be coming from.
Variables and Primitive Types
• We create variables the same way we did in C and C++.
– The primitive types are:
•
•
•
•
•
•
•
•
byte – 8 signed bits
short – 16 signed bits
int – 32 signed bits
long – 64 signed bits
float – 32 bits floating point (IEEE 754)
double – 64 bits floating point (IEEE 754)
boolean – true or false
char – 16 bits Unicode
Reading Input
• We use the input object to read keyboard input.
n1 = input.nextInt();
• This input is automatically converted to an integer value by the
method nextInt().
– If the input is not convertible to an int, then an exception is
thrown.
– Possible methods include;
•
•
•
•
•
•
•
•
next() – read the next character
nextLine() – read the next line as a string
nextByte()
nextShort()
nextInt()
nextLong()
nextFloat()
nextDouble()
Operators are Similar to C++
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Addition +
Subtraction Multiplication*
Division /
Modulus %
Increment ++
Decrement -Assignment =
Equality ==
Add and assign +=
Subtract and assign -=
Multiply and assign *=
Divide and assign /=
Modulus and assign %=
•
•
•
•
•
•
•
Logical and &&
Logical or ||
Logical not !
Logical and &&
Logical or ||
Logical not !
Ternary operator ?:
Order of operations
is similar to C++.
Homework
1. Describe how the method Java uses to produce executable machine
code compares to the methods used by both C++ and Python.
2. Describe the phases in the life cycle of a Java program.
3. Write a program the inputs three integers from the user and
displays the sum, average, product, smallest and largest. Use integer
division to produce the average.
4. Write a program that, given the radius of a circle as user input,
computes and outputs the diameter, circumference, and area of the
circle. Use the constant Math.PI to get the value ofp .
5. Write a program the inputs five numbers and determines and prints
the number of negatives, the number of positives and the number
of zeros.
Homework
6.
Write a program that prints the squares and cubes of the numbers 0
through 10 in a table format as follows. Feel free to explore different
programming tools to make this easier to write.
number
square
cube
0
0
0
1
1
1
2
4
8
3
9
27
4
16
64
5
25
125
6
36
216
7
49
343
8
64
512
9
81
729
10
100
1000