0% found this document useful (0 votes)
1 views

Java Basics Part 1 Lab Note

The document outlines the steps to write, compile, and run a Java program, providing a template for structuring the code. It includes a sample program demonstrating sequential, decision, and loop constructs, along with examples of flow control and formatted input/output using the Scanner class. Additionally, it emphasizes the importance of comments and proper formatting in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Java Basics Part 1 Lab Note

The document outlines the steps to write, compile, and run a Java program, providing a template for structuring the code. It includes a sample program demonstrating sequential, decision, and loop constructs, along with examples of flow control and formatted input/output using the Scanner class. Additionally, it emphasizes the importance of comments and proper formatting in Java programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

CO225-Apr2025 : Software Construction

Java Basics

Steps in Writing a Java Program

Step 1: Write the source code Xxx.java using a programming text editor (such as Sublime
Text, Atom, Notepad++, Textpad, gEdit) or an IDE (such as Eclipse or NetBeans).

Step 2: Compile the source code Xxx.java into Java portable bytecode Xxx.class using the
JDK Compiler by issuing command:
javac Xxx.java

Step 3: Run the compiled bytecode Xxx.class with the input to produce the desired output,
using the Java Runtime by issuing command:
java Xxx

Java Program Template


You can use the following template to write your Java programs. Choose a meaningful
"Classname" that reflects the purpose of your program, and write your programming statements
inside the body of the main() method. Don't worry about the other terms and keywords now. I
will explain them in due course. Provide comments in your program!

/**​
* Comment to state the purpose of the program​
*/​
public class Classname { // Choose a meaningful Classname. Save as
"Classname.java"​
public static void main(String[] args) { // Entry point of the program​
// Your programming statements here!!!​
}​
}
A Sample Program Illustrating Sequential, Decision and Loop
Constructs
Below is a simple Java program that demonstrates the three basic programming constructs:
sequential, loop, and conditional.

/**​
* Find the sums of the running odd numbers and even numbers from a given
lowerbound ​
* to an upperbound. Also compute their absolute difference.​
*/​
public class OddEvenSum { // Save as "OddEvenSum.java"​
public static void main(String[] args) {​
// Declare variables​
final int LOWERBOUND = 1;​
final int UPPERBOUND = 1000; // Define the bounds​
int sumOdd = 0; // For accumulating odd numbers, init to 0​
int sumEven = 0; // For accumulating even numbers, init to 0​
int absDiff; // Absolute difference between the two sums​

// Use a while loop to accumulate the sums from LOWERBOUND to
UPPERBOUND​
int number = LOWERBOUND; // loop init​
while (number <= UPPERBOUND) { // loop test​
// number = LOWERBOUND, LOWERBOUND+1, LOWERBOUND+1, ...,
UPPERBOUND​
// A if-then-else decision​
if (number % 2 == 0) { // Even number​
sumEven += number; // Same as sumEven = sumEven + number​
} else { // Odd number​
sumOdd += number; // Same as sumOdd = sumOdd + number​
}​
++number; // loop update for next number​
}​
// Another if-then-else Decision​
if (sumOdd > sumEven) {​
absDiff = sumOdd - sumEven;​
} else {​
absDiff = sumEven - sumOdd;​
}​
// OR using one liner conditional expression​
//absDiff = (sumOdd > sumEven) ? sumOdd - sumEven : sumEven - sumOdd;​

// Print the results​
System.out.println("The sum of odd numbers from " + LOWERBOUND + " to
" + UPPERBOUND + " is: " + sumOdd);​
System.out.println("The sum of even numbers from " + LOWERBOUND + "
to " + UPPERBOUND + " is: " + sumEven);​
System.out.println("The absolute difference between the two sums is:
" + absDiff);​
}​
}

The expected outputs are:


The sum of odd numbers from 1 to 1000 is: 250000
The sum of even numbers from 1 to 1000 is: 250500
The absolute difference between the two sums is: 500
Flow Control

Example code :
// if-then​
int absValue = -5;​
if (absValue < 0) absValue = -absValue; // Only one statement in the
block, can omit { }​

int min = 0, value = -5;​
if (value < min) { // More than one statements in the block, need { }​
min = value;​
System.out.println("Found new min");​
}​

// if-then-else​
int mark = 50;​
if (mark >= 50) ​
System.out.println("PASS"); // Only one statement in the block, can
omit { }​
else { // More than one statements in the block,
need { }​
System.out.println("FAIL");​
System.out.println("Try Harder!");​
}​

// Harder to read without the braces​
int number1 = 8, number2 = 9, absDiff;​
if (number1 > number2) absDiff = number1 - number2;​
else absDiff = number2 - number1;​
Loop Flow Control
Input/Output

Formatted Output via "printf()" (JDK 5)

System.out.print() and println() do not provide output formatting, such as controlling the
number of spaces to print an int and the number of decimal places for a double.

Java SE 5 introduced a new method called printf() for formatted output (which is modeled
after C Language's printf()). printf() takes the following form:
printf(formattingString, arg1, arg2, arg3, ... );

Input From Keyboard via "Scanner" (JDK 5)


import java.util.Scanner; // Needed to use the Scanner​
/**​
* Test input scanner​
*/​
public class ScannerTest {​
public static void main(String[] args) {​
// Declare variables​
int num1;​
double num2;​
String str;​
​ ​
// Read inputs from keyboard ​
// Construct a Scanner named "in" for scanning System.in (keyboard)​
Scanner in = new Scanner(System.in);​
System.out.print("Enter an integer: "); // Show prompting message​
num1 = in.nextInt(); // Use nextInt() to read an int​
System.out.print("Enter a floating point: "); // Show prompting
message​
num2 = in.nextDouble(); // Use nextDouble() to read a double​
System.out.print("Enter a string: "); // Show prompting message​
str = in.next(); // Use next() to read a String token, up
to white space​
in.close(); // Scanner not longer needed, close it​

// Formatted output via printf()​
System.out.printf("%s, Sum of %d & %.2f is %.2f%n", str, num1, num2,
num1+num2);​
}​
}​

You can also use method nextLine() to read in the entire line, including white spaces, but
excluding the terminating newline.
/**​
* Test Scanner's nextLine()​
*/​
import java.util.Scanner; // Needed to use the Scanner​
public class ScannerNextLineTest {​
public static void main(String[] args) {​
Scanner in = new Scanner(System.in);​
System.out.print("Enter a string (with space): ");​
// Use nextLine() to read entire line including white spaces, ​
// but excluding the terminating newline.​
String str = in.nextLine(); ​
in.close();​
System.out.printf("%s%n", str);​
}​
}​

Try not to mix nextLine() and nextInt()|nextDouble()|next() in a program (as you may need to
flush the newline from the input buffer).

You might also like