long Exercises

Declare a long

Declare a long variable called distance and assign it the value of 123456789L

Show answer:
long distance = 123456789L;

Fix the error

Why does this code not produce the result you expect?

long score = 123;
Show answer:
long score = 123; // without the suffix 'L', score will be automatically converted to int primitive type

Change a value

Create a long variable speed and assign it 45. Then change its value to 60

Show answer:
long speed = 45L;
speed = 60L;

System.out.println(speed); // prints 60

Maximum value

Print the maximum value a long can store using the Long class

Show answer:
System.out.println(Long.MAX_VALUE); // prints 9223372036854775807

String to long

Convert the string "19" into a long and store it in a variable called total.

Show answer:
long total = Long.parseLong("19");
System.out.println(total); // prints 19

Comparison

Given two long values:

long a = 5L;
long b = 8L;

Use a Long method to determine which value is larger

Show answer:
long a = 5L;
long b = 8L;

long max = Long.max(a, b);
System.out.println(max);

Long size

Write code to print:

  • The size of a long in bits
  • The size of a long in bytes
Show answer:
System.out.println(Long.SIZE);   // 64 bits
System.out.println(Long.BYTES);  // 8 bytes

Fix the error

What is the result of running this code and how can you fix it?

long converted = Long.parseLong("abc");
Show answer:
long converted = Float.parseLong("123"); // String needs to be numeric, otherwise a NumberFormatException will be thrown

Sum two numbers

Sum two long numbers (92233720368L and 10000L)

Show answer:
Long.sum(92233720368L, 10000L) // returns 92233730368


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