What's written in println in Java





content

  1. Compile and start the Java program
  2. Example: polymorphism
  3. Example: input / output of text
    1. Command line application
    2. Graphic dialog
    3. Applet (for embedding in HTML page)
  4. Sample applet: graphical text output
  5. Example application: display system properties
  6. Example application: reading and writing a text file
  7. Example application: Serialization of a vector with a binary file
  8. Example: Start dynamically selected class at runtime
  9. More Java topics (with more examples)


Compile and start the Java program

  1. Install the Java JDK as described in java-install.htm.
  2. Set up the environment variables '', '' and '' in the environment as described in java-install.htm.
  3. Save Java source code in a file with the same name as the class name with the file extension .java (e.g.).
  4. Compile with:

  5. Java applications and applets are started differently (see also examples below).
    Java applications start with:

    Integrate Java applets in the HTML page and start with:

    (or load it into a web browser, if the JDK version fits, see java-plugin.htm).
    A simple HTML page can look like this, for example:
  6. You can also compile and run all of the examples in Eclipse. To do this, proceed as described under: ''.


Example: polymorphism

Create a project directory, for example: ''.

Save the following file in this directory:

import java.util.Vector; abstract class figure {abstract double getFlaeche(); } class rectangle extends figure {private double a, b; public rectangle (double a, double b) {this.a = a; this.b = b; } public double getFlaeche() {return a * b; }} class circle extends figure {private double r; public circle (double r) {this.r = r; } public double getFlaeche() {return Math.PI * r * r; }} public class polymorphism {public static void Main(String [] args) {double area = 0; // Instantiate figure objects: rectangle re1 = new rectangle (3, 4); Figure re2 = new rectangle (5, 6); Circle kr1 = new circle (7); Figure kr2 = new circle (8); Vector vec = new Vector (); // Add any number of figures: vec.add (re1); vec.add (re2); vec.add (kr1); vec.add (kr2); // Calculate the sum of the areas of all figures: for (int i = 0; i Figure f = (figure) (vec.get (i));area + = f.getFlaeche (); } System.out.println ("Total area is:" + area); }}

Open a command line window (under Windows XP: 'Start' | 'All Programs' | 'Accessories' | 'Command Prompt') and enter the following commands (under Windows XP you can mark the command text in the web browser with the mouse button pressed, with '' cache and run somewhere in the command line window with the right mouse button, `` and ''):

Documentation on '' and '' can be found under
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html and
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#PI.



Example: Text input / output as a command line application, as a graphic dialog and as an applet

Command line application

Create a project directory, for example: ''.

Save the following file in this directory:

import java.io. *; public class TextInOutput1 {public static void Main(String [] args) {System.out.println ("Enter text and finish with return:"); try { BufferedReader in = new BufferedReader (new InputStreamReader (System.in));String s = in.readLine ();System.out.println("The text read is:" + s ); } catch (IOException ex) {System.out.println (ex.getMessage ()); }}}

Open a command line window (under Windows XP: 'Start' | 'All Programs' | 'Accessories' | 'Command Prompt') and enter the following commands (under Windows XP you can mark the command text in the web browser with the mouse button pressed, with '' cache and run somewhere in the command line window with the right mouse button, `` and ''):

Documentation on '' and '' can be found under
java-io.htm,
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html and
http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html.

Graphic dialog

Save the following file in the directory:

import java.awt. *; import java.awt.event. *; public class TextEinAusgabe2 extends Frame {TextField input; Label issue; public static void Main(String [] args) {TextEinAusgabe2 meinFenster = new TextEinAusgabe2 ("text input / output"); meinFenster.setSize (400, 200); myWindow.setVisible (true); } public TextInOutput2(String windowTitle) {super (windowTitle); Label hint = new Label ("Enter text and complete with return"); input = new TextField ();output = new Label (); add (BorderLayout.NORTH, input); add (BorderLayout.CENTER, note); add (BorderLayout.SOUTH, out); input.addActionListener ( new ActionListener () {public void actionPerformed (ActionEvent ev) { myMethod (); }}); addWindowListener (new WindowAdapter () {public void windowClosing (WindowEvent ev) {dispose (); System.exit (0);}}); } void my method() { output.setText("The text read is:" + input.getText() ); } }

Enter the following commands in the command line window:

Check out the API Javadoc on '', '', '' and ''.


Applet (for embedding in HTML page)

Save the following file in the directory:

import java.applet.Applet; import java.awt. *; import java.awt.event. *; public class TextEinAusgabe3 extends Applet {TextField input; Label issue; public void init() {Label hint = new Label ("Enter text above and complete with Return"); input = new TextField ("");output = new Label (); setLayout (new BorderLayout ()); add (BorderLayout.NORTH, input); add (BorderLayout.CENTER, note); add (BorderLayout.SOUTH, out); input.addActionListener ( new ActionListener () {public void actionPerformed (ActionEvent ev) { myMethod (); }}); } void my method() { output.setText("The text read is:" + input.getText () ); } }

Save the following file in the same directory:

<applet code = "TextEinAusgabe3.class" width = 350 height = 80>

Enter the following commands in the command line window:

If the last command does not work, either no Java or a Java version that is too old is registered in the web browser. For more information, see java-plugin.htm and http://www.oracle.com/technetwork/java/index-jsp-141438.html.

Please note that in the previous example '' was derived from '', while this class was '' derived from ''.



Sample applet: graphic text output and parameter transfer

Save the following file in the directory:

import java.applet.Applet; import java.awt. *; public class FirstHello extends applet {Font f1 = new Font ("Helvetica", Font.BOLD, 11); Font f2 = new Font ("Helvetica", Font.BOLD, 48); Color c1 = new color (255, 0, 0); Color c2 = new color (0, 0, 255); String s; public void init () {// take parameters from HTML file:s = getParameter ("string"); } public void paint (Graphics g) {g.setColor (c1); if (null == s || 0> = s.length ()) {g.setFont (f1); g.drawString ("No 'string' found:" + "The applet was probably started without an HTML file.", 50, 65); } else { g.setFont (f2); g.drawString (s, 50, 65); } g.setColor (c2); g.drawOval (20, 0, 205, 95); } }

Save the following file in the same directory:

Output of a Java applet:

<applet code = "FirstHello.class" width = 250 height = 100> <param name = "string" value = "hello!">

Please activate Java support!

Enter the following commands in the command line window:



If the last command does not work, either no Java or a Java version that is too old is registered in the web browser. For more information, see java-plugin.htm and http://www.oracle.com/technetwork/java/index-jsp-141438.html.

Take a look at the API Javadoc for '', '', '', ''.

Example application: display system properties Save the following file in the directory: public class SystemProperties {public static void Main(String [] args) {System.out.println (

System.getProperties ()

.toString (). replace (',', '\ n') .replace ('{', '') .replace ('}', '')); }}



Enter the following commands in the command line window:

See the API Javadoc for '' and ''.

Example application: reading and writing a text file Save the following file in the directory: import java.io. *; import java.text. *; import java.util. *; public class ReadWriteText file {public static void Main(String [] args) {final String [] KEYS = {"user.name", "user.language", "user.home", "os.name", "java.version"}; Vector vec = new Vector (); String s; // Read lines of text from the file into a vector: try { BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream ("MyTextFile.txt"))); while (null! = (s = in.readLine ())) {vec.add (s); }} catch (FileNotFoundException ex) {} catch (Exception ex) {System.out.println (ex); } finally {if (in! = null) in.close (); } // If there was no file, create entries in the vector: if (0> = vec.size ()) {for (int i = 0; i BufferedWriter out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream ("MyTextFile.txt"))); for (int i = 0; i out.write (s, 0, s.length ());

out.newLine (); }} catch (IOException ex) {System.out.println (ex); } finally {if (out! = null) out.close (); }}}

Enter the following commands in the command line window:



Go to '' several times to see that the old timestamp has been read and the new one is added.

See the API Javadoc on '', '', '', '', '' and '' and ''.

Example application: Serialization of a vector with a binary file Save the following file in the directory: import java.io. *; import java.util.Vector; public class SerializeVector {public static voidMain(String [] args) {// Read my objects from a file into a Vector: Vector vecMyObjs = zero; try {ObjectInputStream in = new ObjectInputStream (new FileInputStream ("MyObjs.dat"));vecMyObjs = (Vector) in.readObject (); } catch (FileNotFoundException ex) {} catch (Exception ex) {System.out.println (ex); } finally {if (in! = null) in.close (); } if (vecMyObjs == null) vecMyObjs = new Vector (); // Do some intelligent stuff with vecMyObjs ... vecMyObjs.addElement (new String ("Hello" + vecMyObjs.size ())); System.out.println (vecMyObjs); // Write my objects into a file: try {ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("MyObjs.dat"));

out.writeObject (vecMyObjs);

out.flush (); } catch (IOException ex) {System.out.println (ex); } finally {if (out! = null) out.close (); }}}

Enter the following commands in the command line window:

Call '' several times to see that the previous '' object was saved and expanded correctly.



The command '' doesn't really make sense, but shows that this is a binary file.

See the API Javadoc on '', '', '', '' and ''.

Example: Start dynamically selected class at runtime

Create the package subdirectory '' in the '' directory. Save the following file in the directory: package mypckg; public class RunClassForName {public static void Main(String [] args) throws Exception {if (1> args.length) {System.out.println ("Class name (e.g. 'mypckg.MyClass1') required as a parameter."); System.exit (1); } Object obj = instantiateClassForName (args [0]); if (obj instanceof Runnable) ((Runnable) obj) .run (); else System.out.println (obj); } public static Object instantiateClassForName (String className) throws exception {class c =Class.forName(className); if (null == c) throw new Exception ("Error: Unable to access class '" + className + "'."); Object o = c. newInstance(); if (null == o) throw new Exception ("Error: Unable to create instance of class '" + className + "'."); return o; }} class MyClass1 implements Runnable {public void run() {System.out.println ("Execution of MyClass1.run ()"); }} class MyClass2 implements Runnable {public void

run()

{System.out.println ("Execution of MyClass2.run ()"); }}

Enter the following commands in the command line window:





See the API Javadoc for '', '' and ''.
A more detailed example including a search in the classpath can be found under ClassFinder.java.