Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎

2018-10-17

posted Oct 17, 2018, 6:30 AM by Konstantinovich Samuel   [ updated Oct 17, 2018, 8:04 AM ]
Classwork:
       After new topic, work on lab from yesterday.

Atom:
Edit -> Preferences -> Install
1. Search for: 
    linter-javac 
2. click install
3. click OK on all of the popups.
4. win

Goal Typecasting:

Typecasting: You tell the compiler to treat a variable like another type.

Syntax:

(newType)variable 
(newType)value


For numbers they are converted, for objects you can only convert into something that the object has an is-a relationship with!

float to int -> cut off the decimal point.
(int)5.5 
5

(int)-12.3
-12


int to float -> add .0
(double)5
5.0


You cannot typecast primitives to strings (String)5 is NOT valid.

System.out.println( (int) 0.5 * 2  ); //0


System.out.println( 9 / (double) 2  ); //4.5


System.out.println( x / (double) y ); //prevent integer division
//instead of saying 1.0 * x / y


Objects can be typecast to other objects.



        Person
        /     \
   Employed   Unemployed
       \        /      \
     Cabbie    Bum    Child


Person p = new Person();
(Object)p   is OK!
NO other typecasting is allowed.

Employed e = new Employed();
(Object)e  is OK
(Person)e is OK
NO other typecasting is allowed.

Employed c = new Cabbie();
Cabbie c2;
c2 = c; ERROR! an Employed is NOT a Cabbie.
c2 =  (Cabbie)c; //This will not crash



Comments