Introduction to Java Programming: Basics, Comments, Loops and More
Introduction to Java Programming
Basics
– Every program has a file name, and that file name must match the name of the class.
– In order for a program to execute successfully, you need to have the following lines of code after the class header:
public class Review { ← class header
public static void main(String[] args) { ← main method header
//insert code here ← your code goes inside the body of the main method
}
}
Input-Process-Output
Every program will have inputs (variable declaration and assignment), processes (calculations, game logic, etc.) and outputs (information provided to solve the problem).
Comments
– Code shows how something is done, but comments explain why a specific, non-obvious design choice or workaround was chosen.
– Proper use of commenting can make code maintenance much easier, as well as making bugs faster to find.
In-Line Comments: brief notes placed on the exact same line as a statement of code.
//This is an example of an in-line comment
Multi-Line Comments: (or block comments) span several lines to provide deeper explanations or context.
/*
* This is an example of a multi-line
* comment. It allows me to write longer
* comments, spanning multiple lines, instead of
* constantly typing “//” for each line
*/
Comment Header: Every program or class you create needs a comment header. This is a comment at the top of the program that describes the purpose of the program.
/*
* The purpose of this program is to
* review everything you need to know
* from Unit 1 (IPO–input, process, output; print; formatting the output;
* arithmetic operators; data types; variables) and
* Unit 2 (decision structures; boolean expressions; logical operators;
* relational operators; for loops–count controlled;
* while loops–used for condition-controlled
* circumstances, input validation, processing data using a sentinel value;
* do while loops–iterates at least once then checks the condition;
* randomly generated numbers; nested loops)
*/
Print Methods for Output
1) System.out.println(“Hello”); ← prints to a new line
System.out.println(“World!”);
Output: Hello
World!
2) System.out.print(“Hello”); ← prints to the same line
System.out.print(“World!”);
Output: HelloWorld!
3) String name = “Alexey”;
double age = 17.5235;
System.out.printf(“Hello %s, I heard that you are %.1f years old!”); ← formats output
Output: Hello Alexey, I heard that you are 17.5 years old!
Formatting Outputs
Escape characters can be used to format the outputs.
System.out.println(“Hello\nWorld!\tYEAHHHH”); ← \n prints to a new line and \t prints a tab
Output: Hello
World! YEAHHHH
This allows you to use just one single println() method instead of multiple if you want to print Strings over multiple lines in the console window.
Data Types and Variable Names
Primitive Data Types:
1) int — integer (positive or negative whole numbers)
2) float/double — decimal values (use double as it is more accurate)
3) boolean — true or false
4) char — ‘a’, ‘A’, … , ‘z’, ‘Z’, ‘1’, ‘!’. These are single characters with a value associated with the ASCII table.
Example:
General Format: dataType variable name = value
int numOfStudents = 30; //variable names have to be indicative of the type of data they hold
double userHeight = 156.5;
boolean gameOver = false;
char multipleChoiceAnswer = ‘B’;
String Reference Variable:
String studentName = “Alexey”;
Since String objects are reference type variables, they have different methods that can be applied:
– studentName.length(); returns the value 6 as Alexey is 6 characters long (this also includes spaces).
– studentName.charAt(0); returns A because A is the very first character (letter in the 0th position of the String).
– studentName.toUpperCase(); makes Alexey turn into ALEXEY.
– studentName.toLowerCase(); makes Alexey turn into alexey.
User Input and Scanner Class
– To get user input, you need to import java.util.Scanner; at the top of the class.
– Then, you need to create a Scanner object: Scanner userInput = new Scanner(System.in);
– Scanner objects require methods from the Scanner class to obtain user information.
Example:
Scanner userInput = new Scanner(System.in); //create Scanner object
System.out.print(“What’s your name? “); //prompt user
String name = userInput.nextLine(); //use Scanner method for obtaining String answer
System.out.print(“What’s your favourite food? “); //prompt user
String favFood = userInput.nextLine(); //use Scanner method for obtaining String answer
System.out.print(“What’s your shoe size? “); //prompt user
double shoeSize = userInput.nextDouble(); //use Scanner method for obtaining a decimal answer
Sequential Programs
Simple programs execute line by line. The order in which the code is written is the order in which it is executed.
Example:
Scanner userInput = new Scanner(System.in); //create Scanner object
//—–INPUT—–
System.out.print(“What’s your name? “); //prompt user
String name = userInput.nextLine(); //use Scanner method for obtaining String answer
System.out.print(“What’s your age? “); //prompt user
double age = userInput.nextDouble(); //use Scanner method for obtaining a decimal answer
System.out.print(“What’s the current year? “); //prompt user
int currentYear = userInput.nextInt(); //use Scanner method for obtaining an integer answer
//—–PROCESS—-
int birthYear = currentYear – age;
//—–OUTPUT—–
System.out.println(“Hi “ + name + ” you are “ + age + ” years old.\n” +
“You were born in “ + birthYear + “.”);
Decision/Selection Structure Programs
Some programs produce different outputs depending on different cases.
Example:
Scanner userInput = new Scanner(System.in); //create Scanner object
//—–INPUT—–
System.out.print(“What’s your age? “); //prompt user
double age = userInput.nextDouble(); //use Scanner method for obtaining a decimal answer
//—–PROCESS & OUTPUT—-
if (age <= 0) {
System.out.println(“Wow, you can’t be a negative or zero age!”);
} else if (age > 0 && age <= 12) { //This checks to see if age is between 0 and 12 (not including 0)
System.out.println(“Wow, you are a tween!”);
} else if (age > 12 && age <= 19) { //This checks to see if age is between 12 and 19 (not including 12)
System.out.println(“Wow, you are a teen!”);
} else if (age > 19 && age <= 25) {
System.out.println(“Wow, you are an adult!”);
} else { //This prints out if age is greater than 25
System.out.println(“Sorry, you’re old!”);
}
Logical Operators
&& (AND) Operator
– If all the boolean expressions tested are true, then the whole boolean expression becomes true.
– All it takes is one boolean expression to be false for the whole boolean expression to be false.
– Best used for checking a range of values.
– We write 0 < x < 10 as (x > 0 && x < 10) in Java.
|| (OR) Operator
– All it takes is at least one of the boolean expressions tested to be true for the whole boolean expression to be true.
– If all the boolean expressions tested are false, then the whole boolean expression is false.
– Best used for checking values outside a range.
– Outside a range of 0 to 10 would be written as (x <= 0 || x >= 10) in Java.
! (NOT) Operator
– Reverses the truth of something.
Relational Operators
– Used to compare and validate primitive data types.
Example:
if (player1 == 1 && player2 == 1) {
System.out.println(“It’s a tie!”);
}
Or you can also say:
if (temperature != 32) {
System.out.println(“This isn’t the optimal temperature.”);
}
String Comparing Methods
– Used to compare and validate String reference objects.
if (player1.equals(“Rock”) && player2.equals(“Rock”)) {
System.out.println(“It’s a tie!”);
}
– Or to sort Strings alphabetically, you can use a different method:
if (name1.compareTo(name2) > 0) {
System.out.println(name1 + ” is greater than “ + name2);
} else if (name1.compareTo(name2) < 0) {
System.out.println(name2 + ” is greater than “ + name1);
} else {
System.out.println(name2 + ” is the same as “ + name1);
}
Repetition Structure Programs
While Loop:
– Condition controlled; it only iterates if the boolean expression is true.
– Used for input validation (get the user to re-enter input if data is invalid).
– Can use a sentinel value (a value that is impossible for a particular sequence of values) to end processing.
Example 1:
while (number <= 5) {
System.out.println(number);
number++; //add one to number
}
Example 2:
while (age <= 0) {
System.out.println(“Please enter a valid age.”);
age = user.nextInt();
}
Do While Loop:
– Condition controlled; but iterates one time for sure, then repeats only if the boolean expression is true.
Example:
do {
number = prompt(“Enter a number between 1 and 10:”);
} while (number < 1 || number > 10);
Repetition Structure Programs (For Loop)
For Loop:
– Count controlled; use when you know the number of iterations ahead of time.
– There are three components:
1) The initialization of the loop control variable, typically i
2) The test or maximum value (once the max value is reached, the loop terminates)
3) Update the loop control variable
Example:
int number = 2;
for (int i = 1; i <= 5; i++) {
System.out.println(number * i); //The output should be 2, 4, 6, 8, 10
}
