java

advertisement
Lesson 1
The Java World
AUBG ICoSCIS Team
Assoc. Prof. Stoyan Bonev
March, 23 - 24, 2013
SWU, Blagoevgrad
Time Schedule
March 23, Saturday – 10:00 – 10:45
– 11:00 – 11:45
– 12:00 – 12:45
Lunch Break (45’)
– 13:30 – 14:15
– 14:30 – 15:15
– 15:30 – 16:15
March 24, Sunday
09:00 – 09:45
10:00 – 10:45
11:00 – 11:45
Lunch Break (45’)
12:30 – 13:15
13:30 – 14:15
14:30 – 15:15
Lessons Schedule
Lesson 1: The Java World
Lesson 2: The Java PL – basic syntax
Lesson 3: The Java PL – StrProg and OOP
Lesson 4: Exception Handling in Java
Lesson 5: Java and GUI Programming
Lesson 6: Event Driven Programming in Java
Lesson 7: Unit Testing in Java
Lesson 8: Java Graphics
Lesson contents
 Why Java? Or Java popularity
 How Java works:

JRE, JVM, JDK
 Windows Environment

Java IDEs
 UNIX/Linux Environment
 First Java Program
Why Java?
Java enables users to develop and deploy applications on the Internet for
servers, desktop computers, and small hand-held devices.
Java
is a general purpose programming language.
Java
is O-O programming language
Java
is the Internet programming language.
Java
programs may be applications or applets or servlets.
Applications are standalone programs, similar to .NET Console and
Windows applications.
Applets are similar to applications, but they do not run as standalone
programs.
- Instead, applets adhere to a set of conventions that lets
them run within a Java-compatible browser (client-side).
- You can only run an applet from an HTML page.
5
The Java popularity
 TIOBE Programming Community Index for January 2013
 http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
The Java World
 Software aspects



Operating Systems
Language Processors
Development Environments
Operating Systems
 Java implemented under





UNIX
Linux
Windows
MAC OS
MS-DOS
Language Processors
 In order to run /to execute/, any program
written in HLL (incl. Java) should be
transformed to executable form
 Three ways to convert source code into
executable form:



Compiler – generate object code – see slide+1
Interpreter – interpret source code – see+2
Compiler of hybrid (semi-interpreting) type - +3
9
data
Source
program
compiler
Compile time
Object
program
Executing
computer
Results
Run time
10
Data
Source
program
Interpreter
Results
Compile time
Run time
11
data
Source
program
compiler
Compile1 time
Object
program in
IL form
Interpreter
Results
Compile2 time
Run time
12
How Java works
Java compiled to intermediate form – byte
code.
Byte code further processed:
by interpreter named JVM
OR
by JIT compiler.
Reminder and Refresh
Java Programming: From Problem Analysis to Program Design, 4e
The SDLC concept - see next slide
13
Problem-Analysis-Coding-Execution Cycle
Java Programming: From Problem Analysis to Program Design, 4e
14
How Java Works
 Java's platform independence is achieved by the use of the Java
Virtual Machine (JVM).
 A Java program consists of one or more files with a .java extension
• these are just text (i.e. source) files.
 When a Java program is compiled, the .java files are fed to the
compiler which produces a .class file for each .java file.
 The .class file contains Java bytecode.
 Java byte code is like machine language, but it is intended for the Java
Virtual Machine, not for a specific processor.
15
16
Executing a Java program
17
JVM emulation run on a physical machine
18
JVM handles translations
19
Java Components of special interest
 Pure Java includes 3 software facilities:
 JRE (includes JVM)
 JVM (a part of JRE)
 JDK
20
JRE
 The Java Runtime Environment
(JRE) provides
the predefined class libraries,
 the Java Virtual Machine, and
 other components to run applets
and applications written in Java.

21
JVM - Overview
 Java Virtual Machine is a program which executes programs,
namely those containing Java bytecode instructions.
 JVM is distributed along with Java Class Library, a set of
standard class libraries (in Java bytecode) that implement the
Java application programming interface (API). These libraries,
bundled together with the JVM, form the Java Runtime
Environment (JRE).
 The use of the same bytecode for all JVMs on all platforms
allows Java to be described as a write once, run anywhere
ProgLan, versus write once, compile anywhere, which describes
cross-platform compiled languages.
 Oracle Corporation, the owner of the Java trademark, produces
most widely used JVM, named HotSpot, that is written in C++
22
JVM
 JVM architecture.
Source code is compiled
to Java bytecode, which
is verified, interpreted or
JIT-compiled for the
native architecture.
The Java APIs and JVM
together make up the
Java Runtime Environment
(JRE).
23
JDK contents
The JDK has
as
its primary components
a collection
of programming tools,
including:
24
JDK contents (most often used utilities)
 appletviewer – this tool can be used to run and debug Java applets
without a web browser
 java – the loader for Java applications. This tool is an interpreter and can
interpret the class files generated by the javac compiler.
 javac – the Java compiler, which converts source code into Java
bytecode
 javadoc – the documentation generator, which automatically generates
documentation from source code comments
 jar – the archiver, which packages related class libraries into a single
JAR file. This tool also helps manage JAR files.
25
JDK contents (full list of utilities)
 appletviewer – this tool can be used to run and debug Java applets






without a web browser
apt – the annotation-processing tool4
extcheck – a utility which can detect JAR-file conflicts
idlj – the IDL-to-Java compiler. This utility generates Java bindings from
a given Java IDL file.
java – the loader for Java applications. This tool is an interpreter and can
interpret the class files generated by the javac compiler. javac – the Java
compiler, which converts source code into Java bytecode
javadoc – the documentation generator, which automatically generates
documentation from source code comments
jar – the archiver, which packages related class libraries into a single
JAR file. This tool also helps manage JAR files.
 Full list of utilities is too long and is not a subject of this lesson
26
A Simple Java Program
Listing 1.1
//This program prints message “Welcome to Java!“
// braces in end-line style
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
27
A Simple Java Program
Listing 1.1
//This program prints message “Welcome to Java!“
// braces in new-line style
public class Welcome
{
public static void main(String[] args)
{
System.out.println("Welcome to Java!");
}
}
28
Creating, Compiling, and
Running Java Programs
Create/Modify Source Code
Source code (developed by the programmer)
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Byte code (generated by the compiler for JVM
to read and interpret, not for you to understand)
…
Method Welcome()
0 aload_0
…
Method void main(java.lang.String[])
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
5 invokevirtual #4 …
8 return
Saved on the disk
Source Code
Compile Source Code
i.e., javac Welcome.java
If compilation errors
stored on the disk
Bytecode
Run Byteode
i.e., java Welcome
Result
29
If runtime errors or incorrect result
Running JAVA
in
Windows Environment
Creating, Compiling & Running
Java Programs
 From the Command Window

Details follow
31
To open command window
Click Start
 Select All Programs >
 Select Accessories
 Click Command Prompt

32
Compiling and Running Java programs
 Using any text editor , /notepad, edit, write/ type the source text
of a Java demo program like this:
public class prog4 {
public static void main(String[] args){
System.out.println("Hello from Java");
}
}
 Save the Java program as a prog4.java file.
33
Compiling and Running Java programs
 Run compiler with statement like this:
javac prog4.java
 Run application with stmt like this:
java prog4
34
Creating, Compiling & Running
Java Programs
 From within IDE jGRASP

Details follow
http://www.jgrasp.org
http://www.jgrasp.org/tutorials187/02_Getting_Started.pdf
35
jGRASP – introduction
 jGRASP is a lightweight development environment,
implemented in Java, and runs on all platforms with a
Java Virtual Machine (Java version 1.5 or higher).
 jGRASP is an academic style IDE.
 jGRASP is developed by the Department of Computer
Science and Software Engineering in the Samuel Ginn
College of Engineering at Auburn University.
36
jGRASP – JGrasp02_Getting_Started.pdf
2.1 Starting jGRASP
jGRASP virtual desktop gets displayed:
menu bar
tool bar
left pane – Browse tab, Find tab, Debug tab
large pane – for UML and CSD windows
lower pane – Messages tab, run I/O tab
37
jGRASP – JGrasp02_Getting_Started.pdf
2.2 Opening a program, compiling and running
File > Open > select a file in a folder
Build > Compile
Build > Run |> Run as Application |> Run as Applet
2.3 Creating a New File
File > New File > Java
2.4 Saving a File
File > Save | Save As
38
jGRASP – JGrasp02_Getting_Started.pdf
2.5 Building Java programs - Recap
39
jGRASP – JGrasp02_Getting_Started.pdf
2.10 Compiling a Program: A Few More Details
When you compile the program, it is automatically
saved.
Settings > check box Auto Save
40
jGRASP – JGrasp02_Getting_Started.pdf
2.11 Running a Program: Additional
Run > check box Run in MSDOS Window
Run > Arguments
2.14 Closing a File
File > Close
|Close All
41
Exercises/Tasks
 Type, compile, run a program: Lesson01_a.java
publ ic class Lesson01_a {
public static void main(String args[]) {
System.out.print("ICosCIS partner AUBG greets");
System.out.println(" ICosCIS partner SWU.");
} // end of main
} // end of class
42
Exercises/Tasks
 Write a Java program Proba3.java:
 To display 5 times the string
“Good luck, dear ICoSCIS student!!”
 To enter two numeric integer/real values and
To display their sum and product.
43
Exercises/Tasks
for(int i=1; i<=5; i++){
System.out.print("Good luck, dear");
System.out.println(" ICoSCIS student!!");
}
44
Exercises/Tasks
import java.util.Scanner;
…
Scanner cin = new Scanner(System.in);
System.out.println("Enter two numeric values:");
double inp1, inp2, result1;
inp1 = cin.nextDouble();
inp2 = cin.nextDouble();
result1 = inp1 + inp2;
System.out.println(" result is = " + result1);
45
Exercises/Tasks
import java.util.Scanner;
public class Proba3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
for(int i=1; i<=5; i++)
System.out.println("Good luck, dear ICoSCIS student!!");
Scanner cin = new Scanner(System.in);
System.out.println("\n Enter two real numeric values:");
double inp1, inp2, result1;
inp1 = cin.nextDouble();
inp2 = cin.nextDouble();
result1 = inp1 + inp2;
System.out.println(" result of addition is = " + result1);
} // end of main
} // end of class
46
Creating, Compiling & Running
Java Programs
 From within IDE NetBeans



Details follow
NetBeans IDE Java Quick Start Tutorial
(http://netbeans.org/kb/docs/java/quickstart.html)
Introduction to GUI Building
(http://netbeans.org/kb/docs/java/guifunctionality.html
47
NetBeans – introduction
 NetBeans refers to both


NetBeans Platform
NetBeans IDE
 NetBeans Platform is a reusable framework for
simplifying the development of Java Swing desktop
applications.
 NetBeans IDE is an open-source industry style
integrated development environment. NetBeans IDE
supports development of all Java application types.
 Current installed NetBeans IDE version - 7.0.1
 Runs on Windows, Linux, Mac OS X and Solaris. 48
To create an IDE project:
 1. Start NetBeans IDE.
 2. In the IDE, choose File > New Project…
(Ctrl+Shift+N), as shown in the figure below.
49
To create an IDE project:
 3. In the New Project wizard, expand the Java
category and select Java Application as shown
in the figure below. Then click Next.
50
To create
an IDE
project:
 4. In the Name and Location page of the wizard, do
the following (as shown in the figure above):




In the Project Name field, type <PrjName> on your choice.
Leave the Use Dedicated Folder for Storing Libraries
checkbox unselected.
In the Create Main Class field, type
<PackageName>.<ClassName> on your choice (if it is empty).
51
Leave the Set as Main Project checkbox selected.
To create an IDE project:
 5. Click Finish.
The project is created and opened in the IDE. You should see the
following components:




The Projects window, which contains a tree view of the components of
the project, including source files, libraries that your code depends on,
and so on.
The Source Editor window with a file called <ClassName>.java open.
The Navigator window, which you can use to quickly navigate between
elements within the selected class.
The Tasks window, which lists compilation errors as well other tasks
52
that are marked with keywords.
Adding Code to the Generated
Source File
 Because you have left the Create Main Class checkbox selected in the New
Project wizard, the IDE has created a skeleton main class for you. You can
add the "Hello World!" message to the skeleton code by replacing the line:
// TODO code application logic here
with the line:
System.out.println("Hello World!");
 Save the change by choosing File > Save.
 The file should look something like the following code sample.
53
Adding Code to the Generated Source File
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworldapp;
/**
*
* @author <your name>
*/
public class HelloWorldApp {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
54
Compiling and running a project
 Because of the IDE's Compile on Save feature, you do
not have to manually compile your project in order to
run it in the IDE. When you save a Java source file,
the IDE automatically compiles it. (how to switch this
option off, see Project > Properties > Compiling).
 To run the program:


Choose Run > Run Main Project
(F6).
The figure below shows what you should now see.
55
Compiling and running a project
 If there are compilation errors, they are marked with
red glyphs in the left and right margins of the Source
Editor.


The glyphs in the left margin indicate errors for the
corresponding lines.
The glyphs in the right margin show all of the areas of the
file that have errors, including errors in lines that are not
visible.
 You can mouse over an error mark to get a description
of the error.
 You can click a glyph in the right margin to jump to the
line with the error.
56
Compiling and running a project
 Here are more options to process the project:
 To test the program:


Choose Run > Test Project(<prj name>)
(Alt+F6)
This is unit testing in Java using JUnit framework.
For more details see lesson 7.
57
Compiling and running a project
 Here are more options to process the project:
 To build manually (without run) the program:



Choose Run > Build Main Project
(F11)
Try the command to know what you should now see.
Open the Output window (if it is closed) and have a
look at the report generated in it.
58
Compiling and running a project
 Here are more options to process the project:
 To establish project settings:

Choose Run > Set Project Configuration >
• <default setting>
• Customize…


Try the command to know what you should now see.
Project Properties screen gets opened – you are free to
manipulate/establish/modify current project parameters.
59
Compiling and running a project
 Here are more options to process the project:
 To establish Main project settings:

Choose Run > Set Main project >
• None
• Select among all projects for the current NetBeans session


Try the command to know what you should now see.
List of existing projects gets displayed and you are to
select/set the main project for the current session.
60
Compiling and running a project
 Here are more options to process the project:
 To create archive (.jar) file for the program:




Choose Run > Clean and Build Main Project (Shift+F11)
Try the command to know what you should now see.
Open the Output window (if it is closed) and have a
look at the report generated in it.
For details see next slide.
61
Building and deploying the application (.jar file)
 Once you have written and test run your application, you can use
the Clean and Build command to build your application for
deployment. When you use the Clean and Build command, the
IDE runs a build script that performs the following tasks:


Deletes any previously compiled files and other build outputs.
Recompiles the application and builds a JAR file containing the compiled
files.
 To build your application:

Choose Run > Clean and Build Main Project (Shift+F11)
 You can view the build outputs by opening the Files window and
expanding the <PrjName> node. The compiled bytecode file
<PrjName>.class is within the build/classes/<ClassName>
subnode. A deployable JAR file that contains the
<PrjName>.class is within the dist node.
62
Building and deploying the application (.jar file)
.
.
63
Create javadoc
 To be discussed in separate lesson
64
Tips for NetBeans users
 The Compile on Save feature can be turned off in the
Project Properties window. Right-click your project,
select Properties. In the Properties window, choose
the Compiling tab. The Compile on Save checkbox is
right at the top.
 Note that in the Project Properties window you can
configure numerous settings for your project: project
libraries, packaging, building, running, etc.
65
Exercises/Tasks
 Write a Java program to test the options for
the main menu Run command:
 To display 5 times the string
“Good luck, dear ICoSCIS student!!”
 To enter two numeric integer/real values and
To display their sum and product.
66
Exercises/Tasks
 Write a Java program to test the command-line
arguments option
 How to specify arguments

Right-click your project, select Properties. In the Properties
window, choose the Run tab. Enter arguments
 How to access arguments
public static void main(String[] args){
for (int i=0; i<args.length; i++)
System.out.println(args[i]);
}
67
Exercises/Tasks
 How to access arguments, second more reliable version
public static void main(String[] args) {
System.out.println("Command line arguments:");
if (args.length >0){
for(int i=0; i<args.length; i++)
System.out.println(args[i]);
}
else
System.out.println(" No cmd line arguments");
}
68
Exercises/Tasks
 Write a Java program to test the command-line
arguments option
 Run from within NetBeans
 Run as a separate OS command
java –jar Application.rar
1111 2222 333
69
Running JAVA
in
UNIX/Linux Environment
Logging In to UNIX/Linux
Practice
• Login
–
–
PuTTY IP address: 194.141.86.251
PuTTY Host Name: webmonitor.swu.bg
• Basic UNIX commands
–
ls, pwd, mkdir, cd, nano-editor, man, cp, mv, rm
• Java related commands
–
–
–
Java compiler: javac
Java Virtual Machine: java
Java utilities: jar, javadoc, jdb
Thank You
For
Your Attention!
73
Download