Java Programming Exercise – Answers
Part A: Java Program
public class Exercise { public static void main(String[] args) { // Countdown
[Link]("5"); [Link]("4"); [Link]("3");
[Link]("2"); [Link]("1"); // Quote on multiple lines
[Link]("Education is the most powerful weapon");
[Link]("which you can use"); [Link]("to change the world.");
// Keyboard numbers [Link]("1 2 3"); [Link]("4 5 6");
[Link]("7 8 9"); [Link]("0"); // Tuna statement
[Link]("I want to have 24.5 tuna"); // Personal information
[Link]("Hometown: Hargeisa"); [Link]("Area Code: 252");
[Link]("Address: Main Street"); [Link]("Height: 170 cm");
[Link]("Weight: 65 kg"); } }
Part B: Theory Questions
<b>1. Character String vs String Literal:</b><br/>A character string is a sequence of characters
stored in a variable. A string literal is a fixed value written inside double quotes, for example "Hello".
<b>2. Declaring a Variable:</b><br/>A variable is declared by specifying its data type and name.
Example: <br/>int age = 20;
<b>3. Using Variables:</b><br/>Variables are used to store data values that can be changed
during program execution. You assign a value using the equals (=) operator.
<b>4. Creating an Object using new:</b><br/>An object is created using the new keyword.
Example:<br/>Scanner input = new Scanner([Link]);
<b>5. Java Program asking Name, Age, Hometown:</b><br/><pre>import [Link]; public
class Info { public static void main(String[] args) { Scanner sc = new Scanner([Link]);
[Link]("Enter name: "); String name = [Link](); [Link]("Enter age: "); int
age = [Link](); [Link](); [Link]("Enter hometown: "); String town = [Link]();
[Link](name + " " + age + " " + town); } }</pre>
<b>6. Java Program that prints a character string from the user:</b><br/><pre>import
[Link]; public class StringInput { public static void main(String[] args) { Scanner sc = new
Scanner([Link]); [Link]("Enter a string: "); String text = [Link]();
[Link](text); } }</pre>