Jan 24 Class Notes

Objectives
   Review 
   Runtime error 
   static method  
   class 
   classpath 
   Use class and static method 
        
-----------------------
Go to Reserved Keywords
Java Data Types:

  primitive types(8).
  composite data types(reference types):
         arrays
         classes

-----------------------
Primitive types(8)
    A boolean type
    A character type
    Four integer types
    Two floating-point types

-----------------------
See Primitive Types


Type Literals

boolean-------- true or false 
char ------------ 'S' '\t' '\u0041' '\'' 
byte --------- --   -128 to 127 
short------------ 23, -333 
int ------- -------1222 ,-1222 
long ------ ------120L, -23l 
float ----- -------3.45f, -3.5F 
double ------ ----3.45, 3.45d, 3.45D 
4.23E+21     scientific notation
034          octal (0-7) 
0x220c       hexadecimal 
0x220cL      a long value 

---------------------------------
Go to Operators

Arithmetic Operators

    Addition(+)
    Subtraction(-)
    Multiplication(*)
    Division(/)
    Modulo(%)
    
----------------------------------
Unary Minus(-) performs unary negation. It converts a positive 
value to an equivalently negative value, and vice versa.
---------------------------------
Assignment Operators(=)

Using “=“ assigns the value of the right operand to the left 
operand. 
The right operand must be a type that is 
assignment-compatible with the left operand.
“=“ returns a value that is assigned to the left operand. 
e. g. a = b = c = d = 1.

----------------------------------
Comparison Operators

    Equals (==)
    Not Equals (!=)
    Less Than (<)
    Less Than or Equal (<=)
    Greater Than (>)
    Greater Than or Equal(>=)
    Compare objects (instanceof)
    
----------------------------------
String Concatenation Operators

 To add numbers
 To indicate a positive number
 To concatenate or join strings
 
 System.out.println(“Total: “ + 10 + 5);  //Total: 105
 System.out.println(10 + 5 + “ Total”); //15 Total
 System.out.println(“Total: “ + 10/7.0);  //Total: 1.4285714285714286
 System.out.println(“Total: “ + (10+5)); //Total: 15
 System.out.println(“Total: “ + var1 + var2); //var1 and var2 are            
                                             //concatenate to string
-----------------------------------
Conversion May Occur

    Assignment
    Method Call
    Arithmetic Promotion
    
-----------------------------------
Widening Conversion OK
Narrowing Conversion Losing data and need casting
-----------------------------------
Casting & Cast Operator

Casting means explicitly telling Java to make a conversion. 
A casting operation may widen or narrow its argument. 
To cast, just precede a value with the parenthesized 
name of the desired type. (type) operator.
    int i = 10;
    double d = (double) i;
    double d2 = i;


-----------------------------------
A method-call conversion happens when you 
pass a value of one type as an argument to 
a method that expects a different type.
-----------------------------------
Arithmetic-promotion conversions happen within arithmetic 
statements while the compiler is trying to make sense out 
of many different types of operand.
There are four rules for binary operators
If one of the operands is a double, the other operand is 
converted to a double
Else if one of the operands is a float, the other 
operand is converted to a float.
Else if one of the operands is a long, the other operand is 
converted to a long
Else both are converted to ints.

short s = 9;
int i= 10;
float f = 11.1f
double d = 12.3;
if (-s * i  >= f / d) ==> false

(type) operator

Type Promotion:

byte b = 5; 
short s = 5; 
b + s ==> int 
b + s + 1.0 ==> double 
short s2 = (short)(b + s); 

------------------------------
Objects are created in programs to model    
concrete  objects that exist in the real world 
  
Objects have states, also called attributes or 
properties, that describe the characteristics of  
the object 

Objects also have methods, or procedures, that  
are encapsulated with the attributes of an object  
and can set or modify the state of the object 

---------------------------------
Defining a class

   Class modifiers
   Class keyword: class
   Class identifier
   Superclass name
   Interfaces implemented
   Class body: {}
   
----------------------------------
public class First extends Object {
    public static void main(String[] args) {
          System.out.println(“First Java Program”);
    }
}

----------------------------------
[modifier] class clsIdentifier [extends clsIdentifier implements       
                    interfaceIdentifier,  ,  ] {
     properties block
     methods block
     inner classes
}
----------------------------------
[modifiers] returnType methodIdentifier([parameter list]) {} 

public static returnType methodIdentifier() {
       //statements
     return returnType;
}

public static returnType methodIdentifier(dataType dt, dataType dt2,..){
       //statements;
     return returnType;
}
------------------------------------
//rewrite Hello.java 
public class Hello {
       public static void main(String[] args) { 
              //initialization required 
              String str = "Judy"; 
              String oneMore = null; 
              String oneMore2 = ""; 
              if (args.length > 0) { 
                     str = args[0]; 
                     oneMore = args[1];
                     oneMore2 = args[2]; 
              } 
             String msg = "Hello " + str + " " + oneMore 
                         + " " +  oneMore2;
             System.out.println(msg); 
       } 
} 
>javac Hello.java
>java –cp . Hello
Hello Judy null
>java –cp . Hello Kathy Bob Dan
Hello Kathy Bob Dan

------------------------------------
>java –cp . Hello 3.14159 ThisIsNotDbl more stuff here
Hello 3.14159 ThisIsNotDbl more
Any message passed through the main() method is a 
String type and held by String array indicated as args. 
-------------------------------------
>java –cp . Hello John Nancy
Exception: java.lang.ArrayIndexOutOfBoundsException   
runtime error
-------------------------------------
class Calculator { 
    public static void main(String[] args) { 
        System.out.println(add(5,5)); 
        System.out.println(sub(5,5)); 
        System.out.println(div(5,5)); //integer part
        System.out.println(mul(5,5)); 
     } 
     public static int add(int a, int b) { 
         return a + b; 
     } 
     public static int sub(int a, int b) { 
         return a - b; 
     } 
     public static int div(int a, int b) { 
         int c =  a / b; 
         return c ; 
     } 
     public static int mul(int a, int b) { 
         return a * b; 
     } 
} 
--------------------------------------
p.41 q.5 
Which of the following values can you assign to a variable 
of type int? 
a. 0
b. 98.6 
c. 'S‘
d. 5,000,000,000,000 

//Test.java 
class Test {
    public static void main(String[] args) {
        int i1 = (int)98.6; 
        int i2 = 'S'; 
        //int i3 = 5000000000000;
        System.out.println(i1 + " " + i2); 
    } 
}
>javac Test.java 
>java -cp . Test 
98 83 
-----------------------------------------
//DemoRaise.java 
public class DemoRaise {
      
    public static void main(String[] args) {
        double mySalary = 200.00; 
        double predictResult = predictRaise(mySalary, 0.1); 
        display(predictResult); 
    } 
  
    public static double predictRaise(double base, double rate) {
        return base*(1+rate);
    }

    public static void display(double result){ 
        System.out.println("With raise salary is " + result); 
    } 
}

>javac DemoRaise.java 

>java -cp . DemoRaise 

With raise salary is 220.000000000003 
-------------------------------------
Write a method named format to accept floating point and decimal 
places and return floating point. It can accept double or float 
types. Use Math.pow(x,y) or Math.round(x). e.g. 103 returned by 
Math.pow(10,3). 357 returned by Math.round(356.55678). 

3.1415 *1000/1000 ==> 3.1415 
3.1415 *1000 = 3141.5 --round it 
3142 /1000 = 3.142 

//format method
public static double format(double amount, int places) { 
    double temp = amount;
    //System.out.println(temp); 
    temp = temp * Math.pow(10, places); 
    // System.out.println(temp); 
    temp = Math.round(temp);
    // System.out.println(temp); 
    temp = temp/Math.pow(10, places); 
    // System.out.println(temp); 
    return temp; 
}

Think about efficiency. 
------------------------------------
class YourName { 
    public static void main(String[] args) { 
        double pi = Math.PI; 
        System.out.println(pi); 
        System.out.println(format(pi,2));
    }
    public static double format(double amount, int places) {                                             double temp = amount;
        temp = temp * Math.pow(10, places); 
        temp = Math.round(temp); 
        temp = temp/Math.pow(10, places); 
        return temp;
    } 
} 
>javac YourName.java
>java -cp . YourName 
3.141592653589793 
3.14 
----------------------------------------
class Tester {
    public static void main(String[] args) {
        double d = YourName.format(Math.PI, 2);             
        System.out.println(d); 

        //default constructor 
        YourName jx  = new YourName();     
        System.out.println(jx.format(Math.PI, 3)); 
    } 
} 
---------------------------------------
If it works, your classpath has been set. 
If you have error message like can't resolve symbol variable YourName: 
1. compile YourName and Tester classes together
 >javac Tester.java YourName.java or
 >javac *.java 
 >java -cp . Tester 

2. One session setup
 >set classpath = A:\ 
 >javac Tester.java 
 >java Tester 

3. write a batch file
 >notepad run.bat then type in: 
 set classpath = A:\ 
Save to disk A:\ 
You can put more specific commands in your batch file 
 >run

4. copy all related source code into one file. 
Only one public class allowed.
 >javac Tester.java 
 >java Tester
 3.14 
 3.142 
-----------------------------------------
// p.44 q12 // displays conversion into currency
//denominations 
class Dollars { 
   public static void main(String[] args){ 
       int dollarAmount = 57;
       calcChange(dollarAmount); 
   } 
   public static void calcChange(int dollars) { 
       int twenties, tens, fives, ones, amount; 
       twenties = dollars / 20; 
       amount = dollars - (twenties * 20); 
       tens = amount / 10; 
       amount = amount - (tens * 10); 
       fives = amount / 5; 
       amount = amount - (fives * 5); 
       ones = amount / 1; 
       System.out.println("$" + dollars + " converted is " + 
                          twenties + " $20, " +                          
                          tens + " $10, " + fives + 
                          " $5, and " + ones + " $1"); 
   } 
} 
-------------------------------------------------
public static void main(String[] args) { 
    int dollar = 57;
    int twenties = 0; 
    int tens = 0; 
    int fives = 0;
    int remainder = 0; 
    if (args.length > 0) { 
        String oneArg = args[0]; //after string class introduced add one 
        //Use wrapper class. 8 wrapper classes
        double temp = Double.parseDouble(oneArg); 
        if (temp < 0) { 
           temp = (-1)*temp; 
        } 
        dollar = (int)temp; 
    }
    twenties = toTwenty(dollar); 
     ……    
    String str = display(dollar, twenties, tens, fives, remainder);                    
    System.out.println(str); 
} 
------------------------------------------
Wrapper Classes

boolean      Boolean
byte         Byte
char         Character
short        Short
int          Integer
long         Long
float        Float
double       Double
--------------------------------------------
How to use wrapper classes to convert String 
to primitive data types?

String s = “123”;
byte b = Byte.parseByte(s);
short s = Short.parseShort(s);
int i = Integer.parseInt(s);
long lg = Long.parseLong(s);
float f = Float.parseFloat(s);
double d = Double.parseDouble(s);

--------------------------------------------
>java -cp . DollarChanger
 57 dollars equal 
 2 20's 
 1 10's 
 1 5's 
 2 1's 

>java -cp . DollarChanger 99 
99 dollars equal 
4 20's 
1 10's 
1 5's 
4 1's 

Use any number to test it. e.g 0, -34, 58967, 157.89 ... 

--------------------------------------------
class Tester2 {
    public static void main(String[] args) { 
        int dollar = 57;
        if (args.length > 0) { 
            double temp = Double.parseDouble(args[0]); 
            if (temp < 0){ 
               temp = (-1)*temp; 
            } 
            dollar = (int)temp; 
        }
        //default constructor
        DollarChanger dc = new DollarChanger();          
        System.out.println(dc.toTwenty(dollar));
        System.out.println(dc.toTens(dollar)); 
        System.out.println(dc.toFives(dollar));           
        System.out.println(DollarChanger.toTwenty(dollar));      
        System.out.println(DollarChanger.toTens(dollar));        
        System.out.println(DollarChanger.toFives(dollar));
   } 
} 
--------------------------------------
>javac Tester2.java 

>java -cp . Tester2 195 

.... 

Try this: 

>java -cp . Tester2 oop 
--------------------------------------
When you download it to your floppy disk, 
unjar it on command line: 

A:\jar -xf AutoCheckP1.jar 

And then type:

A:\java -cp . AutoCheckP1 DollarChanger 
-------------------------------------
Write a method called initials to print out
your initials like

    j  x   x
    j   x x
    j    x
    j   x x
j j j x     x

so it can be called with the following statement.
YourName.initials(); 

create Calculator object with the following methods
int add(int a, int b);
int sub(int a, int b); 
int mul(int a, int b); 
int div(int a, int b); 

and compile it for use in the Jan 29 Lab class

int i = YourName.cal.add(5,5); 

Jan 29. chapter 2 Section B, chapter 3

------------------------------------