University College of Applied SciencesProgramming 1
العربية
Lecture 1 · 100 min

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

  1. Explain what programming is, using an everyday example
  2. Identify the input, processing and output of a simple program
  3. Distinguish between Java, JDK and NetBeans, and describe the path a program takes from a .java file to the JVM
  4. Create a project, write a print statement, and run it
  5. Step through a program line by line with the debugger on this site
  6. Read a simple error message and fix it
In this lecture
  1. Every app we use is built with programming
  2. A calculator takes input, processes it and shows a result
  3. A computer follows instructions literally; it does not guess
  4. Learning Java is like learning a new language
  5. A variable is a name that holds a value the program uses
  6. Three parts work together whenever a program runs
  7. Three terms you need before we start
  8. A program passes through four stops: .java, javac, .class, then the JVM
  9. Create your first NetBeans 8 project in five steps, then use only three areas
  10. Your first program: one line that prints a message
  11. The "Debug line by line" button shows the program running each line
  12. Quotation marks change the meaning of what we write
  13. An error message shows us where to fix the code
  14. A routine for every exercise, plus time-saving shortcuts
  15. Final exercise: a program that prints three lines
  16. Review questions
Part one: what is programming?

Every app we use is built with programming

Mobile apps

Messages, maps and the calculator on your phone.

Desktop programs

Text editors, web browsers and the calculator in Windows.

Websites

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.

WordWhat it means
InstructionsSpecific commands: add, print, save.
OrderedThe computer runs them in sequence, line by line.
PurposeEvery program has a clear task to perform.

A calculator takes input, processes it and shows a result

1. Input

2 and 3. What data did we give the program?

2. Processing

Addition. What operation did we ask for?

3. Output

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);
    }
}
Output
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

Incomplete instruction: "Type my name"

What is the exact name? Which program do we use? Where on the page?

Clear, ordered instructions

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
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
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

ElementIn a human languageIn Java
VocabularyWords such as: book, write, studentReserved keywords such as class, public and int
GrammarWord order and punctuationBraces { } 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?

A variable is a name that holds a value the program uses

firstNumber2int
secondNumber3int
  • 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
intData type: integer
firstNumberVariable name
2Value 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);
    }
}
Output
5

Three parts work together whenever a program runs

PartIts 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.
Examples of operating systems

Windows, macOS on Mac, iOS on iPhone, and Android on most other phones.

A term we will see later: Method

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?

Part two: your IDE and first program

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.

Java

The language we write instructions in: its keywords, symbols and rules.

Java 8
JDK

Java development tools, including the compiler that turns code into a runnable program.

JDK 8u111
NetBeans

An integrated development environment (IDE): write, run and debug code in one place.

NetBeans IDE 8.2
Where do we write code?Verdict
Plain text editorPossible, but no helper tools
NetBeansBest choice: write, run, find errors
Microsoft WordNot suitable for writing code

Which of the three contains the compiler?

A program passes through four stops: .java, javac, .class, then the JVM

  1. Source file: FirstProgram.javaThis is where we write instructions in Java. It is text that people read.
  2. 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.
  3. Bytecode: FirstProgram.classThe compiler produces a file of bytecode: instructions that the Java Virtual Machine understands.
  4. 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");
    }
}
Output
Compiled, then run by the JVM

What does javac produce from a correct FirstProgram.java?

Create your first NetBeans 8 project in five steps, then use only three areas

  1. Open the New Project windowFile, then New Project, or Ctrl+Shift+N.
  2. Choose the project typeJava, then Java Application, then Next.
  3. Name the projectFirstProgram. Keep Create Main Class checked, then Finish.
  4. Open the main classFirstProgram.java opens automatically, with main in it.
  5. Run the projectRun Project, or F6, or the green Run button.
AreaWhat it is for
ProjectsYour project files, including the code file.
Code editorWhere we write and edit instructions.
OutputWhere results and error messages appear.
Output - FirstProgram (run)
run:
Hello, Java!
BUILD SUCCESSFUL (total time: 0 seconds)
The Output window in NetBeans. The run: and BUILD SUCCESSFUL lines come from NetBeans itself, not from your program.

Your first program: one line that prints a message

  1. Write the line inside the braces of main
  2. Predict the output before running
  3. Run itIn the lab press F6; here use the Run button or Ctrl+Enter.
  4. Change the message and run again
package firstprogram;

public class FirstProgram {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}
Output
Hello, Java!
PartMeaning for a beginner
package firstprogram;The package that contains the class (like a folder)
public class FirstProgramDefines the class that holds our example code
mainWhere program execution starts
{ }Start and end of a block of instructions
System.out.printlnPrints 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!");
    }
}
Expected output
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.

  1. Press "Debug line by line"The program pauses and highlights the line about to run. It has not run yet.
  2. Press "Next line" or F8The line runs. Look at the output below the editor, then predict what comes next.
  3. 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);
    }
}
Output
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
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
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");
    }
}
Output
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

    }
}
Expected output
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")
    }
}
Compiler message';' expected
Show the fix
public class Welcome {
    public static void main(String[] args) {
        System.out.println("Welcome");
    }
}
Output
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);
    }
}
Compiler messageunclosed string literal
Show the fix
public class Welcome {
    public static void main(String[] args) {
        System.out.println("Welcome");
    }
}
Output
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

Predict

What will it print?

Run

Press F6.

Explain

Why did this appear?

Modify

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");
    }
}
Output
10 + 5
15
Done
ShortcutWhat it does in NetBeans 8
Ctrl+Shift+NNew project
sout + TabInsert a print statement
F6Run the project
Shift+F6Run the open file
Ctrl+SSave the file
Alt+Shift+FFormat 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

    }
}
Expected output
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?

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
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?