Java code examples: An example of everything!

This is a repost of a post I made a few years ago. You might find it useful just to refresh your memory of the syntax of various elementary constructs in Java.

This post contains examples of some of the things we have covered so far. These are code snippets, ie they are not complete programs. Don’t paste them into NetBeans and be surprised when they don’t run. They are supposed to help you write your own code. They are not supposed to be slavishly copied. Please email me if you would like to see any other examples.

Here is a simple if statement:

if (x==3) {
  System.out.println("Hooray! x is equal to three!! Wohoo!!");

Here is an if statement with an else:

if (x!=1234) {
  System.out.println("Sorry. You have entered the wrong code.");
else {
  System.out.println("Access granted.");

Here is an if statement with some else ifs and an else too:

if (colour.equals("Red")) {
  System.out.println("Tomatoes are that colour");
} else if (colour.equals("Blue")) {
  System.out.println("The sea is that colour");
} else if (colour.equals("Yellow")) {
  System.out.println("Bananas are that colour");
} else if (colour.equals("Green")) {
  System.out.println("Cucumbers are that colour");
} else {
  System.out.println("I am not familiar with that colour");

Here is a for loop that prints how many times it has run:

for(int i = 0; i < 10; i++) {
  System.out.println("This loop has now executed " + i + " times.");

Here is some code that gets input from the user:

// (remember to add import java.util.Scanner; at the top of your code)
Scanner in = new Scanner(;
System.out.println("Enter your name:");
String userName = in.readLine();
System.out.println("Enter your age:");
int userInt = in.nextInt();
System.out.println("Hello " + userName + ". You are " + userInt + " years old." );

Here is some code that uses a while loop to get string after string from the user, and stops if the user enters “x”:

String input;
Scanner in = new Scanner(;
System.out.println("Enter some text (x = quit):");
input = in.readLine();
while (!input.equals("x")) {
  System.out.println("That's nice. You entered: " + input);
  input = in.readLine();
System.out.println("You entered an x so goodbye!");

Here is some code that puts the numbers 1 to 10 into an integer array:

int[] myArray = new int[10];
  for (int i = 0; i < 10; i++) {
  myArray[i] = i + 1;

Here is a method that takes a string s and an int n and returns a new string made up of s concatenated n times:

String stringTimes(String s, int n){
  String newString = "";
  for(int i = 0; i < n; i++) {
    newString = newString + s;
  return newString;

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s