UF 06: JAVA¶

Objects and strings¶

Alta Formazione Professionale - ITT Marconi

January 2021

2.1. Objects - Instances of Classes¶

  • will follow the book course.csawesome.org EXCEPT Java Swing Gui
  • will add challenges later

1) What are Objects and Classes?

  • class
  • instances
  • objects
  • new instances / objects
  • methods
  • attributes / properties
  • calling methods
  • dot operator .

2) Intro to Objects (with Turtles)

3) Creating Turtle Objects

4) Programming Challenge : Turtle Drawing

2.2. Creating and Initializing Objects: Constructors¶

  • new again
  • default constructor

1) Overloading Constructors

2) The World Class Constructors

3) The Turtle Class Constructors

  • passing a reference to world

4) Object Variables and References

  • null

5) Constructor Signatures

  • parameter list
  • formal parameters

6) Formal and Actual Parameters

12) Programming Challenge: Custom Turtles

2.3. Calling Methods Without Parameters¶

1) Procedural Abstraction

  • methods use attributes
  • NullPointerException

2) Programming Challenge : Draw a Letter

2.4. Calling Methods With Parameters¶

1) Tracing Methods

2) Programming Challenge : Turtle House

2.5. Calling Methods that Return Values¶

1) Get Methods

  • attributes
  • set methods

2) toString() Methods

3) Methods with Arguments and Return Values

4) Programming Challenge : Turtle Distances

2.6. Strings¶

char

  • single character
  • single quote literal 'c'
  • two bytes
  • primitive

String

  • many characters
  • double quote literal "ciao mondo"
  • object
  • immutable
  • NOTE: even if on Java Tutor strings appears as a primitive (blue box), they are not!

1) String Operators - Concatenation

  • + operator
  • produces a NEW String
In [1]:
String x = "ciao";
String y = " mondo";
String z = x + y;
System.out.println(z);
ciao mondo

2.7. String Methods¶

indexes start from 0 included

//                0123456789
String stringa = "ciao mondo";

1) String Methods: length, substring, indexOf

.length()

In [2]:
"Ciao".length()
Out[2]:
4
In [3]:
//  012345678
   "un dubbio".length()
Out[3]:
9
In [4]:
//                  012?.....
System.out.println("un\ndubbio");
un
dubbio
In [5]:
//  012 345678
   "un\ndubbio".length()
Out[5]:
9

.substring(a,b)

  • from a included
  • until b excluded
  • you may get IndexOutOfBoundsException
In [6]:
//                  0123456
System.out.println("cartone".substring(2,5))
rto

No chars:

In [7]:
//                  0123456
System.out.println("cartone".substring(2,2))

One char:

In [8]:
//                  0123456
System.out.println("cartone".substring(2,3))
r
In [9]:
//                  0123456
System.out.println("cartone".charAt(2))
r
In [10]:
//                  0123456
System.out.println("cartone".substring(2,3).getClass())
class java.lang.String
char c = "cartone".charAt(2);        // OK
char c = "cartone".substring(2,3);   // WRONG

String s = "cartone".substring(2,3); // OK
String s = "cartone".charAt(2);      // WRONG

.indexOf(s)

indexOf returns the FIRST occurrence of string s

In [11]:
//                  0123456 
System.out.println("cartone".indexOf("to"));
3

WARNING: ALWAYS ask yourself if your algorithm still works if you have duplicates:

In [12]:
//                  0123456789... 
System.out.println("arzigogolato".indexOf("go"));
4

2) CompareTo and Equals

Equals:

  • .equals(otherString) method
In [13]:
System.out.println("Ciao".equals("Ciao")); // correct way
true
In [14]:
// case sensitive

System.out.println("Ciao".equals("Ciao"));
true

== operator

  • compares references
  • not char by char !

Don't use == with strings!

WARNING: sometimes seems to work because for efficiency Java may cache strings so two identical copies actually share the same memory address

In [15]:
System.out.println("Ciao" == "Ciao");  // WRONG: HERE WORKS *BY LUCK*
true

compareTo

  • negative
  • zero
  • positive
In [16]:
System.out.println("Mario".compareTo("Wario"));
-10
In [17]:
System.out.println("Wario".compareTo("Mario"));
10
In [18]:
System.out.println("Mario".compareTo("Mario"));
0

Different lengths:

In [19]:
System.out.println("Mario".compareTo("MarioAndLuigi"));
-8
In [20]:
System.out.println("MarioAndLuigi".compareTo("Mario"));
8

Comparison with < and > is not supported:

In [21]:
// System.out.println("Mario" < "Wario");   // error

More strings¶

Seems like CSAwsome doesn't have many much material on strings, so

DO THESE EXERCISES: https://codingbat.com/java/String-1

2.8. Wrapper Classes - Integer and Double

  • primitive -> object conversion
  • autoboxing
In [22]:
Integer i = new Integer(2);  // the old way
Double d = new Double(3.5);
In [23]:
Integer i = 2;    // Autoboxing in Java 9+
Double d = 3.5;
In [24]:
i.getClass()
Out[24]:
class java.lang.Integer

QUESTION: does this work?

2.getClass()

overflow / underflow¶

  • Integer.MIN_VALUE
  • Integer.MAX_VALUE

2.9. Using the Math Class¶

  • static methods
  • sqrt, pow, abs, max, min

Square root¶

In [25]:
Math.sqrt(5)
Out[25]:
2.23606797749979

power¶

To raise to a power, you can call pow:

In [26]:
Math.pow(3,2)  // 3 power 2
Out[26]:
9.0

WARNING: in Java 3^2 does NOT mean power raise!

absolute value¶

In [27]:
Math.abs(-4)
Out[27]:
4

min and max¶

In [28]:
Math.min(2,6)
Out[28]:
2
In [29]:
Math.min(7,3)
Out[29]:
3
In [30]:
Math.max(7,3)
Out[30]:
7

Note in Java you can only pass two values:

Math.max(2,6,8)  // WRONG: does not work in Java!

random numbers¶

In [31]:
System.out.println(Math.random());  // number changes at each call
System.out.println(Math.random());
0.9017304454541571
0.1058621772838938

Use Random with a seed for repeatable results:

In [32]:
int seed  = 10;
Random generator = new Random(seed);
System.out.println("seed = " + seed);
System.out.println(generator.nextDouble());  
System.out.println(generator.nextDouble());

System.out.println();  

seed = 10;
Random generator = new Random(seed);
System.out.println("seed = " + seed);
System.out.println(generator.nextDouble());   // get the same as before  
System.out.println(generator.nextDouble());

System.out.println();  

seed = 1234;                                  // changed seed
Random generator = new Random(seed);  
System.out.println("seed = " + seed);
System.out.println(generator.nextDouble());   // different sequence
System.out.println(generator.nextDouble());
seed = 10
0.7304302967434272
0.2578027905957804

seed = 10
0.7304302967434272
0.2578027905957804

seed = 1234
0.6465821602909256
0.9513577109193919