Common Code Snippets

These simple examples can help students grasp new concepts.

Each snippet has been tested with students, but we welcome suggestions on our mailing list and in our Github repository.


!

!true       // false
!false      // true
!!true      // true
!!!true     // false
            

!=

2 != 2;     // false
3 != 4;     // true
            

&&

true && false;	// false
true && true;	// true
            

<

2 < 5;	// true
2 > 5;	// false
2 > 2;	// false
2 < 2;	// false
            

<=

2 <= 2;     // true
3 <= 2;     // false
2 <= 3;     // true
            

==

2 == 2;     // true
2 == 4;     // false
            

>

2 > 1;      // true
2 > 4;      // false

            

>=

5 >= 5;       // true
10 >= 5;      // true
5 >= 10;      // false
            

Absolute value

Math.abs(-16);      // returns 16
Math.abs(98.8);     // returns 98.8
            

Addition

2 + 2;              // 4
"Hi" + " there";   // "Hi there"
            

alist.add("Add me");

ArrayList ourList = new ArrayList();
ourList.add("Hello");
            

alist.clear();

ArrayList ourList = new ArrayList();
ourList.add("Hello");
ourList.add("Allo");
ourList.add("Hi there!");
ourList.clear();

            

alist.get(0);

ArrayList ourList = new ArrayList();
ourList.add("Hello");
ourList.get(0);         // returns "Hello"
            

alist.insert(1, "Insert me");

ArrayList ourList = new ArrayList();
ourList.add("Hello");
ourList.insert(0, "Goodbye");
            

alist.isEmpty();

ArrayList ourList = new ArrayList();
ourList.isEmpty();              // returns true
ourList.add("Hello");
ourList.isEmpty();              // returns false
ourList.clear();
ourList.isEmpty();              // returns true
            

alist.remove(int);

ArrayList ourList = new ArrayList();
ourList.add("Hello");
ourList.add("Goodbye");
ourList.remove(1);	//Removes and returns the "Goodbye" String
            

alist.set(0, "Set me");

ArrayList ourList = new ArrayList();
ourList.set(0, "Hello");
            

alist.size();

ArrayList ourList = new ArrayList();
ourList.size();	//Returns 0
ourList.add("Hello");
ourList.size();	//Returns 1
            

arraylist

ArrayList ourList = new ArrayList();
            

boolean

true
false
2 == 2                  // evaluates to true
2 != 2                  // evaluates to false
4 != 4.90               // evaluates to true
boolean willRain = false;
            

boolean[]

boolean[] options = new boolean[2];
options[0] = true;
options[1] = false;

// Alternatively:
boolean[] options = {true, false};

// And then ...
System.out.println(options[0]);         // prints `true`
System.out.println(options[1]);         // prints `false`
            

casting

(int) 11.0           // = 11
(int) 11.84          // = 11
(double) 11          // = 11.0
(double) 11/2        // = 5.5
            

char

char myCharacter = '!';
            

charAt (Strings)

CharacterMy phone
Index01234567

class

class Book{
	String title;
	String author;

	Book(String titleFromuser, authorFromuser){
		this.title = titleFromuser;
		this.author = authorFromuser;
	}

	public static void main(String[] args){
		//Make a book!
		Book b = new Book("Alice in Wonderland", "Lewis Carroll");
	}
}
            

Concatenate

"Hello" + "there!";         // "Hellothere!"

"Hello" + " there!";        // "Hello there!"
            

constructor

class Book{
    String title;
    String author;

    Book(){
        this.title = "Alice in Wonderland";
        this.author = "Lewis Carroll";
    }
}
            

Decrementor

// These code snippets are equivalent
n--;
n -= 1;
n = n - 1;
            

double

-4.5
9.4949
double d = 500.0;
            

double[]

double[] coins = new double[4];
coins[0] = 0.01;
coins[1] = 0.05;
coins[2] = 0.10;
coins[3] = 0.25;

// Alternatively:
double[] coins = {0.01, 0.05, 0.10, 0.25};

// And then ...
System.out.println(coins[0]);         // prints `0.01`
System.out.println(coins[1]);         // prints `0.05`
            

e, the base of natural logarithms

Math.E;   // 2.71828
            

final

final double PI = 3.14159;
PI = 4.5 // illegal!
            

Find max of two numbers

Math.max(-2.01,-5.4);   // returns -2.01
Math.max(4, 2);         // returns 4
            

Find min of two numbers

Math.min(-2.01,-5.4);   // returns -5.4
Math.min(4, 2);         // returns 2
            

fn-static

Math.abs(-4);
StringUtils.isEmpty(String text);
String.valueOf(boolean b);
            

for loop

for(int i = 0; i < 5; i++){
	System.out.println("i is " + i);
}

/* Prints:
   i is 0
   i is 1
   i is 2
   i is 3
   i is 4
*/
            

function

int addTwo(int x){
	return x + 2;
}

int y = addTwo(4);
System.out.println(y)       // Prints 6
            

If statement

if(2 == 2){
	System.out.println("I'll print!");
}else{
	System.out.println("I won't print!")
};

if(2 != 2){
    System.out.println("I won't print!");
}else{
    System.out.println("I'll print!")
};
            

Incrementor

// These code snippets are equivalent
n++;
n += 1;
n = n + 1;
            

indexOf (String)

String str = "Hello world!";

str.indexOf("World");                   // -1
str.indexOf("world");                   // 7
str.indexOf("world", 10)                // -1
str.indexOf("hi");                      // -1
str.indexOf("Hello world!");            // 0
str.indexOf("!", 10)                    // 12
            

instance

int bills[] = {1, 2, 5, 10, 20, 50, 100};
bills.length;     // returns 7
            

Instance variables

class Book{
    String title;
    String author;

    Book(String titleFromUser, String authorFromUser){
        this.title = titleFromUser;
        this.author = authorFromUser;
    }
}
            

int

49
0
-1045
int i = 3;
            

int[]

int[] grades = new int[3];
grades[0] = 97;
grades[1] = 84;
grades[2] = 92;

// Alternatively:
int[] grades = {97, 84, 92};

// And then ...
System.out.println(grades[0]);         // prints `97`
System.out.println(grades[1]);         // prints `84`

            

Integer division

4 / 2; // = 2
5 / 2; // = 2
6 / 2; // = 4
7 / 2; // = 3
            

lowercase

"HI THERE".toLowerCase();           // "hi there"
"Hello".toLowerCase();              // "hello"
            

main function

public static void main(String[] args){
	//Your program here
}
            

Modulus

0 % 3;      // returns 0
1 % 3;      // returns 1
2 % 3;      // returns 2
3 % 3;      // returns 0
4 % 3;      // returns 1
5 % 3;      // returns 2
6 % 3;      // returns 0
7 % 3;      // returns 1
8 % 3;      // returns 2
9 % 3;      // returns 0
10 % 3;      // returns 1
            

Multiplication

2 * 2;              // returns 4
10.0  * 0.25;       // returns 2.5
            

New line

String s = "First line!\nSecond line!"
System.out.println(s);

First line!
Second line!
            

Next random double

Random gen = new Random();
int d = gen.nextDouble();

// d will be a double in the range 0 <= d < 1
            

Next random integer

Random gen = new Random();
int chosen = gen.nextInt(5);
// chosen will be 0, 1, 2, 3 or 4

Random dice = new Random();
int roll = dice.nextInt(6) + 1;
// roll is a whole number between 1 and 6, inclusive.
            

null

String empty;
empty == null;              // returns true

String blank = "";
blank == null;              // returns false

Object alsoEmpty;
alsoEmpty == null;          // returns true
            

object

class Book{
	String title;
	String author;

	Book(String titleFromuser, authorFromuser){
		this.title = titleFromuser;
		this.author = authorFromuser;
	}

	public static void main(String[] args){
		//Make a book - that's your object
		Book b = new Book("Alice in Wonderland", "Lewis Carroll");
	}
}
            

Parentheses

(5 + 5) / 2.0;      // returns 10.0
5 + 5/2.0;          // returns 7.5
            

pi, the ratio of a circle's circumfrence to its diameter

Math.PI;   // 3.141592653589793
            

Powers

Math.pow(2, 4);   // returns 16
            

Prefix incrementor

int x = 1; 
int y = ++x;

System.out.println(y);          // prints 2
System.out.println(x);          // prints 2

// Versus ...
int x = 1;
int y = x++;

System.out.println(y);          // prints 1
System.out.println(x);          // prints 2


            

print

System.out.println("Yo!");              // prints "Yo!"
System.out.println(1 + 3);              // prints 4
System.out.println(4 == 2 + 2);         // prints true
            

replace (Strings)

"Hello".replace("ll", "mm")         // "Hemmo"
            

return

return;     // ends the method
return 5;   // ends the method, sends back the value 5
return x;   // ends method, sends back the variable x
            

Round a number

Math.round(4.222);    // returns 4
Math.round(-2.444);   // returns -2
            

Round a number down

Math.floor(4.722);    // returns 4
Math.floor(-2.444);   // returns -3
            

Round a number up

Math.ceil(4.222);    // returns 5
Math.ceil(-2.444);   // returns -2
            

Square roots

Math.sqrt(16);   // returns 4
Math.sqrt(66);   // returns 6
Math.sqrt(81);   // returns 9
            

String

String company = "Google";
String state = new String("California");
            

String comparisons

"Jessica".compareTo("Jessica");
0

"Jessica".compareTo("jessica");
-32

"jessica".compareTo("Jessica");
32

"Amy".compareTo("Jessica");
-9

"Amy".compareTo("jessica");
-41

"Stephanie".compareTo("Jessica");
9

"Stephanie".compareTo("jessica");
-23
            

String length

"Measure me".length();	// 10
"Hello".lenght();       // 5
            

String[]

String[] smalltalk = new String[10];
smalltalk[0] = "Hi!";
smalltalk[1] = "How's it going?";
smalltalk[2] = "Have a good day.";

// Alternatively:
String[] smalltalk = {"Hi!", "How's it going?", "Have a good day."};

// And then ...
System.out.println(smalltalk[0]);         // prints `Hi!`
System.out.println(smalltalk[1]);         // prints `How's it going?`

            

substring

"Hello".substring(0);               // "Hello"
"Hello".substring(1);               // "ello"
"Hello".substring(2);               // "llo"
"Hello".substring(3);               // "lo"
"Hello".substring(4);               // "o"
"Hello".substring(5);               // ""
"Hello".substring(6);               // StringIndexOutOfBoundsError


"Hello".substring(0, 5);            // "Hello"
"Hello".substring(0, 4);            // "Hell"
"Hello".substring(0, 3);            // "Hel"
"Hello".substring(0, 2);            // "He"
"Hello".substring(0, 1);            // "H"
"Hello".substring(0, 0);            // ""
            

Subtraction

2 - 2;          // returns 0
10.5 - 0.25;   // returns 10.25
            

uppercase

"hi there".toUpperCase();           // "HI THERE"
"Hello".toUpperCase();              // "HELLO"
            

value

4
"Hello"
false

            

variable

x is the variable in int x = 2; 2 is the value.
            

Variable scope

//The variable 'even' is scoped to the 'isEven' function
boolean isEven(int num){
	boolean even = num % 2 == 0;
	return even;
}
            

while loop

/* Prints
 Spent another $25!
 Spent another $25!
 Spent another $25!
 Spent another $25!
 No money left!
 */
int wallet = 100;
while(wallet > 0){
    wallet = wallet - 25;
    System.out.println("Spent another $25!");
}
System.out.println("No money left!");


/* Prints
 Spent another $25! Now my wallet has $75
 Spent another $25! Now my wallet has $50
 Spent another $25! Now my wallet has $25
 Spent another $25! Now my wallet has $0
 No money left!
 */
int wallet = 100;
while(wallet > 0){
    wallet = wallet - 25;
    System.out.println("Spent another $25! Now my wallet has $" + wallet);
}
System.out.println("No money left!");

/* Prints
 My wallet has $100
 Spent another $25! 
 My wallet has $75
 Spent another $25! 
 My wallet has $50
 Spent another $25!
 My wallet has $25
 Spent another $25!
 No money left!
 */
int wallet = 100;
while(wallet > 0){
    System.out.println("My wallet has $" + wallet);
    wallet = wallet - 25;
    System.out.println("Spent another $25!");
}
System.out.println("No money left!");
            

||

true || true;        // true
true || false;       // true
false || true;       // true
false || false;      // false
            

Contribute, edit, and comment on exercise resources on our mailing list or in our Github repository

Join list Visit repository