Study/Java

Java Exercises from W3School

고래상어9 2022. 2. 16. 12:07

Java Data Types.

Add the correct data type for the following variables:

int myNum = 9;
float myFloatNum = 8.99f;
char myLetter = 'A';
boolean myBool = false;
String myText = "Hello World";

byte, short, int, long, float, double, boolean and char are called:

primitive data types.

Type casting - convert double type(myDouble) to an int type:

double myDouble = 9.78d;
int myInt = (int) myDouble;

Java Operators

Multiply 10 with 5, and print the result.

System.out.println(10 * 5);

Divide 10 by 5, and print the result.

System.out.println(10 / 5);

Use the correct operator to increase the value of the variable x by 1.

int x = 10;
++x;

Use the addition assignment operator to add the value 5 to the variable x.

int x = 10;
x += 5;

Java Strings

Fill in the missing part to create a greeting variable of type String and assign it the value Hello.

String greeting = "Hello";

Use the correct method to print the length of the txt string.

String txt = "Hello";
System.out.println(txt.length());

Convert the value of the txt to upper case.

String txt = "Hello";
System.out.println(txt.toUpperCase());

Use the correct operator to concatenate two strings:

String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName + lastName);

Use the correct method to concatenate two strings:

String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));

Return the index(position) of the first occurrence of "e" in the following string:

String txt = "Hello Everybody";
System.out.println(txt.indexOf("e"));

Java Math

Use the correct method to find the highest value of x and y.

int x = 5;
int y = 10;
Math.max(x, y);

Use the correct method to find the square root of x.

int x = 16;
Math.sqrt(x);

Use the correct method to return a random number between 0 (inclusive), and 1(exclusive).

Math.random();

Java Booleans

Fill in the missing parts to print the values true and false:

boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);

Fill in the missing parts to print the value true:

int x = 10;
int y = 9;
System.out.println(x > y);

Java If...Else

Print "Hello World" if x is greater than y.

int x = 50;
int y = 10;4
if (x > y) {
  System.out.println("Hello World");
}

Print "Hello World" if x is equal to y.

int x = 50;
int y = 50;
if (x == y) {
  System.out.println("Hello World");
}

Print "Yes" if x is equal to y, otherwise print "No".

int x = 50;
int y = 50;
if (x == y) {
  System.out.println("Yes")l
} else {
  System.out.println("No");
}

print "1" if x is equal to y, print "2" if x is greater than y, otherwise print "3".

int x = 50;
int y = 50;
if (x == y) {
  System.out.println("1");
} else if (x > y) {
  System.out.println("2");
} else {
  System.out.println("3");
}

Insert the missing parts to complete the following "short hand if . . . else statement" (ternary operator):

int time = 20;
String result = ( time < 18 ) ? "Good day." : "Good evening.";
System.out.println(result);
int time = 20;
String result;
result = (time < 18)? "Good day." : "Good evening.";
System.out.println(result);

Java Switch

Insert the missing parts to complete the following switch statement.

int day = 2;
switch (day) {
  case 1:
    System.out.println("Saturday");
    break;
  case 2:
    System.out.println("Sunday");
    break;
}

Complete the switch statement, and add the correct keyword at the end to specify some code to run if there is no case match in the switch statement.

int day = 4;
switch (day) ;
  case 1:
    System.out.println("Saturday");
    break;
  case 2:
    System.out.println("Sunday");
    break;
  default:
    System.out.println("Weekend");
}

Java Loops

Print i as long as i is less than 6.

int i = 1;
while (i < 6) {
  System.out.println(i);
  i++;
}

Use the do/while loop to print i as long as i is less than 6.

int i = 1;
do {
  System.out.println(i);
  i++;
}
while (i < 6);

Use a for loop to print "Yes" 5 times:

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

Loop through the items in the cars array.

String[] cars = {"Volvo", "BMW", "Ford"};
for (String i : cars) {
  System.out.println(i);
}

Stop the loop if i is 5.

for (int i = 0; i <10; i++) {
  if (i ==5) {
    break;
  }
  System.out.println(i);
}

In the loop, when the value is "4", jump directly to the next value.

for ( int i= 0; i <10; i++) {
  if (i == 4) {
    continue;
  }
  System.out.println(i);
}

Java Arrarys

Create an array of type String called cars.

String[] cars = {"Volvo", "BMW", "Ford"};

Print the second item in the cars array.

String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars[1]);

Change the value from "Volvo" to "Opel", in the cars array.

String[] cars = {"Volvo", "BMW", "Frod"};
cars[0] = "Opel";
System.out.println(cars[0]);

Find out how many elements the cars array have.

String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars.length)

Loop through the items in the cars array.

String[] cars = {"Volvo", "BMW", "Ford"};
for (String i : cars) {
  System.out.println(i);
}

Insert the missing parts to create a two-dimensional array.

int[][] myNumbers = { {1,2,3,4}, {5,6,7} };

Java Methods

Insert the missing part to call myMethod from main.

static void myMethod() {
  System.out.println("I just got executed!");
}

public static void main(String[] args) {
 myMethod();
 }

Insert the missing part to call myMethod from main two times.

static void myMethod() {
  System.out.println("I just got executed!");
}

public static void main(String[] args) {
  myMethod();
  myMethod();
}

Add a frame parameter of type String to myMethod, and output "John Doe".

static void myMethod(String fname) {
  System.out.println(fname + " Doe");
}

public static void main(String[] args) {
 myMethod("John");
 }

Insert the missing part to print the number 8 in main, by using a specific keyword inside myMethod :

static int myMethod(int x) {
 return 5 + x;
}

public static void main(String[] args) {
 System.out.println(myMethod(3));
}

Follow the comments to insert the missing parts of the code below:

// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {

  // If age is less than 18, print "Access denied"
  if (age < 18) {
   System.out.println("Access denied");
  
  // If age is greater than, or equal to, 18, print "Access granted"
  } else {
    System.out.println("Access granted");
  }

}

public static void main(String[] args) {
  // Call the checkAge method and pass along an age of 20
  checkAge(20);
}

Java Classes / Objects

Create a class called MyClass.

public class MyClass

Create an object of MyClass called myObj.

MyClass myObj = new MyClass();

Use myObj to access and print the value of the x attribute of MyClass.

public class MyClass {
  int x = 5;
  
  public static void main(String[] args) {
   MyClass myObj = new MyClass();
   System.out.println(myObj.x);
 }
}

Call myMethod on the object.

public class MyClass {
  public void myMethod() {
    System.out.println("Hello World");
  }
  
  public static void main(String[] args)  {
    MyClass myObj = new MyClass();
    myObj.myMethod();
   }
 }

Create and call a class constructor of MyClass

Follow the comments to insert the missing parts of the code below:

// Create a MyClass class
public class MyClass {
  int x; // Create a class attribute x
  
  // Create a class constructor for the MyClass class
  public MyClass() {
    x = 5; // Set the initial value for the class attribute x to 5
  }
 
 public static void main(String[] args) {
   // Crate an myObj object of class MyClass (This will call the constructor)
   MyClass myObj = new MyClass();
   // Print the value of x
   System.out.println(myObj.x);
  }
}

The class below should not be inherited by other classes. Add the correct modifier:

final class MyClass

Fill in the missing parts to import the java.util.Scanner class from the Java API:

import java.util.Scanner;

The Car class should inherit the attributes and methods from the Vehicle class. Add the correct keyword to make this possible.

class Car extends Vehicle

 

Java Exceptions

Insert the missing parts to handle the error in the code below.

try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]);
} catch (Exception e) {
  System.out.println("Something went wrong.");
}

Insert the missing keyword to execute code, after try..catch regardless of the result.

try {
  int[] myNumbers = {1, 2, 3};
  System.out.println(myNumbers[10]);
} catch (Exception e) {
  System.out.println("Something went wrong.");
} finally {
  System.out.println("The 'try catch' is finished.");
}