Java Tips for Beginners (3): i++,print, loop, format,convert

Idioms for single-operand operations

The idiom i++ is a shorthand notation for i = i + 1. (Source: textbook: http://introcs.cs.princeton.edu/java/13flow/ )

Question: Any difference between i++ and ++i?

Answer: When they are used in the loops, they are the same.

But when used outside the loops, they behave differently: “i++ return the original value of i and then increase it by 1; ++i increases i by 1 and then returns the new value.” (Source: Youtube video: https://www.youtube.com/watch?v=vyQthubfAoI)

Another explanation in text: https://thomassundberg.wordpress.com/2011/08/05/what-is-the-difference-between-i-and-i/

Two ways to print output

System.out.print() // does not skip to a new line

System.out.println()//skip to a new line

Create a large string

Using “\n” in a String causes a line break. For example,

String s = "one" + "\n" + "two";

prints out to:

one
two

While & For loop

loop.png

(Source: Washington University in St. Louis CSE 131 Module 2 PowerPoint, Author: Ron K. Cytron)

How to format the spacing

Press “Ctrl+A” to select the whole file and then press “Ctril + I ”

Convert to double

add “1.0*” to convert data type from int to double

 

Advertisements

One thought

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s