Talk:Java Training Course/JT04: Difference between revisions

From tehowiki
Jump to navigation Jump to search
imported>Gfis
Created page with " georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 4 24 georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 -4 -8 georg@nunki:~/work/project/bekasi/JTC$ java DupInt 0..."
 
imported>Gfis
No edit summary
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
Complete program:
public class DupInt {
    public static void main(String[] args) {
        int st0 = Integer.parseInt(args[0]); // the 1st argument on the commandline
        int st1 = Integer.parseInt(args[1]); // the 2nd ...
        int st2 = st0 + st1;
        st2 = st2 + st2 + st2 + st2;
        System.out.println(st2);
    } // main
} // DupInt
Output with different arguments:
  georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 4
  georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 4
24
  24
  georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 -4
  georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 -4
  -8
  -8
Line 8: Line 20:
  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
  at DupInt.main(DupInt.java:3)
  at DupInt.main(DupInt.java:3)
<code>parseInt(String)</code> is a <code>static</code> method in the Java class <code>java.lang.Integer</code> which attempts to convert a <code>String</code> and return an <code>int</code>. It fails if the <code>String</code> does not have the proper syntax of an <code>int</code>. We will later learn how to prevent this hard failure of the program by using a <code>try { ... } catch</code> block around sensible operations.

Latest revision as of 10:05, 24 September 2017

Complete program:

public class DupInt {
    public static void main(String[] args) {
        int st0 = Integer.parseInt(args[0]); // the 1st argument on the commandline
        int st1 = Integer.parseInt(args[1]); // the 2nd ...
        int st2 = st0 + st1;
        st2 = st2 + st2 + st2 + st2;
        System.out.println(st2);
    } // main
} // DupInt

Output with different arguments:

georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 4
 24
georg@nunki:~/work/project/bekasi/JTC$ java DupInt 2 -4
-8
georg@nunki:~/work/project/bekasi/JTC$ java DupInt 0 -1
-4
georg@nunki:~/work/project/bekasi/JTC$ java DupInt
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
	at DupInt.main(DupInt.java:3)

parseInt(String) is a static method in the Java class java.lang.Integer which attempts to convert a String and return an int. It fails if the String does not have the proper syntax of an int. We will later learn how to prevent this hard failure of the program by using a try { ... } catch block around sensible operations.