Presentation is loading. Please wait.

Presentation is loading. Please wait.

Building Java programs using Command Line Window

Similar presentations


Presentation on theme: "Building Java programs using Command Line Window"— Presentation transcript:

1 Building Java programs using Command Line Window
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 03 Title: Building Java programs using Command Line Window Reference: 1

2 Lecture Contents: Anatomy of a Java program (reminder)
More on elementary Java Input/Output dialogs Programming Style and Documentation Building Java programs using DOS command lines

3 A Simple Java Program Listing 1.1
//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

4 Two More Simple Examples
WelcomeWithThreeMessages Run ComputeExpression Run

5 Anatomy of a Java Program
Class name Main() method Statements Statement terminator Reserved words Comments Blocks

6 Class Name Every Java program must have at least one class. Each class has a name. By convention, class names start with an uppercase letter. In this example, the class name is Welcome. //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

7 Main Method Line 2 defines the main method. In order to run a class, the class must contain a method named main. The program is executed from the main() method. //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

8 Statement A statement represents an action or a sequence of actions. The statement System.out.println("Welcome to Java!"); in the program below is a statement to display the greeting "Welcome to Java!“. //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

9 Statement Terminator Every statement in Java ends with a semicolon (;). //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

10 Reserved words Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

11 Blocks A pair of braces in a program forms a block that groups components of a program.

12 Don’t confuse names parentheses, curly braces, square brackets, and angle brackets
Punctuation Name Typical use Alternate names ( ) Parentheses Round brackets { } Curly braces Curly brackets [ ] Square brackets Box brackets, Square braces < > Angle brackets Chevron is <> with nothing in Java Programming, Fifth Edition

13 Special Symbols

14 { … } // This program prints Welcome to Java! public class Welcome {
{ … } // This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

15 ( … ) // This program prints Welcome to Java! public class Welcome {
( … ) // This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }

16 ; // This program prints Welcome to Java! public class Welcome {
public static void main(String[] args) { System.out.println("Welcome to Java!"); }

17 // … // This program prints Welcome to Java! public class Welcome {
public static void main(String[] args) { System.out.println("Welcome to Java!"); }

18 " … " // This program prints Welcome to Java! public class Welcome {
public static void main(String[] args) { System.out.println("Welcome to Java!"); }

19 Programming Style and Documentation
Appropriate Comments Naming Conventions Proper Indentation and Spacing Lines Block Styles

20 Appropriate Comments Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. Include your name, class section, instructor, date, and a brief description at the beginning of the program.

21 Naming Conventions Choose meaningful and descriptive names.
Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea. Class names: Capitalize the first letter of each word in the name. For example, the class name ComputeArea, and the class name ComputeExpression. Constants: Capitalize all letters in constants, and use underscores to connect words. E.g. the constant PI, and MAX_VALUE

22 Proper Indentation, Spacing, Block Styles
Indent two spaces. Spacing Use blank line to separate segments of the code. Use end-of-line style for braces.

23 . More on Elementary Java

24 JOptionPane - Input For now Two ways of obtaining input are to be discussed. Using the Scanner class (console input) And methods like nextInt(), nextDouble(), hasNext(), … Using JOptionPane input dialogs And method showInputDialog() – to introduce now

25 Problem: Computing Loan Payments
This program lets the user enter the interest rate, number of years, and loan amount, and computes monthly payment and total payment. ComputeLoan Run

26 Getting Input from Input Dialog Boxes
String inp; inp=JOptionPane.showInputDialog("Enter an input"); // OR String inp = JOptionPane.showInputDialog( "Enter an input");

27 Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog( null, “Prompting Message”, “Dialog Title”, JOptionPane.QUESTION_MESSAGE);

28 Converting Strings to Integers
The input returned from the input dialog box is a string. If you type a numeric value such as 123, it returns “123”. To obtain the input as a number, you have to convert a string into a number. To convert a string into an int value, you can use the static parseInt() method in the Integer class as follows: int intValue = Integer.parseInt(intString); where intString is a numeric string such as “123”.

29 Converting Strings to Doubles
To convert a string into a double value, you can use the static parseDouble() method in the Double class as follows: double doubleValue =Double.parseDouble(doubleString); where doubleString is a numeric string such as “123.45”.

30 Problem: Computing Loan Payments Using Input Dialogs
Same as the program for computing loan payments, except that the input is entered from the input dialogs and the output is displayed in an output dialog. ComputeLoanUsingInputDialog Run

31 JOptionPane - Output For now Two ways of sending output are to be discussed. Using the System class, the out object And methods System.out.print(), System.out.println() Using JOptionPane message dialogs And method showMessageDialog() – to introduce now

32 Displaying Text in a Message Dialog Box
you can use the showMessageDialog( ) method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel.”

33 The showMessageDialog Method
JOptionPane.showMessageDialog(null, "Welcome to Java!", "Display Message", JOptionPane.INFORMATION_MESSAGE);

34 What processing takes place?
. Building Java programs Or How Java works? What processing takes place?

35 Compiling Java Source Code
You can port a source program to any machine with appropriate compilers. The source program must be recompiled, however, because the object program can only run on a specific machine. Nowadays computers are networked to work together. Java was designed to run object programs on any platform. With Java, you write the program once, and compile the source program into a special type of object code, known as bytecode. The bytecode can then run on any computer with a Java Virtual Machine, as shown below. Java Virtual Machine is a software that interprets Java bytecode.

36

37 Executing a Java program

38 JVM emulation run on a physical machine

39 JVM handles translations

40 Java Popularity Pure Java includes 3 software facilities: JRE JVM JDK

41 The Java Runtime Environment (JRE) provides
the libraries, the Java Virtual Machine, and other components to run applets and applications written in Java.

42 JVM - Overview Java Virtual Machine is a program which executes certain other 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). JVMs are available for many hardware and software platforms. The use of the same bytecode for all JVMs on all platforms allows Java to be described as a write once, run anywhere programming language, versus write once, compile anywhere, which describes cross-platform compiled languages. Oracle Corporation, the owner of the Java trademark, produces the most widely used JVM, named HotSpot, that is written in the C++ programming language.

43 JRE – Execution Environment
Oracle's Java execution environment is termed the Java Runtime Environment, or JRE. Programs intended to run on a JVM must be compiled into Java bytecode, a standardized portable binary format which typically comes in the form of .class files (Java class files). A program may consist of many classes in different files. For easier distribution of large programs, multiple class files may be packaged together in a .jar file (short for Java archive). The Java application launcher, java, offers a standard way of executing Java code. The JVM runtime executes .class or .jar files, emulating the JVM instruction set by interpreting it or using a just-in-time compiler (JIT) such as Oracle's HotSpot. JIT compiling, not interpreting, is used in most JVMs today to achieve greater speed

44 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).

45 its primary components
JDK contents The JDK has as its primary components a collection of programming tools, including:

46 JDK contents 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. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, no longer comes with Sun JDK, and instead it has been replaced by this new java loader. 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.

47 JDK contents (cont.) javah – the C header and stub generator, used to write native methods javap – the class file disassembler javaws – the Java Web Start launcher for JNLP applications JConsole – Java Monitoring and Management Console jdb – the debugger jhat – Java Heap Analysis Tool (experimental) jinfo – This utility gets configuration information from a running Java process or crash dump. (experimental) jmap – This utility outputs the memory map for Java and can print shared object memory maps or heap memory details of a given process or core dump. (experimental) jps – Java Virtual Machine Process Status Tool lists the instrumented HotSpot Java Virtual Machines (JVMs) on the target system. (experimental) jrunscript – Java command-line script shell

48 JDK contents (cont.) jstack – utility which prints Java stack traces of Java threads (experimental) jstat – Java Virtual Machine statistics monitoring tool (experimental) jstatd – jstat daemon (experimental) keytool – tool for manipulating the keystore pack200 – JAR compression tool policytool – the policy creation and management tool, which can determine policy for a Java runtime, specifying which permissions are available for code from various sources VisualVM – visual tool integrating several command-line JDK tools and lightweight[] performance and memory profiling capabilities wsimport – generates portable JAX-WS artifacts for invoking a web service. xjc – Part of the Java API for XML Binding (JAXB) API. It accepts an XML schema and generates Java classes

49 Creating, Compiling, and Running Programs

50 Creating, Compiling & Running Java
How is the required processing realized? From the Command Line Window From within IDEs

51 Creating, Compiling and Running Java from Command Line Window
First: to open a Command Window Click Start; Select Run…; Type cmd Second: to create a separate directory/folder on C: drive or Q: drive where to save .java and .class files md INF120Progs cd INF120Progs Third: to Set path to JDK bin directory Already done by OCC Fourth: to create and save Java source file Notepad/Write Welcome.java Fifth: to Compile javac Welcome.java Sixth: to Run java Welcome

52 Creating and Editing Using NotePad
To use NotePad, type notepad Welcome.java from the DOS prompt.

53 Creating and Editing Using WordPad
To use WordPad, type write Welcome.java from the DOS prompt.

54 Creating, Compiling, and Running Java Programs
In order to compile your Java program, you should type javac Welcome.java In order to run your compiled to bytecode Java program, you should type java Welcome

55 Creating, Compiling, and Running Java Programs
Training session: Create, compile and run the Java version of the “Hello, World!!!” program

56 Saving, Compiling, and Running, and Modifying a Java Application
Saving a Java class Save class in file with exactly same name and .java extension For public classes Class name and filename must match exactly Compiling a Java class Compile source code into bytecode Type javac First.java Translate bytecode into executable statements Using Java interpreter Type java First Java Programming, Fifth Edition 56 56

57 Saving, Compiling, and Running and Modifying a Java Application (continued)
Compilation outcomes Javac unrecognized command Program language error messages No messages indicating successful completion Reasons for error messages Misspelled command javac Misspelled filename Not within correct subfolder or subdirectory on command line Java not installed properly Java Programming, Fifth Edition 57 57

58 Running a Java Application
Class (file named First.class as result/output of Java compilation) stored in folder named for example Java on C drive Or in folder INF120Progs on Q drive Run application from command line Type java First Shows application’s output in command window Java Programming, Fifth Edition 58 58

59 Modifying a Java Class TASK:
Modify text file that contains existing class Save file with changes Using same filename Compile class with javac command Interpret class bytecode and execute class using java command TASK: Modify your “Hello, world!” program to a program that displays your name, your address and your postal address, each topic on a new line on the screen. Java Programming, Fifth Edition 59

60 Creating a Java Application Using GUI Output
JOptionPane (import javax.swing.JOptionPane;) Produce dialog boxes Dialog box GUI object resembling window Messages placed for display Package Group of classes The import statement Use to access built-in Java class Java Programming, Fifth Edition 60 60

61 Creating Java Application Using GUI Output
TASK: Modify your “Hello, world!” program to a program that displays your name, your address and your postal address, each topic on a new output message dialog box. Java Programming, Fifth Edition 61 61

62 Creating a Java Application Using GUI Output
import javax.swing.JOptionPane; public class FirstDialog { public static void main(String[] args) JOptionPane.showMessageDialog(null,”First Java dialog"); } Java Programming, Fifth Edition 62 62

63 Correcting Errors and Finding Help
First line of error message displays: Name of file where error found Line number Nature of error Next lines identify: Symbol Location Compile-time error Compiler detects violation of rules Refuses to translate class to byte code. Java Programming, Fifth Edition 63 63

64 Correcting Errors and Finding Help (continued)
Parsing Process compiler uses to divide source code into meaningful portions Logic error Syntax correct but produces incorrect results when executed Usually more difficult to find and resolve Java API Also called the Java class library Prewritten Java classes Java Programming, Fifth Edition 64 64

65 You Do It – training session
Your first application Compile and run file First.java Compile and run file FirstDialog.java (for more details see next slide) Try to compile and run file ErrorTest.java Adding comments to a class Modifying a class Java Programming, Fifth Edition 65 65

66 You Do It – training session
Creating a dialog box Compile and run file FirstDialog.java Modify program to produce two dialog boxes JOptionPane.showMessageDialog(null, "First Java dialog"); JOptionPane.showMessageDialog(null, "Second Java dialog"); Modify program to produce three dialog boxes JOptionPane var = new JOptionPane(); var.showMessageDialog(null, "Third Java dialog"); Java Programming, Fifth Edition 66 66

67 The jar utility pp 68-80

68 What is JAR? Java archive file can be used to group all the project files in a compressed file for deployment. The Java archive file format (JAR) is based on the popular ZIP file format.

69 The jar utility JAR stands for Java ARchiver and it is used to compress and archive one or more files. It is equivalent to Zip file in Window OS. A typical .jar file contains Java class files in addition to source files as well as resource files, like images and properties. Let us see how to create A regular Java archive (.jar) file and A self-Executable Java archive file. An archive self executable file is nothing but a .jar file along with a manifest info containing the entry point of the Application specified in the form of class name. For example, consider the following Java source files.

70 The jar utility – regular archive file
// File prog44.java: import java.util.Scanner; public class prog44 { public static void main(String[] args) { int a, b, c; Scanner cin = new Scanner(System.in); System.out.println("Enter two integers:"); a = cin.nextInt(); b = cin.nextInt(); c = a + b; System.out.println("Result is = " + c); System.out.println("Factoriel of result is " + factr(c)); } static int factr(int n) { if (n==0) return 1; else return n*factr(n-1);

71 The jar utility We must build the corresponding .class file using javac compiler. javac prog44.java This is the only class and it contains the main() method Now, let us see how to create the regular jar comprising the above class. Java utility called jar.exe contains options for creating, listing, updating the jar file. Q:\>jar cvf prog44.jar prog44.class In the above command, the options can be interpreted as follows, c - to create the archive file v – to give verbose output during the jar file creation f – the name of the jar file, ‘prog44.jar'

72 The jar utility Some more options:
t – list table of contents for archive x – extract named (or all) files from archive To list the contents of archive file, type command: Q:\>jar tf prog44.jar To extract files from archive, type command: Q:\>jar xf prog44.jar

73 The jar utility Now to list down the contents of the jar file, we have to use the 't' option along with 'v' and 'f' options, Q:/>jar tvf prog44.jar The above command will list down the contents of prog44.jar (including directories and files).

74 Viewing the Contents of a JAR File
You can view the contents of a .jar file using WinZip.

75 The jar utility To extract the contents of a .jar file to the current working directory, we can use the 'x' option as used in the following command, Q:\>jar xvf prog44.jar

76 The jar utility- self executable archive file
File ProgGeometricObject.java: We must build the corresponding .class file(s) using javac compiler. javac ProgGeometricObject.java There are four .class files generated by the compiler: Circle.class GeometricObject.class ProgGeometricObject.class – (includes main() method) Rectangle.class Now, let us see how to create the self executable jar comprising the above classes. When we invoke jar, we must point the entry point of the application using another option

77 jar utility- self executable archive file
e – specify application entry point for stand-alone application bundled in executable .jar file To create self executable .jar file, type the command: Q:\>jar cvfe Archive2.jar ProgGeometricObject *.class To create regular .jar file, type command: Q:\>jar cvf Archive1.jar *.class Compare both Archive1 and Archive2 .jar files

78 The jar utility- self executable archive file
To run self executable .jar file, application we have to specify the '-jar' option like this command Q:\>java –jar Archive2.jar OR First: extract files and Second: run JVM Q:\>jar xf Archive2.jar Q:\>java ProgGeometricObject

79 The jar utility- self executable archive file
To run self executable .jar file, type command Q:\>java –jar Archive1.jar No success Archive1.jar has no specified entry point and therefore cannot consider it as self-executable archive file.

80 Practical session 5 Write a Java program to read a positive integer value n and to display: The first n elements of the Fibonacci series Save the source texts as Prog55.java Build the corresponding .class file using javac compiler. javac prog55.java Run the program using java prog55 Build an archive file using jar utility. jar cvf prog55.jar prog55.class Run the program through the archive file java –jar prog55.jar

81 Thank You For Your Attention! Any Questions?


Download ppt "Building Java programs using Command Line Window"

Similar presentations


Ads by Google