Lab 2-Introduction To Java (Part 2)
Lab 2-Introduction To Java (Part 2)
Objective
At the end of this lab, the student is able to: Create a Java Program
Compile and Run Java programs
Lecture Review
Example 1:
public class Squaring {
public static void main(String arguments[]) {
int n = 10;
int n2 = n * n;
System.out.println(n + " squared is " + n2);
}
}
The first line of the main method defines a variable int n. This means that the name of the variable is n
and it holds an int data type. The type of every variable in Java must be explicitly declared. Java
provides several primitive data types; the ones you will probably use most frequently, at least at the
beginning, are
boolean, whose value is either true or false,
int, a 32 bit signed integer,
float, a 32 bit floating point number, and
double, a 64 bit floating point number.
Once a variable is declared, it is accessible from anywhere within the smallest block of code that
contains it.
Java supports common mathematical operations such as
+ for addition,
- for subtraction,
* for multiplication,
/ for division, and
% for modulos.
Texts are stored as Strings in Java; for example, we may give an instruction such as
String s = "Some piece of text.";
3. Save this code to a file. The name of the file must be the same as the class name
followed by .java
i. Using the Save in drop-down menu, specify the directory (folder) where
youll save your file. In this example the directory is Lab2 in drive C.
ii. In File name text box, type "ComputeArea.java", including the double
quotation marks.
iii. From the Save as type drop-down menu, choose Text Document.
C:\Lab2\javac ComputeArea.java
If the program is error free, a .class file will be produce, Compute Area.class and the prompt is
ready for the next command, otherwise the compiler will list all the errors found in the program.
Exercises
Instructions
1. Create sourcefile using notepad.
2. Compile and run the class using Dos prompt .
Exercise 1
1. Code the class method ,variables definition and process for each of following :
a) A constant integer named quantity initialized to 5
b) afloating point named price initialized to 59.90
c) A floating point name totalprice
d) Calculated and print the total price :
totalprice = price*quantity
e) A public class Total to calculate and print totalprice
Exercise 2
1. Write a java application SalesTax to calculate sales tax with Purchase amount = 128 and sales
tax 6%.
Exercise 3
1. Given a=3 , b= 4, c=5 , write a java application that will print the result of expressions and
variables value as below:
a) a* 4 + b/2-c * b
b) a-- * (3+b)/2-++ c * b
c) value of a , b and c
Exercise 4
1. Using data type String , write a java program to display Java ! I like it on the console