Lesson 2 CS 141

23
Lesson 2 CS &141 ECC © Niko Čulevski 1 Lesson #2 – Introduction to Java Applications 2.0 Introduction. The objective in this chapter is to write simple, well-written, neatly arranged Java application programs. Topics include input an output statements, data types, memory concepts, arithmetic operators, and decision-making statements. We begin by reading such programs. 2.1 Several Simple Programs. These sample programs are applications rather than applets. 2.1.1 HelloWorld. /** * HelloWorld.java * @author Niko Culevski * @version 1.0 */ public class HelloWorld { public static void main (String args[ ]) { System.out.println("Hello World!"); // just say Hello! } } output: run: Hello World! BUILD SUCCESSFUL (total time: 0 seconds) 2.1.1.1 The first five lines are comments (Javadoc compliant with @ tags for author and version) 2.1.1.2 public class HelloWorld declares a class (class heading) named HelloWorld. Since the class name is used as the base name for the file, the file name must be exactly the same as the class with java extension, i.e., HelloWorld.java. The keyword public is an access modifier—it means that other classes anywhere have access to HelloWorld. Other access modifiers include private, protected, and default (none). Of the four, only public and default are applicable to top-level classes (in other words, there is no such thing as a private or protected top-level—not inner—classes). Furthermore, a file cannot contain more than one public top-level class. 2.1.1.3 Class names begin with a capital letter (convention, not requirement) and must be nonempty string of letters, digits and underscores as long as they begin with a letter, underscore or “$” and contain no blanks. Java is case sensitive—upper and lower case letters differ. So HelloWorld Helloworld and System system.

description

Lesson 2 CS 141

Transcript of Lesson 2 CS 141

  • Lesson 2 CS &141

    ECC Niko ulevski 1

    Lesson #2 Introduction to Java Applications

    2.0 Introduction. The objective in this chapter is to write simple, well-written, neatly arranged Java application programs. Topics include input an output statements, data types, memory concepts, arithmetic operators, and decision-making statements. We begin by reading such programs.

    2.1 Several Simple Programs. These sample programs are applications rather than applets.

    2.1.1 HelloWorld. /** * HelloWorld.java * @author Niko Culevski * @version 1.0 */ public class HelloWorld { public static void main (String args[ ]) { System.out.println("Hello World!"); // just say Hello! } } output: run: Hello World! BUILD SUCCESSFUL (total time: 0 seconds)

    2.1.1.1 The first five lines are comments (Javadoc compliant with @ tags for author and version)

    2.1.1.2 public class HelloWorld declares a class (class heading) named HelloWorld. Since the class name is used as the base name for the file, the file name must be exactly the same as the class with java extension, i.e., HelloWorld.java. The keyword public is an access modifierit means that other classes anywhere have access to HelloWorld. Other access modifiers include private, protected, and default (none). Of the four, only public and default are applicable to top-level classes (in other words, there is no such thing as a private or protected top-levelnot innerclasses). Furthermore, a file cannot contain more than one public top-level class.

    2.1.1.3 Class names begin with a capital letter (convention, not requirement) and must be nonempty string of letters, digits and underscores as long as they begin with a letter, underscore or $ and contain no blanks. Java is case sensitiveupper and lower case letters differ. So HelloWorld Helloworld and System system.

  • Lesson 2 CS &141

    ECC Niko ulevski 2

    2.1.1.4 Single comment lines begin with a double slash // and are neglected by the compiler. Multiple comment lines begin with /* and end with */. Java has a third form of comment syntax for javadoc documentation: /** and */.

    2.1.1.5 The braces delineate blocks and must match. 2.1.1.6 The next line is a method heading of the class. The word public

    means that the contents of the following block are accessible from all other classes. The word static means that the method (function) being defined applies to the class itself rather than to objects of the class. The word void means that the method main has no return value. The parameter list for main is (String args [] ). It states that the only argument of the method main is an array of String type called args. Every Java application must have this line as it appearsthe main method is executed first.

    2.1.1.7 The line System.out.println(Hello World!); invokes the println method of the System.out object to display Hello World! followed by nonprintable newline in the DOS command line window. Note the quotes and semicolon at the end.

    2.1.2 Frames. The JFrame class is found in the javax.swing package. As a GUI component, derives from the Frame class which in term derives from the Window class, and so on to the top-level Object class. It comes pre-equiped with a ContentPane, a menu Bar and a JLabel in the ContentPane.

  • Lesson 2 CS &141

    ECC Niko ulevski 3

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #2a--TestFrame // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // An Example of old style Frame //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import java.awt.*; public class TestFrame //tests the frame class { public static void main (String args [ ]) { Frame frame = new Frame ("Example #2"); frame.setSize(250,100); //250x100 pixels frame.setVisible(true); } }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #2b--JTestFrame // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // An Example of alternate version using Swing and JFrame //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import javax.swing.*; public class JTestFrame //tests the frame class { public static void main (String args []) { JFrame jframe = new JFrame("Example #2"); jframe.setSize(250,100); //250x100 pixels jframe.setVisible(true); } }

    2.1.3 Temperature

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #3--Temperature // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // This program gets input from the user, temperature // in Fahrenheit, and displays temperature in Celsius //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import java.io.*; //Llook in this library for definition of classes //IOException, InputStreamReader, and BufferedReader import java.text.*; //Needed for the DecimalFormat class

    public class Temperature // convert Fahrenheit to Centigrade { public static void main (String args [ ]) throws IOException { double temperature; //Fahrenheit temperature, declaration String name, text; InputStreamReader reader = new InputStreamReader(System.in); BufferedReader input = new BufferedReader (reader);

  • Lesson 2 CS &141

    ECC Niko ulevski 4

    System.out.print("Enter your name: "); //Prompt for name name = input.readLine(); System.out.print("Hello, " + name + "!"); System.out.print("\nPlease type the temperature (deg F): ");

    text = input.readLine(); //Get temperature in Fahrenheit temperature = new Double(text).doubleValue(); System.out.print("\n" + temperature);

    temperature = (5.0 * (temperature - 32.0)) / 9.0; //String myString = NumberFormat.getInstance().format(temperature); DecimalFormat fourDigits = new DecimalFormat("0.00000");

    //Display temperature in Celsius System.out.print(" deg F is " + fourDigits.format(temperature)); System.out.println(" deg C"); } } output: run: Enter your name: Niko Culevski Hello, Niko Culevski! Please type the temperature (deg F): 56

    56.0 deg F is 13.33333 deg C BUILD SUCCESSFUL (total time: 20 seconds)

    2.1.4 Area of a circle.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #4--Area of circle // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // This program calculates the area of a circle //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import java.io.*; // Look in this library for definition of classes // Exception, InputStreamReader, and BufferedReader public class Circle // convert Fahrenheit to Centigrade temperature { public static void main (String args [ ]) throws Exception { InputStreamReader reader = new InputStreamReader(System.in); BufferedReader input = new BufferedReader (reader); System.out.print("Enter the radius of the circle: "); String text = input.readLine(); Double x = new Double(text); double r = x.doubleValue(); System.out.print("The area of a circle of radius " + r); double area = Math.PI*r*r; System.out.println(" is " + area); } } output: run: Enter the radius of the circle: 5.6 The area of a circle of radius 5.6 is 98.52034561657591 BUILD SUCCESSFUL (total time: 15 seconds)

    2.1.5 Adding integers. This example uses JOptionPane.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • Lesson 2 CS &141

    ECC Niko ulevski 5

    // Example #5--Adding two integers with JoptionPane // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // This program adds two integers and uses the // JOptionPane class for input and output //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    import javax.swing.JOptionPane; // import class JOptionPane

    public class Addition { public static void main( String args[] ) { String firstNumber, // first string entered by user secondNumber; // second string entered by user int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2

    // read in first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

    // read in second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer" );

    // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber );

    // add the numbers sum = number1 + number2;

    // display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );

    System.exit( 0 ); // terminate the program } }

    While the JOptionPane class may appear complex because of the large number of methods, almost all uses of this class are one-line calls to one of the static showXxxDialog methods shown below:

    showConfirmDialog Asks a confirming question, like yes/no/cancel. showInputDialog Prompt for some input. showMessageDialog Tell the user about something that has happened. showOptionDialog The Grand Unification of the above three.

    2.2 Simple Input and Output. Output for Java applications is straightforward; not so for input, unfortunately, until the recent addition of the Scanner class. I/O is handled with much more ease in applets.

  • Lesson 2 CS &141

    ECC Niko ulevski 6

    2.2.1 Output. In Java the methods System.out.print and System.out.pritnln are the easiest way to produce output. For example,

    2.2.1.1 System.out.pritnln(temperature); will display the value of the variable temperature on the stdout (standard output streamthe console). Note that method print is identical to println, except it does not emit a newline character.

    2.2.1.2 System.out.pritnln(temperature + deg F is ); is similar to the above, with the plus sign, + , acting as a concatenation operator.

    2.2.2 Input is now accomplished easily too. You are provided with a new Scanner class with methods for inputting data from the keyboard. You must have however the following import statement:

    import java.util.Scanner; Typically you will need a Scanner object, call it keyboard, accomplished with the following statement: Scanner keyboard = new Scanner(System.in);

    The Scanner class has a multitude of read methods. 2.2.2.1 Scanner.nextChar()reads a character. 2.2.2.2 Scanner.nextDouble()reads a double (real number with double

    precision). 2.2.2.3 Scanner.nextLine()reads a string.

    2.2.3 Close examination of the keyboard class reveals strong reliance on the classes BufferedReader and InputStreamReader (see example #4 above).

    2.2.4 Example 6The Scanner class.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #6--Adding two integers with the Scanner class // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // This program adds two integers and uses the // Scanner class for input and output //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    import java.util.Scanner;

    public class ScannerExample { public static void main(String[] args) { System.out.println("Hello out there."); System.out.println("I will add two numbers for you."); System.out.println("Enter two whole numbers on a line: ");

    int n1, n2;

    Scanner keyboard = new Scanner(System.in); n1 = keyboard.nextInt( ); n2 = keyboard.nextInt( );

    System.out.print("The sum of those two numbers is: "); System.out.println(n1 + n2); } }

  • Lesson 2 CS &141

    ECC Niko ulevski 7

    output: run: Hello out there. I will add two numbers for you. Enter two whole numbers on a line: 45 -12 The sum of those two numbers is: 33 BUILD SUCCESSFUL (total time: 7 seconds)

    2.3 Variables, Objects, Arithmetic, and Assignment Statements. 2.3.1 Variables. There are two kinds of entities that hold data in Java: variables and

    objects. 2.3.1.1 A variable can one of nine possible types (the first eight are primitive):

    2.3.1.1.1 boolean either false or true 2.3.1.1.2 char 16-bit Unicode characters 2.3.1.1.3 byte 8-bit integers from 128 to 127 2.3.1.1.4 short 16-bit integers from 32,768 to 32 767 2.3.1.1.5 int 32-bit integers from 2,147,483,648 to 2,147,483,647 2.3.1.1.6 long 64-bit integers ranging from 9,223,372,036,854,775,807 2.3.1.1.7 float 32-bit decimals from 1.40239846E-45 to

    3. 40239847E+38 2.3.1.1.8 double 64-bit decimal from 4.94065645841246544E-324 to

    1.79769313486231570E+308 2.3.1.1.9 reference the address of objects are stored in variables.

    2.3.1.2 Each variable has unique name which is designated when the variable is declared, e.g., double temperature = 56.8d;.

    Examples of Literal Values and Their Data Types

    Literal Data Type Size (bits) Min Max Init.

    value

    true false boolean

    1 false

    108 byte 8 -27 =

    -128 27 - 1 = 127 0

    'c' char 16 \u0000

    -28700 short 16 -215 =

    -32768 215 - 1 = 32767 0

    178 int 32 -231 =

    -2147483648 231 - 1 = 2147483647 0

    8864L long 64 -263 263 - 1 =

    9223372036854775807 0L

    87.363F float 32 1.4E-45 3.4028235E38 0.0f

    37.266 double 64 4.9E-324 1.7976931348623157E308 0.0D

  • Lesson 2 CS &141

    ECC Niko ulevski 8

    37.266D 26.77e3

    2.3.1.3 Java supports local variables, declared within method definition. But Java does not have global variables (they are part of a class).

    2.3.1.4 An identifier in Java is a word used to name a variable, method, class, or a label. An identifier cannot be a keyword or a reserved word and it must begin with a letter, underscore ( _ ), or dollar sign ($) . Subsequent characters may consist of any number of letters, digits, underscores, or dollar signs. Thus, fahrTemp, Xy_Z, e45TYP$ and _Hello$5 are valid names, but 3TP2, main&, #$%kl are not.

    2.3.1.5 Java has a number of keywords (reserved) words (see table 4.2, page 152ff or Java Language Keywords.doc). Identifiers that are reserved words are illegal.

    2.3.1.6 To declare a variable whose value will never change, add the word final to the declaration, e.g., final double EXPON = 2.7182818;

    2.3.1.7 Java supports variables of two different lifetimes: 2.3.1.7.1 A member variable of a class is created when an instance is created.

    They are assigned automatically an initial value (0 for short, byte, and int, 0L for long, 0.0f for float, 0.0d for double, \u0000 for char, false for boolean, and null for object reference).

    2.3.1.7.2 An automatic (local) variable of a method is created on entry of a method, and exists only during execution of the method. Local variables are not initialized by the system; they must be explicitly initialized before being used. For example, this method will not compile:

    public double fourthRoot(double d) { double result; //trouble hereneeds initialization if (d >= 0) { result = Math.sqrt(Math.sqrt(d)); } return result;

    } 2.3.2 Objects. An object is an instance of a class and may contain many variables.

    OOP encapsulates data (attributes) and methods (behavior) into packages called objects; the data and methods of an object are intimately tied together. Objects have the property of information hiding.

    2.3.2.1 Object may instantiate an unlimited number of classes. 2.3.2.2 Objects have references, instead of names, so they need not be unique. 2.3.2.3 An object is created by using the new operator to invoke a constructor,

    and it dies when it has no references. 2.3.2.4 Java manipulates objects by reference, but it passes object references to

    methods by value (copies of address).

  • Lesson 2 CS &141

    ECC Niko ulevski 9

    2.3.2.5 Referencing and dereferencing of objects is handled for you automatically by Java. Java does not allow you to manipulate pointers or memory addresses. Specifically, Java does not allow you to:

    2.3.2.5.1 cast object or array references into integers or vice-versa. 2.3.2.5.2 do pointer arithmetic. 2.3.2.5.3 compute the size in bytes of any primitive type or object.

    2.3.2.6 The default value for variables of reference type is null, a reserved word indicating absence of reference (not defined to be 0, as in C).

    2.3.3 Arithmetic. Java supports almost all of the standard C operators. It is important to understand their precedence and associativity shown below from appendix C.

    Operators are shown in decreasing order of precedence from top to bottom. Operator Type Associativity () [] . parentheses array subscript member

    selection left to right

    ++ -- unary postincrement unary postdecrement right to left ++ -- + - ! ~ ( type )

    unary preincrement unary predecrement unary plus unary minus unary logical negation unary bitwise complement unary cast

    right to left

    * / % multiplication division modulus left to right + - addition subtraction left to right > >>> bitwise left shift bitwise right shift

    with sign extension bitwise right shift with zero extension

    left to right

    < >= instanceof

    relational less than relational less than or equal to relational greater than relational greater than or equal to type comparison

    left to right

    == != relational is equal to relational is not equal to

    left to right

    & bitwise AND left to right ^ bitwise exclusive OR boolean logical

    exclusive OR left to right

    | bitwise inclusive OR boolean logical inclusive OR

    left to right

    && logical AND left to right || logical OR left to right ?: ternary conditional right to left = += -= *= /= %= &= ^= |= = >>>=

    assignment addition assignment subtraction assignment multiplication assignment division assignment modulus assignment bitwise AND assignment bitwise exclusive OR assignment bitwise inclusive OR assignment bitwise left shift assignment bitwise right shift with sign

    right to left

  • Lesson 2 CS &141

    ECC Niko ulevski 10

    extension assignment bitwise right shift with zero extension assignment

    2.3.4 Example #7Primitive Data Types.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #7Primitive Data Types // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to show values of primitive types //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public class PrintTypes { public static void main(String[] args) { boolean b = false; char c = 'R'; byte j = 127; short k = 32767; int m = 2147483647; long n = 9223372036854775807L; // 'L' is for "long" // 'F' is for "float", compilation error without F float x = 3.14159265F; double y = 3.141592653589793238; System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("j = " + j); System.out.println("k = " + k); System.out.println("m = " + m); System.out.println("n = " + n); System.out.println("x = " + x); System.out.println("y = " + y); } }

    Output: run: b = false c = R j = 127 k = 32767 m = 2147483647 n = 9223372036854775807 x = 3.1415927 y = 3.141592653589793 BUILD SUCCESSFUL (total time: 1 second)

    2.3.5 Example #8Maximum values of Primitive Data Types.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #8Primitive Data Types--Maximum values // CS 151, 6 Apr 2009 // ECC, Spring 2009

  • Lesson 2 CS &141

    ECC Niko ulevski 11

    // Niko Culevski // Program to show values of primitive types //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    public class MaxVariablesDemo { public static void main(String args[]) {

    // integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE;

    // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE;

    // other primitive types char aChar = 'S'; boolean aBoolean = true;

    // display them all System.out.println("The largest byte value is " + largestByte); System.out.println("The largest short value is " + largestShort); System.out.println("The largest integer value is " + largestInteger); System.out.println("The largest long value is " + largestLong);

    System.out.println("The largest float value is " + largestFloat); System.out.println("The largest double value is " + largestDouble);

    if (Character.isUpperCase(aChar)) { System.out.println("The character " + aChar + " is upper case."); } else { System.out.println("The character " + aChar + " is lower case."); } System.out.println("The value of aBoolean is " + aBoolean); } }

    Output: run: The largest byte value is 127 The largest short value is 32767 The largest integer value is 2147483647 The largest long value is 9223372036854775807 The largest float value is 3.4028235E38 The largest double value is 1.7976931348623157E308 The character S is upper case. The value of aBoolean is true BUILD SUCCESSFUL (total time: 2 seconds)

    2.3.6 Example #9Maximum values of Primitive Data Types.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #9Increment and Decrement Operators

  • Lesson 2 CS &141

    ECC Niko ulevski 12

    // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to show values of primitive types //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    public class IncrementDecrement { public static void main(String[] args) { char c = 'R'; byte j = 127; short k = 32767; System.out.println("c = " + c); ++c; System.out.println("c = " + c); ++c; System.out.println("c = " + c); System.out.println("j = " + j); --j; System.out.println("j = " + j); ++j; System.out.println("j = " + j); ++j; System.out.println("j = " + j); System.out.println("k = " + k); k -= 4; System.out.println("k = " + k); k += 5; System.out.println("k = " + k); } }

    Output: run: c = R c = S c = T j = 127 j = 126 j = 127 j = -128 k = 32767 k = 32763 k = -32768 BUILD SUCCESSFUL (total time: 0 seconds)

    2.3.7 Example #10Arithmetic.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #10Arithmetic // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to show values of primitive types

  • Lesson 2 CS &141

    ECC Niko ulevski 13

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    public class Arithmetic { //member variables--class level variables static float f; static double d = -10.0/0; //no error! public static void main(String[] args) { //local variables int m = 25, n = 7; System.out.println("m = " + (++m)); System.out.println("n = " + (n--));

    //access member variables from within a static method //requires static declaration of the variables System.out.println("f = " + f); System.out.println("d = " + d); int sum = m + n; System.out.println("m + n = " + sum); int difference = m - n; System.out.println("m - n = " + difference); int product = m * n; System.out.println("m * n = " + product); int quotient = m / n; System.out.println("m / n = " + quotient); int remainder = m % n; System.out.println("m % n = " + remainder); System.out.println(12345*234567/234567); System.out.println(12345/234567*234567); System.out.println(7.6 % 2.9); System.out.println(-5 % 2); //m = 26, n = 6 System.out.println(m >> 2); System.out.println(n >> 2); System.out.println(Double.NaN == Math.sqrt(-1)); System.out.println(Double.NaN != Double.NaN); System.out.println("4 | 3 = " + (4 | 3)); // 4 = 0100, 3 = 0011 System.out.println("4 & 3 = " + (4 & 3)); System.out.println("~4 = " + ~4); //-5 = 11111111111111111111111111111011 } }

    Output: run: m = 26 n = 7 f = 0.0 d = -Infinity m + n = 32 m - n = 20 m * n = 156 m / n = 4 m % n = 2

  • Lesson 2 CS &141

    ECC Niko ulevski 14

    -5965 0 1.7999999999999998 -1 6 48 1073741823 false true 4 | 3 = 7 4 & 3 = 0 ~4 = -5 BUILD SUCCESSFUL (total time: 2 seconds)

    2.4 Data Types and Expressions. Most of the material in this section was covered already in section 2.3. Here are few additional comments.

    2.4.1 Dividing two integers together yields an integer. Thus, 7/5 = 1. 2.4.2 The modulus operator, m % n, is the remainder when m is divided by n,

    e.g., 11 % 7 = 4. A useful rule of thumb for dealing with modulo calculations that involve negative numbers is this: simply drop any negative signs from either operand and calculate the result. Then, if the original left operand was negative, negate the result. The sign of the right operand is irrelevant. Verify for yourself that 5 % -2 = -1.

    2.4.3 Java does not give warning for integer overflow: int x = 100000 * 100000; System.out.println(x); //Output: 1410065408

    2.4.4 Numbers in scientific notation are expressed with the so-called e-notation, e.g., 0.5e+002, 2.817939e-15.

    2.4.5 Internal representation of real numbers cannot be exact. Consider, double x = 1.0/5.0 + 1.0/5.0 +1.0/5.0 0.6; //result should be 0 System.out.println(x); //Output: 1.1102230246251565E-16

    2.4.6 Java provides a number of mathematical methods. 2.4.7 Some floating-point calculations can return a NaN (for example,

    Math.float(-1);). Two NaN values are defined in the java.lang package: Float.NaN and Double.NaN, both considered non-ordinal for comparisons. Thus, do not surprise yourself when Float.NaN == Float.NaN results in false. The most appropriate way to test for NaN is to use Float.isNaN(float) or its Double equivalent static methods in the java.lang package.

    2.4.8 Division by 0 is illegal for integral types but not so for the two floating-point types. Java provides the following infinities: Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, and Double.POSITIVE_INFINITY.

    2.4.9 To flush out the output buffer use System.out.flush(); 2.4.10 Java promotes lower precision integer types to upper ones in mixed

    type arithmetic (say, integers to doubles). Downward demotion need to be casted, e.g. i = (int)(10.3 * x);

  • Lesson 2 CS &141

    ECC Niko ulevski 15

    2.5 Classes, Methods and Objects. A Java class is a specific category of objects. It specifies the range of data that objects of that class can have. There are three essential features that distinguish classes from types in Java:

    classes can be defined by a programmer. class objects can contain variables, including references to other objects. classes can contain methods that give their objects the ability to act.

    Here is an example of a Point class:

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #11Class Example // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to usage of a Point class // Note that the Class Point should be saved in a // separate file //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    public class Point // Objects represent points in the Cartesian plane { // the points coordinates are hidden from outside private double x, y; public Point(double a, double b) //constructor, invoked to initialize { x = a; y = b; }

    public double xcoord() //method to return x-coordinate { return x; }

    public double ycoord() //method to return y-coordinate { return y; }

    public boolean equals(Point p) { return (x == p.x && y == p.y); }

    public String toString() { return new String("(" + x + ", " + y + ")"); }

    public static void main(String args[])

    /*The line that follows does three things: 1. it declares p to be a reference to Point objects. 2. it applies the new operator to create a point object with values 2 and 3 for the fields x and y. 3. it initializes the reference p with this new objects. */ {

  • Lesson 2 CS &141

    ECC Niko ulevski 16

    Point p = new Point(2,3); // instantiate a point object

    System.out.println("p.xcoord() = " + p.xcoord() + ", p.ycoord() = " + p.ycoord ());

    // display the point p using its toString() method System.out.println("p = " + p);

    // create anoher point Point q = new Point(7,4); System.out.println("q = " + q);

    // check if p and q are equal using the equals() method if (q.equals(p)) System.out.println("q equals p"); else System.out.println("q does not equal p");

    q = new Point(2,3); System.out.println("q = " + q); if (q.equals(p)) System.out.println("q equals p"); else System.out.println("q does not equal p"); } }

    Output: run: p.xcoord() = 2.0, p.ycoord() = 3.0 p = (2.0, 3.0) q = (7.0, 4.0) q does not equal p q = (2.0, 3.0) q equals p BUILD SUCCESSFUL (total time: 2 seconds)

    2.5.1 The String Class. A string is a sequence of characters. The String class is a special, heavily used class in Java.

    2.5.1.1 String objects can be created without the required new for other objects, by writing string literalssequence of character within double quotes.

    2.5.1.2 Strings have the concatenation operator, + which converts integers into strings for concatenating with a string.

    2.5.1.3 String object suffer the restriction of being immutable; they cannot be changed. Java provides the separate StringBuffer class for string objects that need to be changed. Use this class instead!

    2.5.1.4 Every String object has a unique integer value, called its hash code and computed from the Unicode values of characters in the string. For example, the hash value of the string ABCDEFGHIJKLMNOPQRSTUVWXYZ is 218640813. This number has no meaning other than serving as a numerical label for the object. Hash values are used as storage locators when the

  • Lesson 2 CS &141

    ECC Niko ulevski 17

    objects are stored in tables. 2.5.1.5 An example of String class.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #12String Class Example // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to demonstrate few methods of the String class //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    public class Alphabet { public static void main(String[] args) { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //no new System.out.println(alphabet); System.out.println("This string contains " + alphabet.length() + " characters."); System.out.println("The character at index 4 is " + alphabet.charAt(4)); //letter E, 4 letters before E System.out.println("The index of the character Z is " + alphabet.indexOf('Z')); //number of characters that precede Z System.out.println("The hash code for this string is " + alphabet.hashCode()); } }

    Output: run: ABCDEFGHIJKLMNOPQRSTUVWXYZ This string contains 26 characters. The character at index 4 is E The index of the character Z is 25 The hash code for this string is 218640813 BUILD SUCCESSFUL (total time: 2 seconds)

    2.5.1.6 Substring Example. A substring is a string whose characters form a contiguous part of another string. The substring method returns a new string that is a substring of this string. Note that the substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex - beginIndex.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #13String Class Example // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to demonstrate the substring() method // of the String class //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public class Substrings

  • Lesson 2 CS &141

    ECC Niko ulevski 18

    { public static void main(String args[]) { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println(alphabet); System.out.println("The substring from index 4 to index 8 is " + alphabet.substring(4, 8)); System.out.println("The substring from index 4 to index 4 is " + alphabet.substring(4, 4)); //empty string System.out.println("The substring from index 4 to index 5 is " + alphabet.substring(4, 5)); System.out.println("The substring from index 0 to index 8 is " + alphabet.substring(0, 8)); System.out.println("The substring from index 8 to the end is " + alphabet.substring(8)); } }

    Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ The substring from index 4 to index 8 is EFGH The substring from index 4 to index 4 is The substring from index 4 to index 5 is E The substring from index 0 to index 8 is ABCDEFGH The substring from index 8 to the end is IJKLMNOPQRSTUVWXYZ

    2.5.1.7 Searching for characters in a string example. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #14String Class Example // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to demonstrate the indexOf() method // of the String class //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public class SearchingForChars { public static void main(String args[ ]) { String str = "This is the Mississippi River."; System.out.println(str); // display string

    //one version of indexOf() method int i = str.indexOf('s'); System.out.println("The first index of 's' is " + i);

    //overloaded version of indexOf() method int j = str.indexOf('s', i+1); System.out.println("The next index of 's' is " + j); int k = str.indexOf('s', j + 1); System.out.println("The next index of 's' is " + k); k = str.lastIndexOf('s'); System.out.println("The last index of 's' is " + k); System.out.println(str.substring(k)); System.out.println(str.toLowerCase()); System.out.println(str.toUpperCase());

  • Lesson 2 CS &141

    ECC Niko ulevski 19

    } }

    Output: run: This is the Mississippi River. The first index of 's' is 3 The next index of 's' is 6 The next index of 's' is 14 The last index of 's' is 18 sippi River. this is the mississippi river. THIS IS THE MISSISSIPPI RIVER. BUILD SUCCESSFUL (total time: 1 second)

    2.5.1.8 Converting Strings into primitive data types example. Try changing the month and rerun. What happens?

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #15String Class Example // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to demonstrate converting Strings into // primitive data types //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public class TestConversions { public static void main(String args[]) { String today = "April 18, 2009"; String todaysDayString = today.substring(6, 8); int todaysDayInt = Integer.parseInt(todaysDayString); int nextWeeksDayInt = todaysDayInt + 7; String nextWeek = today.substring(0, 6) + nextWeeksDayInt + today.substring(8); System.out.println("Today's date is " + today); System.out.println("Today's day is " + todaysDayInt); System.out.println("Next week's day is " + nextWeeksDayInt); System.out.println("Next week's date is " + nextWeek); } }

    Output: run: Today's date is April 18, 2009 Today's day is 18 Next week's day is 25 Next week's date is April 25, 2009 BUILD SUCCESSFUL (total time: 2 seconds)

    2.5.1.9 Modifying StringBuffer objects. Java provides the separate StringBuffer class for string objects that need to be changed.

  • Lesson 2 CS &141

    ECC Niko ulevski 20

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #15StringBuffer Class Example // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Program to demonstrate the StringBuffer class // The StringBuffer is superior to the String class and // should be used in lieu of the String class whenever possible //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public class TestAppending { public static void main(String[] args) { StringBuffer buf = new StringBuffer(10); buf.append("It was"); System.out.println("buf = " + buf); System.out.println("buf.length() = " + buf.length()); System.out.println("buf.capacity() = " + buf.capacity()); buf.append(" the best"); System.out.println("buf = " + buf); System.out.println("buf.length() = " + buf.length()); System.out.println("buf.capacity() = " + buf.capacity()); buf.append(" of times."); System.out.println("buf = " + buf); System.out.println("buf.length() = " + buf.length()); System.out.println("buf.capacity() = " + buf.capacity()); } }

    Output: run: buf = It was buf.length() = 6 buf.capacity() = 10 buf = It was the best buf.length() = 15 buf.capacity() = 22 buf = It was the best of times. buf.length() = 25 buf.capacity() = 46 BUILD SUCCESSFUL (total time: 2 seconds)

    2.5.2 Class Methods and Variables. 2.5.2.1 Note that Java allows for class methods as well as for object

    methods. For example, Integer.parseInteger(), Mouse.howManyLegs().

    2.5.2.2 Similarly classes can have variables. 2.5.3 Review of dot notation.

    2.5.3.1 Each class has associated set of objects. 2.5.3.2 New objects are created with the new operator. 2.5.3.3 Each object has a set of methods (functions) and a set of variables

    (data). To access them (if permitted), one writes: object. method

  • Lesson 2 CS &141

    ECC Niko ulevski 21

    or object.variable. 2.5.4 Prototypes.

    2.6 Memory Concepts. Variable names, such as temperature, cent, and sum correspond to computers memory location. Each variable has a name, a type, and a value. Java is strongly-types, so mixing of types has to follow strict type conversion (casting) rules.

    2.6.1 For example, when the statement number1 = Integer.parseInt(firstNumber); executes, firstNumber is converted to integer before storing it in memory. 2.6.2 When the statement sum = sum + number1; is executed, sums previous

    value is added with number1 and the result of that addition replaces the variable sum.

    2.7 Program Layout. 2.7.1 Use Javadoc headings (as comments) for each class an method,

    describing its functionality, pre and post conditions, author, version, parameters, and types).

    2.7.2 Indent and make the code readable: strive for clarity and simplicity. 2.7.3 Watch your braces and semicolons! 2.7.4 Comment as you write the code and more than you think is necessary.

    2.8 Debugging. 2.8.1 Syntax errorserrors due to grammatical misuse of the language rules. 2.8.2 Run-time errorsthe program compiles but it attempts to perform some

    illegal operation (division by zero). 2.8.3 Logic errorsthe program compiles and runs but produces incorrect

    results.

    2.9 Decision Making: Equality and Relational Operators. The selection (if) statement is treated fully in Chapter 4here it is introduced briefly in context with relational operators.

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Example #16 JOptionPane Class Example // CS 151, 6 Apr 2009 // ECC, Spring 2009 // Niko Culevski // Using if statements, relational operators, // and equality operators //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    import javax.swing.JOptionPane;

    public class Comparison {

  • Lesson 2 CS &141

    ECC Niko ulevski 22

    public static void main( String args[] ) { String firstNumber, // first string entered by user secondNumber, // second string entered by user result; // a string containing the output int number1, // first number to compare number2; // second number to compare

    // read first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer:" );

    // read second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer:" );

    // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber );

    // initialize result to the empty string 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 + " >= " + number2;

    // Display results JOptionPane.showMessageDialog( null, result, "Comparison Results", JOptionPane.INFORMATION_MESSAGE );

    System.exit( 0 ); } }

    Output:

  • Lesson 2 CS &141

    ECC Niko ulevski 23