Download Simple Java Programs - Introduction to Programming in Java - Lecture Slides and more Slides Network security in PDF only on Docsity!
- Objectives
- give some simple examples of Java
applications and one applet
- Simple Java Programs
Contents
1. Steps in Writing a Java Application
2. Hello.java
3. A Better Programming Environment?
4. Comparison.java
5. Steps in Writing a Java Applet
6. WelcomeApplet.java
2. Hello.java
import java.io.*;
public class Hello
public static void main(String args[])
System.out.println(“Hello Andrew”);
} // end of class
Compile & Run
- The Java file (e.g. Hello.java) must contain a
public class with the file’s name (e.g. Hello
class).
continued
- System.out is the standard output stream
- like cout (C++) or stdout (C)
- System.out.println() is the main print
function (method) in Java.
Hello
main() calls
System.out.println(…)
writes to screen
via output stream
- Useful Notepad++ features
- it will format Java code automatically
- colour-coded display of code
- it is possible to add calls to javac, java,
appletviewer to the Notepad++ menu
- no need to leave the editor to compile/run
- there is an optional window that show the output
from running Java code
4. Comparison.java
import javax.swing.JOptionPane; // GUI dialogs
public class Comparison
public static void main( String args[] )
{ String firstNumber,secondNumber,result;
int number1,number2;
// read user numbers
firstNumber = JOptionPane. showInputDialog(
"Enter first integer:");
secondNumber = JOptionPane. showInputDialog (
"Enter second integer:" );
// convert numbers
number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber );
result = ""; if ( number1 == number2 ) result = number1 + " == " + number2; if ( number1 != number2 ) result = number1 + " != " + number2; if ( number1 < number2 ) result = result + "\n" + number1 + " < " + number2; if ( number1 > number2 ) result = result + "\n" + number1 + " > " + number2; if ( number1 <= number2 ) result = result + "\n" + number1 + " <= " + number :
Compile & Run$ javac Comparison.java
$ java Comparison
Notes
• The Comparison class is just a single
main() function (method)
continued
- Notice the use of familiar C/C++ control
structures (e.g. if, while) and data types
(e.g. int, double)
- “...” + “...” means concatenation
(put strings together)
- String is a pre-defined class for strings.
- int is a built-in type (just like C’s int).
Calling Methods
• Methods are defined in classes.
• Syntax for calling a method:
Class.method-name
or object.method-name
– e.g. JOptionPane.showMessageDialog( ...);
• this calls the showMessageDialog() method in the
class JOptionPane
Classes start
with an upper
case letter.