Dr. Mark Humphrys

School of Computing. Dublin City University.

Online coding site: Ancient Brain

coders   JavaScript worlds

Search:

Free AI exercises


Java programs

Partially based on the introductory Java course of Joe Morris.


Read stdin

 
// reads 2 numbers and adds them

import java.io.*;

public class prog 
{
  public static void main ( String[] args ) throws IOException 
  {
    // --- pick one: ------------------------------------------------------------------
    // BufferedReader in = new BufferedReader ( new InputStreamReader ( System.in ) );
       Console in = System.console();
    // --------------------------------------------------------------------------------

    System.out.print("Number 1: ");
    String n1s = in.readLine();
    int n1 = Integer.parseInt( n1s );	// convert string to integer

    System.out.print("Number 2: ");
    String n2s = in.readLine();
    int n2 = Integer.parseInt( n2s );

    int sum = n1 + n2;

    System.out.println ( n1 + " + " + n2 + " = " + sum );
  }
}


Notes:

  1. Console needs Java 1.6
  2. Basic data types - int, double, boolean, char, String
  3. Operators
  4. throw and catch Exceptions


Control flow

 

// enter two integers and output the larger
// integers come in as command-line parameters:
// $ java prog n1 n2

public class prog 
{
  public static void main ( String[] args ) 
  {
    int n1 = Integer.parseInt( args[0] );
    int n2 = Integer.parseInt( args[1] );

    if ( n1 > n2 )
    {
     System.out.println ( n1 ); 
    }
    else
    {
     System.out.println ( n2 ); 
    }

  }
}


Notes:

  1. Control Flow Statements


When { } enclose single statement can omit them:


 
    if ( n1 > n2 )
     System.out.println ( n1 ); 
    else
     System.out.println ( n2 ); 


Other control flow statements include while, for:


 
// print squares of numbers 0 to 50

public class prog 
{
  public static void main ( String[] args ) 
  {
    for ( int i=0; i <= 50; i++ ) 
     System.out.println ( i * i  ); 
  }
}




Real numbers

 
// print square roots of numbers 0 to 50

public class prog 
{
  public static void main ( String[] args ) 
  {
    for ( int i=0; i <= 50; i++ ) 
    {
     double r = Math.sqrt(i);

     // System.out.println ( r  );     	 // default formatting (variable no. of decimal places)

     System.out.format ( "%.4f \n", r  );      // 4 decimal places

    }
  }
}


Notes:

  1. Math class and methods
  2. formatting
  3. capture stdout to file:
    program > file
    

  4. Above will work for UNIX/Linux. For new lines for DOS/Windows might need:
         System.out.format ( "%.4f \r\n", r  );   
    

  5. Platform independent:
         System.out.format ( "%.4f", r  );   
         System.out.println();
    



Exercise

Write a program called cuberoot.java, which takes a command-line argument n, and then for the integers i = 1 to n, prints on a separate line i and the cube root of i. If n is less than 1, or is not an integer, or is greater than 1000, it prints an error.


String

Examples:


String s "Dublin"
s.length() 6
s.charAt(2) 'b' [indexed 0,1,2, ...]
s.substring(2,5) "bli" [2 to 4]
s.substring(2) "blin" [2 to end]
s.indexOf("bli") 2
s.indexOf("cat") -1
s.startsWith("Dub") true
s.startsWith("dub") false [case matters]
s.toUpperCase() "DUBLIN"
s.trim() "Dublin" [already trimmed]




Methods

 
// my class with a main method
// and one defined method  

public class myclass 
{

  // fn returns maximum of 3 numbers 
  static int fn ( int i, int j, int k )
  {
   if ( i>=j && i>=k )   
            return i;
        else if ( j>=i && j>=k )    
            return j;
        else   
            return k;
  }


  public static void main ( String[] args ) 
  {
     int a = Integer.parseInt( args[0] );
     int b = Integer.parseInt( args[1] );
     int c = Integer.parseInt( args[2] );

     System.out.println ( fn(a,b,c) );     
  }

}


Notes:

  1. OO introduction




Arrays

 
public class myclass 
{
  public static void main ( String[] args ) 
  {
   int n = args.length;
   int[] a = new int [ n ];     // a = array of size n

  // read args (array of strings) into array of integers:

   for ( int i=0; i < n; i++ ) 
     a[i] = Integer.parseInt( args[i] );
   
  // print in reverse order:

   for ( int i=(n-1); i >= 0; i-- ) 
     System.out.print ( a[i] + " " );   

   System.out.print("\n");  
  }

}


Notes:

  1. Arrays




Objects

Define an object called Point (2-D point).
Takes args x and y.
Default display output is "(x,y)".


 
class Point
{
 private double x, y;

 Point ( double xarg, double yarg )   // constructor
 {
  x = xarg;
  y = yarg;
 }

 void print()
 {
  System.out.format ( "(%.4f,%.4f)", x, y );
 }
}


class prog 
{
  public static void main ( String[] args ) 
  {
    Point p = new Point ( 1.5, 4.33778 );
    p.print();
    System.out.print("\n");
  }
}


Notes:

  1. Objects
  2. edit as prog.java
  3. javac prog.java makes two files:
    Point.class
    prog.class
    
  4. java prog looks for main() in prog.class and runs it




Exceptions

 
public class prog 
{
  public static void main ( String[] args ) 
  {
    try
    {
     int x = 5 / 0;
     System.out.println("Divide by zero worked!");
    }
    catch ( Exception e )
    {
     System.out.println("Error handling here.");
    }

    System.out.println("Program didn't crash.");
  }
}


Notes:

  1. Exceptions




Inheritance

 
class Book 
{
    private String author;
    private String title;

    Book ( String a, String t ) 
    {   
        author = a; 
	  title = t;
    }

    void print() 
    {
        System.out.print ( "\"" + title + "\" by " + author );
    }
}


class TextBook extends Book       // sub-class
{
    private int level;

    TextBook ( String a, String t, int l ) 
    { 
        super(a,t);       // call constructor of super-class
        level = l;
    }

    void print() 
    {
        super.print();    // call method of super-class
        System.out.print ( " (Level " + level + ")" );
    }
}


public class prog 
{
  public static void main ( String[] args ) 
  {      
    Book b = new Book ( "C.Darwin", "Origin of Species" );
    TextBook t = new TextBook ( "J.Prof", "Introduction to Biology", 3 );

    b.print(); System.out.print("\n");
    t.print(); System.out.print("\n");
  }
}


Notes:

  1. Inheritance
  2. Characters (printing double-quotes)




That's all for now!

This is not a full introductory course in Java.
These brief notes are to get you to understand roughly what you have to do to get up to speed in Java for the other modules.

You should now be able to find out:

Bookmark all the links I have shown you so far.

It's up to you now!



ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.      New 250 G VPS server.

Note: Links on this site to user-generated content like Wikipedia are highlighted in red as possibly unreliable. My view is that such links are highly useful but flawed.