JShell Exercises

Print numbers from 1 to 10 (for loop)

Perform the following operations in JShell:

  • 7 + 3
  • 10 – 4
  • 6 * 5
  • 8 / 2
  • 9 % 4 (modulo operation)
Show answer:
7 + 3     // 10
10 - 4    // 6
6 * 5     // 30
8 / 2     // 4
9 % 4     // 1

Test String Method

Test the length() method on the string "Java Programming" and display the result.

Show answer:
"Java Programming".length()   // 17

String.CharAt()

Use the charAt() method to get the character at index 2 in the string "Hello".

Show answer:
"Hello".charAt(2)  // l

Math.sqrt()

Find the square root of 81 using the Math.sqrt() method.

Show answer:
Math.sqrt(81)  // 9.0

Simple Conditionals

Create a boolean variable isJavaFun and assign it a value of true. Print "I love Java!" if isJavaFun is true.

Show answer:
boolean isJavaFun = true;
if (isJavaFun) {
    System.out.println("I love Java!");  // I love Java!
}

Concatenate Strings

Declare two string variables, firstName and lastName, and concatenate them to print "Hello, [firstName] [lastName]".

Show answer:
String firstName = "John";
String lastName = "Doe";
System.out.println("Hello, " + firstName + " " + lastName);  // Hello, John Doe

Import and Use Scanner

Import java.util.Scanner, create a Scanner object, and ask the user to input their age. Print the message "You are [age] years old.".

Show answer:
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");

Method Testing

Test the String.substring() method on the string "Java Programming" to extract "Programming".

Show answer:
"Java Programming".substring(5)  // Programming

Array Manipulation

Declare an array numbers = {10, 20, 30, 40, 50}. Replace the third element (30) with 100 and print the updated array.

Show answer:
int[] numbers = {10, 20, 30, 40, 50};
numbers[2] = 100;
System.out.println(Arrays.toString(numbers));  // [10, 20, 100, 40, 50]

String.contains()

Test if the string "Hello, World!" contains the substring "World". Print "Yes" if it does, otherwise "No".

Show answer:
String str = "Hello, World!";
if (str.contains("World")) {
    System.out.println("Yes");  // Yes
} else {
    System.out.println("No");
}

Calculate Factorial

Write a Java expression to calculate the factorial of 5 using a loop.

Show answer:
int factorial = 1;
for (int i = 1; i <= 5; i++) {
    factorial *= i;
}
System.out.println(factorial);  // 120


Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories