Java Basics

Print your name and age with variables

Description: Create a String variable for your name and an int variable for your age. Print the sentence My name is Riya and I am 21 years old. (use your own values).

Hint:

  • Join text and variables with +.
  • Or use String.format() with %s and %d.

Solution

public class Main {
    public static void main(String[] args) {
        String name = "Riya";
        int age = 21;
        System.out.println("My name is " + name + " and I am " + age + " years old.");
        System.out.println(String.format("My name is %s and I am %d years old.", name, age));
    }
}
Output

My name is Riya and I am 21 years old.
My name is Riya and I am 21 years old.

How it works

  • + joins a String with other values, and Java changes the number to text.
  • %s and %d in String.format() are placeholders for text and whole numbers.

Read Java Variables.

Swap two numbers with and without a third variable

Description: Swap the values of a = 10 and b = 25. First use a third variable. Then do it without a third variable.

Hint:

  • With three variables: temp = a; a = b; b = temp;
  • Without: use addition and subtraction.

Solution

public class Main {
    public static void main(String[] args) {
        int a = 10, b = 25;

        int temp = a;           // way 1: a third variable
        a = b;
        b = temp;
        System.out.println("a = " + a + ", b = " + b);

        a = a + b;              // way 2: no third variable
        b = a - b;
        a = a - b;
        System.out.println("a = " + a + ", b = " + b);
    }
}
Output

a = 25, b = 10
a = 10, b = 25

How it works

  • The first way keeps one value safe in temp before it is replaced.
  • In the second way, a becomes the sum, and then each variable gets the other value by subtraction. (Be careful: with very big numbers the sum can overflow.)

Read Java Operators.

Convert Celsius to Fahrenheit

Description: Write a method toFahrenheit(double celsius) using F = C x 9 / 5 + 32. Print the result for 0, 37 and 100 degrees.

Hint:

  • Use double to keep the decimals.
  • Write 9.0 / 5, not 9 / 5 (that is integer division).

Solution

public class Main {
    static double toFahrenheit(double celsius) {
        return celsius * 9.0 / 5 + 32;
    }

    public static void main(String[] args) {
        for (double c : new double[]{0, 37, 100}) {
            System.out.printf("%.1f C = %.1f F%n", c, toFahrenheit(c));
        }
    }
}
Output

0.0 C = 32.0 F
37.0 C = 98.6 F
100.0 C = 212.0 F

How it works

  • 9.0 / 5 is a decimal division (1.8). With 9 / 5 the answer would be 1.
  • printf with %.1f prints one digit after the decimal point.

Read Java Methods.