Sei sulla pagina 1di 2

TMP2634/TMT2013 Multimedia Programming

Lab 01
Objectives
1.
2.
3.

Learn the basics of Java and try out several sample programs.
Learn how to declare variables and deal with arithmetic expressions.
Deal with String variables and methods.

Preparatory Work
1.
2.
3.

Create a folder named MP on the Desktop.


Create a folder named Labs inside the MP folder.
Create a folder named Lab01 inside the Labs folder (this will be your working folder).

Exercise 1
a.
b.

Open a Terminal Window.


Create a new Java file, i.e., Lab01_Ex1.java using Notepad.
... > Lab01 > notepad Lab01_Ex1.java

c.

Type in the following code.


public class Lab01_Ex1
{
public static void main(String[] args)
{
int answer;
System.out.println("Hello reader.");
System.out.println("Welcome to Java.");
System.out.println("Let's demonstrate a simple calculation.");
answer = 2 + 2;
System.out.println("2 plus 2 is " + answer);
}
}

d.

Compile the program (using a Java compiler) and correct any compilation errors.
... > Lab01 > javac Lab01_Ex1.java

e.

Run the program (using a Java interpreter) to obtain following output:


... > Lab01 > java Lab01_Ex1
Hello reader.
Welcome to Java.
Let's demonstrate a simple calculation.
2 plus 2 is 4

1/2

Exercise 2
a.
b.

Create a new Java file, i.e., Lab01_Ex2.java using Notepad.


Complete the following code to answer the following questions.
public class Lab01_Ex2
{
public static void main(String[] args)
{
int x = 9;
...
}
}

Declare and initialize another two variables: double y = 2.3 and float z = 5.2f.
Display the result of each of the following arithmetic expressions using the
System.out.println() statement. Complete the table.
Arithmetic Expression

Result

Precedence/Priority Rules

x + y * z

20.959999561309814

*, +

x / y * z

20.34782534060271

/, *

x / 2 + y / 2

/,+
/,+

1 + x / 2

%,%,*,+
*,+
/,+

2 - x % 2
x % 5 * 3 + 1
(y + 3) * 2
z / (1 + 1)

Exercise 3
a.
b.

Create a new Java file, i.e., Lab01_Ex3.java using Notepad.


Complete the blanks [ ...] to realize what is shown in the comment lines. Here, you
should start learning on how to find the correct Java method by googling it.
public class Lab01_Ex3
{
public static void main(String[] args)
{
String str1 = "I Love";
String str2 = " Programming";
String str3 = " in Java";
String str4;
System.out.println(...);

// display the length of str1

str4 = ...;
System.out.println(str4);

// concatenate the strings str1, str2,


// and str3 in str4, and display it

System.out.println(...);

// returns the index of the first


// occurrence of the string Love in str1

str1 = ...;
System.out.println(str1);

// convert str1 into uppercase characters,


// and display it

}
}

2/2

Potrebbero piacerti anche