Java Basics
Beginner Java exercises on variables, data types and simple calculations. These are good to practice right after you write your first Java program.
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%sand%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));
}
}
My name is Riya and I am 21 years old.
My name is Riya and I am 21 years old.
How it works
+joins aStringwith other values, and Java changes the number to text.%sand%dinString.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);
}
}
a = 25, b = 10
a = 10, b = 25
How it works
- The first way keeps one value safe in
tempbefore it is replaced. - In the second way,
abecomes 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
doubleto keep the decimals. - Write
9.0 / 5, not9 / 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));
}
}
}
0.0 C = 32.0 F
37.0 C = 98.6 F
100.0 C = 212.0 F
How it works
9.0 / 5is a decimal division (1.8). With9 / 5the answer would be1.printfwith%.1fprints one digit after the decimal point.
Read Java Methods.