Introduction to Programming in Java
From a calculator to your first running program
Prepared by: Eng. Badereddin Mohammed Elhalimi
By the end of this lecture you will be able to
- Explain what programming is, using an everyday example
- Identify the input, processing and output of a simple program
- Distinguish between Java, JDK and NetBeans, and describe the path a program takes from a
.javafile to the JVM - Create a project, write a print statement, and run it
- Step through a program line by line with the debugger on this site
- Read a simple error message and fix it
In this lecture
- Every app we use is built with programming
- A calculator takes input, processes it and shows a result
- A computer follows instructions literally; it does not guess
- Learning Java is like learning a new language
- A variable is a name that holds a value the program uses
- Three parts work together whenever a program runs
- Three terms you need before we start
- A program passes through four stops:
.java,javac,.class, then the JVM - Create your first NetBeans 8 project in five steps, then use only three areas
- Your first program: one line that prints a message
- The "Debug line by line" button shows the program running each line
- Quotation marks change the meaning of what we write
- An error message shows us where to fix the code
- A routine for every exercise, plus time-saving shortcuts
- Final exercise: a program that prints three lines
- Review questions
Every app we use is built with programming
Messages, maps and the calculator on your phone.
Text editors, web browsers and the calculator in Windows.
Search engines, learning platforms and online stores.
Each one is a set of instructions written by programmers in a programming language. Programming is writing ordered instructions that a computer follows to solve a problem or perform a task. Today we write our first instructions in Java.
| Word | What it means |
|---|---|
| Instructions | Specific commands: add, print, save. |
| Ordered | The computer runs them in sequence, line by line. |
| Purpose | Every program has a clear task to perform. |
A calculator takes input, processes it and shows a result
2 and 3. What data did we give the program?
Addition. What operation did we ask for?
5. What result did it show?
Input, then processing, then output: a pattern you will see in most programs you write.
The calculator in one line
Press Run. Then change the numbers to 7 and 8 and run again. Where is the input here? The processing? The output?
public class Calculator {
public static void main(String[] args) {
System.out.println(2 + 3);
}
}5
A program takes a student's marks, calculates the average, then shows it. What is the "processing" here?
A computer follows instructions literally; it does not guess
What is the exact name? Which program do we use? Where on the page?
1. Open Notepad. 2. Click inside the page. 3. Type the name: Ahmed. 4. Save the file as name.
Clear, ordered instructions are a core part of programming. Predict the output of the next two programs before revealing the answer.
The text has a spelling mistake. Will the computer correct it?
public class Literal {
public static void main(String[] args) {
System.out.println("Helo, Jaba!");
}
}Show the output
Helo, Jaba!
Why? The computer does not know what you meant; it prints the text exactly as written. The compiler does not object either, because text can be anything.
The instructions are not in alphabetical order. What does the program print?
public class Order {
public static void main(String[] args) {
System.out.println("C");
System.out.println("A");
System.out.println("B");
}
}Show the output
C A B
Why? The computer runs the lines from top to bottom in the order we wrote them, and does not rearrange them. Each println then moves to a new line.
Learning Java is like learning a new language
| Element | In a human language | In Java |
|---|---|---|
| Vocabulary | Words such as: book, write, student | Reserved keywords such as class, public and int |
| Grammar | Word order and punctuation | Braces { } and the semicolon ; |
| Sentence | "The student writes the lesson." | System.out.println("Hi"); |
Java introduces ideas shared by many languages, such as variables, conditions and loops. Each language still has its own rules; knowing Java does not mean you know every language.
Which of these matches "punctuation" in a human language?
class is part of the vocabulary.A variable is a name that holds a value the program uses
- A program often needs to store values while it runs.
- The number 2 is not a variable; the variable is the name that holds it.
- The value can change later, but the name stays the same.
- Variables are not limited to numbers.
The part of int firstNumber = 2; | Meaning |
|---|---|
int | Data type: integer |
firstNumber | Variable name |
2 | Value stored in it |
The calculator with two variables
This is only a first look; a later lecture covers variables in detail. Press Run, then change the two values and run again.
public class TwoNumbers {
public static void main(String[] args) {
int firstNumber = 2;
int secondNumber = 3;
System.out.println(firstNumber + secondNumber);
}
}5
Three parts work together whenever a program runs
| Part | Its role |
|---|---|
| Program (application) | Defines the task and how data and results are handled. |
| Operating system (OS) | Manages hardware resources and gives programs services such as files, input and output. |
| CPU (processor) | Executes the program's instructions, including arithmetic and logic operations. |
Windows, macOS on Mac, iOS on iPhone, and Android on most other phones.
A named group of instructions that performs a task. Addition itself is written directly with the + operator.
Your phone has a maps app and Android. What is Android?
Three terms you need before we start
Where do we write a program, and how do we run it in NetBeans 8? We start by separating three names you will hear often.
The language we write instructions in: its keywords, symbols and rules.
Java 8Java development tools, including the compiler that turns code into a runnable program.
JDK 8u111An integrated development environment (IDE): write, run and debug code in one place.
NetBeans IDE 8.2| Where do we write code? | Verdict |
|---|---|
| Plain text editor | Possible, but no helper tools |
NetBeans | Best choice: write, run, find errors |
Microsoft Word | Not suitable for writing code |
Which of the three contains the compiler?
A program passes through four stops: .java, javac, .class, then the JVM
- Source file:
FirstProgram.javaThis is where we write instructions in Java. It is text that people read. - The compiler:
javacIt checks the code against the rules. If it finds an error it stops and shows a message; otherwise it translates the code. - Bytecode:
FirstProgram.classThe compiler produces a file of bytecode: instructions that the Java Virtual Machine understands. - The Java Virtual Machine: JVMThe JVM runs the bytecode on your device, using the operating system and the CPU.
Watch the two stages
Press Run. "Compiling…" appears for a moment before the JVM runs the program. Then delete the ; and run again: everything stops at the compiler, and the JVM never runs.
public class Path {
public static void main(String[] args) {
System.out.println("Compiled, then run by the JVM");
}
}Compiled, then run by the JVM
What does javac produce from a correct FirstProgram.java?
.class file.Create your first NetBeans 8 project in five steps, then use only three areas
- Open the New Project windowFile, then New Project, or Ctrl+Shift+N.
- Choose the project typeJava, then Java Application, then Next.
- Name the projectFirstProgram. Keep Create Main Class checked, then Finish.
- Open the main class
FirstProgram.javaopens automatically, withmainin it. - Run the projectRun Project, or F6, or the green Run button.
| Area | What it is for |
|---|---|
Projects | Your project files, including the code file. |
| Code editor | Where we write and edit instructions. |
Output | Where results and error messages appear. |
Output - FirstProgram (run)
run:
Hello, Java!
BUILD SUCCESSFUL (total time: 0 seconds)run: and BUILD SUCCESSFUL lines come from NetBeans itself, not from your program.Your first program: one line that prints a message
- Write the line inside the braces of
main - Predict the output before running
- Run itIn the lab press F6; here use the Run button or Ctrl+Enter.
- Change the message and run again
package firstprogram;
public class FirstProgram {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}Hello, Java!
| Part | Meaning for a beginner |
|---|---|
package firstprogram; | The package that contains the class (like a folder) |
public class FirstProgram | Defines the class that holds our example code |
main | Where program execution starts |
{ } | Start and end of a block of instructions |
System.out.println | Prints a value, then moves to a new line |
"Hello, Java!" | Text we want to print exactly as written |
; | Ends the statement |
Change the message
Edit the program so it prints exactly Welcome to Java.
public class Welcome {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}Welcome to Java
Hint 1
Change only the text between the quotation marks, and keep the marks.
Solution
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java");
}
}The "Debug line by line" button shows the program running each line
This site has a debugger on every program: it pauses before each line so you can watch the program work step by step. It is the best way to understand a program that does not do what you expected.
- Press "Debug line by line"The program pauses and highlights the line about to run. It has not run yet.
- Press "Next line" or F8The line runs. Look at the output below the editor, then predict what comes next.
- Press "Continue" or F9The program runs the remaining lines without stopping.
Try the debugger
Press "Debug line by line", then press "Next line" three times. When does each line appear in the output? Then try the same button on the two-variable lab above, and watch the boxes appear and fill.
public class Trace {
public static void main(String[] args) {
System.out.println("Line one");
System.out.println("Line two");
System.out.println(2 + 3);
}
}Line one Line two 5
Quotation marks change the meaning of what we write
An expression without quotation marks. What does it print?
public class NoQuotes {
public static void main(String[] args) {
System.out.println(2 + 3);
}
}Show the output
5
Why? An arithmetic expression: calculated first, then the result is printed.
Now inside quotation marks. What does it print?
public class WithQuotes {
public static void main(String[] args) {
System.out.println("2 + 3");
}
}Show the output
2 + 3
Why? Text: printed exactly as written, while the quotation marks themselves are not printed.
Write both lines together
Change the numbers in both lines. Which line's result is recalculated? Then try 2 * 3 in the first line.
public class Quotes {
public static void main(String[] args) {
System.out.println(2 + 3);
System.out.println("2 + 3");
}
}5 2 + 3
Print the sum, then its result
Print the line 4 + 6 as text, then on the next line print the calculated result of 4 + 6.
public class SumTwice {
public static void main(String[] args) {
// Write two println statements here
}
}4 + 6 10
Hint 1
One line needs quotation marks, and the other does not.
Solution
public class SumTwice {
public static void main(String[] args) {
System.out.println("4 + 6");
System.out.println(4 + 6);
}
}An error message shows us where to fix the code
An error is information that helps us fix the code, and seeing errors while learning is normal. In NetBeans a red mark appears next to the line number, with a red underline under the error. Hover over the mark to read the message.
Deliberate test: the semicolon
We deleted the semicolon at the end of the print line. Read the message, then add it back and run the program again.
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome")
}
}';' expectedShow the fix
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome");
}
}Welcome
Why? The line does not end with ;, so the compiler cannot tell where the statement ends. It stops and produces no .class file.
Another common error: the quotation mark
We forgot to close the text. Fix the line so the program prints Welcome.
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome);
}
}unclosed string literalShow the fix
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome");
}
}Welcome
Why? The first quotation mark starts some text, and the compiler looks for the mark that closes it on the same line, but finds none.
A routine for every exercise, plus time-saving shortcuts
What will it print?
Press F6.
Why did this appear?
Change it and try again.
Apply the four steps
Predict the three lines, run, and explain the difference between them. Then change one number and predict again.
public class Routine {
public static void main(String[] args) {
System.out.println("10 + 5");
System.out.println(10 + 5);
System.out.println("Done");
}
}10 + 5 15 Done
| Shortcut | What it does in NetBeans 8 |
|---|---|
Ctrl+Shift+N | New project |
sout + Tab | Insert a print statement |
F6 | Run the project |
Shift+F6 | Run the open file |
Ctrl+S | Save the file |
Alt+Shift+F | Format the code |
- New to the keyboard? Switch the keyboard to English before typing code (Alt+Shift).
- Parentheses
( ): Shift + 9 and 0. - Braces
{ }: Shift + the two keys right of P. - Quotation mark
": Shift + the key right of the semicolon key. - Semicolon
;: the key right of L.
Final exercise: a program that prints three lines
Three lines
Write a program that prints: the name Ahmed, then the sentence My first Java program, then the result of 10 + 5.
public class FirstProgram {
public static void main(String[] args) {
// Write your three println statements here
}
}Ahmed My first Java program 15
Hint 1
You need three println statements inside main.
Hint 2
Think: should the calculation go inside quotation marks?
Solution
public class FirstProgram {
public static void main(String[] args) {
System.out.println("Ahmed");
System.out.println("My first Java program");
System.out.println(10 + 5);
}
}Review questions
Where did we write the instructions in the program?
main, so our instructions go inside its braces.In which window did the output appear in NetBeans?
Why did we put the text inside quotation marks?
What is the difference in output between these two lines?
public class Review {
public static void main(String[] args) {
System.out.println("10 + 5");
System.out.println(10 + 5);
}
}Show the output
10 + 5 15
Why? The first line is text printed as is, and the second is an expression calculated first.
What is the correct order of a program's path?
javac compiles it to bytecode in a .class file, and the JVM runs it.