Lab1 (2)
Lab1 (2)
OBJECT-ORIENTED PROGRAMMING
LAB 1: JAVA, HOW TO PROGRAM
I. Objective
After completing this first lab tutorial, you can:
• Set up the Java Environment, compile, and run the Java program.
• Know the primitive types and basic operators in Java.
• Use the basic statements: conditional statements, loop statements, and declare the method in
Java.
• Use input and output syntax in Java.
o Then, open the command prompt (CMD) window and type java -version and
javac -version. If you get the message that provides the information about the
installed Java version, that means you have successfully set up the JDK and Java Path.
• For Java code editor, we strongly recommend Visual Studio Code for your very beginning course
in Java. Besides that, you can use Notepad++ or Sublime Text. After completing this course,
you can use other Java IDE, e.g., NetBeans, Eclipse, and IntelliJ IDEA.
Do the following steps to save the file, compile and run the program (as in Figure 2):
• Open the text editor program (Visual Studio Code, Notepad++, …) and type the above code.
• Save as MyFirstProgram.java.
• Open the command prompt window (CMD) and navigate to the directory where you save the
file.
• Type javac MyFirstProgram.java and press Enter to compile the source code.
• Type java MyFirstProgram to run the program.
• Now, you will see the "Hello World" string on the screen.
1. Basic syntax
In java, you should keep in mind the following points:
• Case Sensitivity: Java is case sensitive, which means the identifier “Hello” and “hello” would
have different meanings in Java.
• Class Names: For all class names, the first letter should be in Upper-Case. If several words are
used to form the name of the class, each inner word's first letters should be in Upper-Case.
Example: class MyFirstProgram
• Method Names: All method names should start with a Lower-Case letter. If several words are
used to form the names of the method, then each inner word's first letter should be in Upper-
Case.
Example: public void methodName()
• Program File Name: The name of the program file has to exactly match the public class name.
Example: public class MyFirstProgram → MyFirstProgram.java
• public static void main(String args[]): Java program processing starts from the
main() method which is a mandatory part of every Java program.
2. Java Identifiers
The identifier is the name used for classes, variables, and methods. To name an identifier in Java, you
should remember the following points:
• All identifiers should begin with a letter (A to Z or a to z), a currency character ($), or an
underscore (_).
• After the first character, identifiers can have any combination of characters.
V. Data Types
In this first lab tutorial, we only focus on primitive data types. For the user-defined data types, we will
discuss later in this course.
byte 0 8 bits
short 0 16 bits
int 0 32 bits
long 0 64 bits
// MyFirstProgram.java
public class MyFirstProgram {
public static void main(String[] args) {
int a = 5, b = 10;
int sum = a + b;
System.out.println("a + b = " + sum);
}
}
Operators Example
2. Relational operators
The followings are the relational operations supported by Java language.
Initial two variables a = 10 and b = 20.
Operators Example
3. Logical operators
The followings are the logical operators supported by Java language.
Initial two variables A = true and B = false.
Operators Example
4. Assignment operators
Operators Example
+= C += A is equivalent to C = C + A
-= C -= A is equivalent to C = C - A
*= C *= A is equivalent to C = C * A
/= C /= A is equivalent to C = C / A
%= C %= A is equivalent to C = C % A
1. while loop
A while loop statement in Java programming language repeatedly executes the target statement as long
as a given condition is true.
Example:
2. for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be
executed a specific number of times. A for loop is useful when you know how many times a task will
be repeated.
Example:
Example:
public class MyFirstProgram {
public static void main(String[] args) {
int i = 0, sum = 0;
do {
sum = sum + i;
i++;
} while (i <= 10);
System.out.println("sum = " + sum);
}
}
Example 2:
public class MyFirstProgram {
public static void main(String[] args) {
int x = 11, y = 12;
if (x < y && x + y >= 10) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
IX. Methods
A Java method is a collection of statements that are grouped to operate. The syntax is as follows:
modifier returnType nameOfMethod (Parameter List) {
// statements
}
Example:
public class MyFirstProgram {
public static int findMax(int a, int b) {
return (a > b) ? a : b;
}
According to the above example, findMax is the static method. So in the main function, you can call
directly without creating a new object. You will learn more about the method in Lab 4.
X. Text Output
Here is a list of the various print functions that we use to output statements:
• print(): This method in Java is used to display text on the console. This text is passed as the
parameter to this method in the form of a String. This method prints the text on the console and
the cursor remains at the end of the text at the console. The next printing takes place from just
here.
Example:
class Demo {
public static void main(String[] args) {
System.out.print("Hello! ");
System.out.print("Hello! ");
System.out.print("Hello! ");
}
}
Output:
Hello! Hello! Hello!
• println(): This method in Java is also used to display text on the console. It prints the text on
the console and the cursor moves to the start of the next line at the console. The next printing
takes place from the next line.
Example:
class Demo {
public static void main(String[] args) {
System.out.println("Hello! ");
System.out.println("Hello! ");
System.out.println("Hello! ");
}
}
Output:
Hello!
Hello!
Hello!
• printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may take multiple
arguments. This is used to format the output in Java.
Example:
class Demo {
public static void main(String args[]) {
int x = 100;
System.out.printf("Printing simple" + " integer: x = %d\n",x);
System.out.printf("Formatted with" + " precision: PI = %.2f\n", Math.PI);
float n = 5.2f;
System.out.printf("Formatted to " + "specific width: n = %.4f\n", n);
n = 2324435.3f;
System.out.printf("Formatted to " + "right margin: n = %20.4f\n", n);
}
}
Output:
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500
Method Description
class MyFirstProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Create a Scanner object
XII. Exercises
1. Write a program to print your name, date of birth, and student ID from the keyboard.
2. Write a program to compute the area of a triangle with a height and base provided by the user.
1
(𝑎𝑟𝑒𝑎 = 2 × 𝑏𝑎𝑠𝑒 × ℎ𝑒𝑖𝑔ℎ𝑡)
e. ∑𝑛𝑖=1 𝑖 2
9. Write a function that displays the Hailstone sequence:
• With some positive number (n > 0):
1. If n is an even number, divide by 2.
2. If n is an odd number, multiply it by 3 and add 1.
3. Repeat the two steps above until n equals 1.
• For example, choose n = 5
10. Write a function to sum the first digit and the last digit of a number.
11. Write a function to count the number of digits in a number.
12. Write a function to reverse the input integer number.
13. Write a function to check whether a number is a palindrome or not.
14. Write a program to simulate a vending machine. This is the output of the demo program, you
can use this output to build your program (Hint: you should use while statement and
switch…case… statement):
-- THE END --