Upload
conrad-armstrong
View
216
Download
2
Embed Size (px)
Citation preview
Lesson 1The Java World
AUBG ICoSCIS TeamAssoc. Prof. Stoyan Bonev
March, 23 - 24, 2013 SWU, Blagoevgrad
Time Schedule
March 23, Saturday - March 24, Sunday– 10:00 – 10:45 09:00 – 09:45– 11:00 – 11:45 10:00 – 10:45– 12:00 – 12:45 11:00 – 11:45
Lunch Break (45’) Lunch Break (45’)– 13:30 – 14:15 12:30 – 13:15– 14:30 – 15:15 13:30 – 14:15– 15:30 – 16: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 popularityHow Java works:
JRE, JVM, JDK
Windows Environment Java IDEs
UNIX/Linux EnvironmentFirst Java Program
5
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.
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
UNIXLinuxWindowsMAC OSMS-DOS
9
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
10
Source program compiler
data
Results Object program
Executing computer
Compile time Run time
11
Data
Results Source program
Interpreter
Compile time
Run time
12
Source program compiler
data
Results Object program in IL form
Interpreter
Compile1 time Compile2 time
Run time
1313Java Programming: From Problem Analysis to Program Design, 4e
How Java worksJava compiled to intermediate form – byte
code.
Byte code further processed: by interpreter named JVMORby JIT compiler.
Reminder and RefreshThe SDLC concept - see next slide
1414Java Programming: From Problem Analysis to Program Design, 4e
Problem-Analysis-Coding-Execution Cycle
15
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.
16
17
Executing a Java program
18
JVM emulation run on a physical machine
19
JVM handles translations
20
Java Components of special interest
Pure Java includes 3 software facilities:
JRE (includes JVM)
JVM (a part of JRE)
JDK
21
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.
22
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++
23
JVM JVM architecture.
Source code is compiledto Java bytecode, whichis verified, interpreted orJIT-compiled for thenative architecture. The Java APIs and JVMtogether make up theJava Runtime Environment(JRE).
24
JDK contents
The JDK has as
its primary components a collection
of programming tools, including:
25
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.
26
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
27
A Simple Java Program
//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!"); }}
Listing 1.1
28
A Simple Java Program
//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!"); }}
Listing 1.1
29
Creating, Compiling, and Running Java Programs
Source Code
Create/Modify Source Code
Compile Source Code i.e., javac Welcome.java
Bytecode
Run Byteode i.e., java Welcome
Result
If compilation errors
If runtime errors or incorrect result
public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
… 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
stored on the disk
Source code (developed by the programmer)
Byte code (generated by the compiler for JVM to read and interpret, not for you to understand)
Running JAVA inWindows Environment
31
Creating, Compiling & Running Java Programs
From the Command Window Details follow
32
To open command window
Click Start Select All Programs > Select Accessories Click Command Prompt
33
Compiling and Running Java programsUsing 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.
34
Compiling and Running Java programs
Run compiler with statement like this:
javac prog4.java
Run application with stmt like this:
java prog4
35
Creating, Compiling & Running Java Programs
From within IDE jGRASP Details follow
http://www.jgrasp.orghttp://www.jgrasp.org/
tutorials187/02_Getting_Started.pdf
36
jGRASP – introductionjGRASP 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.
37
jGRASP – JGrasp02_Getting_Started.pdf
2.1 Starting jGRASP
jGRASP virtual desktop gets displayed:menu bartool barleft pane – Browse tab, Find tab, Debug tablarge pane – for UML and CSD windowslower pane – Messages tab, run I/O tab
38
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
39
jGRASP – JGrasp02_Getting_Started.pdf
2.5 Building Java programs - Recap
40
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
41
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
42
Exercises/TasksType, 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
43
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.
44
Exercises/Tasks
for(int i=1; i<=5; i++){
System.out.print("Good luck, dear");
System.out.println(" ICoSCIS student!!");
}
45
Exercises/Tasksimport 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);
46
Exercises/Tasksimport 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
47
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/gui-functionality.html
48
NetBeans – introductionNetBeans 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.1Runs on Windows, Linux, Mac OS X and Solaris.
49
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.
50
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.
51
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).
Leave the Set as Main Project checkbox selected.
52
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 that are marked with keywords.
53
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.
54
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!"); }}
55
Compiling and running a projectBecause 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.
56
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.
57
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.
58
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.
59
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.
60
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.
61
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.
62
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.
63
Building and deploying the application (.jar file)
.
.
64
Create javadoc
To be discussed in separate lesson
65
Tips for NetBeans usersThe 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.
66
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.
67
Exercises/TasksWrite a Java program to test the command-line
arguments optionHow 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]);}
68
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");
}
69
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
Running JAVA inUNIX/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
73
Thank You For
Your Attention!