A Simple Java Program
A Simple Java Program
DEVESH VARSHNEY
09211006
CS IDD
E4 1
Java Program Structure
• In the Java programming language:
– A program is made up of one or more classes
– A class contains one or more methods
– A method contains program statements
– Program statements can reference local or instance
variables. There is no concept of global variable.
2
Java Program Structure
class body
3
Java Program Structure
4
Comments
• Comments in a program are called inline documentation
• They should be included to explain the purpose of the program and
describe processing steps
• They do not affect how a program works
• Java comments can take three forms:
5
Identifiers
• Application
– Executes when you use the java command to
launch the Java Virtual Machine (JVM)
• Sample program
– Displays a line of text
– Illustrates several important Java language
features
7
• Welcome1.java
Outline
1. //Prog.1: Welcome1.java
2. //Text-printing program
3.
4. public class Welcome1
5. {
6. //main method begins execution of Java application
7. public static void main(String args[])
8. {
9. System.out.println(“Welcome to Java Programming!”);
10.
11. }//end method main
12.
13. }//end class Welcome1
8
First Program in Java: Printing a Line of Text (Cont.)
1 // Prog.1: Welcome1.java
9
First Program in Java: Printing a Line of Text (Cont.)
– Saving files
• File name must be class name with .java extension
• Welcome1.java
5 {
– Left brace {
• Begins body of every class
• Right brace ends declarations (line 13)
10
First Program in Java: Printing a Line of Text (Cont.)
8 {
11
2.2 First Program in Java: Printing a Line of Text (Cont.)
12
First Program in Java: Printing a Line of Text (Cont.)
13
First Program in Java: Printing a Line of Text (Cont.)
• Compiling a program
– Open a command prompt window, go to directory
where program is stored
– Type javac Welcome1.java
– If no syntax errors, Welcome1.class created
• Has bytecodes that represent application
• Bytecodes passed to JVM
14
First Program in Java: Printing a Line of Text (Cont.)
• Executing a program
– Type java Welcome1
• Launches JVM
• JVM loads .class file for class Welcome1
• .class extension omitted from command
• JVM calls method main
15
Executing Welcome1 in a Microsoft Windows Command Prompt window.
16
Displaying Text with printf
• System.out.printf
– Feature added in Java SE 5.0
– Displays formatted data
9 System.out.printf( "%s\n%s\n",
10 "Welcome to", "Java Programming!" );
– Format string
• Fixed text
• Format specifier – placeholder for a value
– Format specifier %s – placeholder for a string
17
THANK YOU
18