Skip to content

Latest commit

 

History

History
135 lines (97 loc) · 2.08 KB

20160908.md

File metadata and controls

135 lines (97 loc) · 2.08 KB

Sept. 8th, 2016

Puzzle (from last lecture)

int a;
int b;
a = 5;
b = 3;

Write code to swap values in a & b.

My own solution

int c; // Initialize a intermediate variable.
c = a; // Swap-out a.
a = b; // Assign value of b to a.
b = c; // Swap-in value of a via c.

Without the 3rd/temporary variable?

Say, we have a = 20, b = 30.

int a = 20;
int b = 30;

Using a basic "algorithm", taking advantage of the int declaration, simple additions and substractions may do the trick.

a = a + b; // 20+30=50
b = a - b; // 50-30=20
a = a - b; // 50-20=30

Declaration, print, and literal

int numCars = 9;
int numTrucks = 4;

System.out.print( numCars );
System.out.print( nunCars + numTracks );
System.out.print( "numCars" + numTracks );

In the sample code above...

  • System: A collection of system call.
  • out: Attribute that specifies action category, out in I/O operation here, for example.
  • print: Instance that carries out a particular method call.
  • (): Parameters (in experssions).
  • +: Operator overloading, combining operations. Declaration types like int will allow this notation to represent addition/summation.
  • "": String literal.

Special call instance of println allows Java to print output with a newline character at the end of the output line. For instance:

System.out.print( numCars );

Results in an output of:

9

And...

System.out.println( numCars );

Results in an output of:

9
(newline)

Try and print

Starting with:

int a = 5;
int b = 3;

Produce output:

a has 5
b has 3

My solution

System.out.println( "a has " + a );
System.out.print( "b has " + b );

Escape sequences

Special character sequences within a String.

\n  \"  \\  \t

In an example...

System.out.print( "hello\n\t\"hi\"\\" );

Outputs...

hello
  "hi"\