0% found this document useful (0 votes)
2 views61 pages

01 - Java Syntax

The document provides an introduction to Java programming, covering basic syntax, variable declaration, operators, conditional statements, and loops. It includes examples of a simple Java program, the structure of classes and methods, and the use of comments and variables. Additionally, it discusses Java's compiled and interpreted nature, as well as best practices for writing readable code.

Uploaded by

CayCor CayCor
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)
2 views61 pages

01 - Java Syntax

The document provides an introduction to Java programming, covering basic syntax, variable declaration, operators, conditional statements, and loops. It includes examples of a simple Java program, the structure of classes and methods, and the use of comments and variables. Additionally, it discusses Java's compiled and interpreted nature, as well as best practices for writing readable code.

Uploaded by

CayCor CayCor
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/ 61

1

ECSE 250
FUNDAMENTALS OF SOFTWARE
DEVELOPMENT
Lecture 01 - Java syntax

Lili Wei

Material by Giulia Alberini and Michael Langer


3

WHAT ARE WE GOING TO DO TODAY?

▪ A simple Java program


▪ General Java syntax
▪ Variable declaration
▪ Operators
▪ Conditional Statement and Loops
4

JAVA SYNTAX
5

STEPS TO PROGRAMMING IN JAVA

1. public class HelloWorld {


2. public static void main(){
3. System.out.println("Hello, World!");
4. }
5. }

1. Write Java source code and save it as "HelloWorld.java"

2. Compile the program (javac) – it is enough to save your file in IDE

3. Run the program (java) – the run button in IDE

4. As expected, the program simply displays Hello, World! on your screen.


6

JAVA
▪ Java is both compiled and interpreted:
▪ Java compiler translated the source code into bytecode.
▪ As machine language, it is easy and fast to interpret.
▪ Java Virtual Machine (JVM), an interpreter, runs the bytecode.

Java source Interpreter Output


Compiler Byte Code
code (JVM)

➢ Java is a "High-level" programming language and portable


7

FYI: THE BYTECODE OF "HELLO WORLD!"


Compiled from "Hello.java"

public class Hello {


public static int cnt;

public Hello();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);


Code:
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String Hello World!
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return

static {};
Code:
0: iconst_0
1: putstatic #5 // Field cnt:I
4: return
}
Java bytecode instructions (Java 21): https://docs.oracle.com/javase/specs/jvms/se21/html/jvms-6.html
8

CLASSES AND METHODS

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ In this program: HelloWorld is a class, main is a method.


▪ Something similar to functions in Python.
▪ Almost every line of code you will write in Java will be inside a method.
▪ Some exceptional cases will be introduced in later lectures.
▪ Every method you will ever write will be part of a class.
9

CLASSES

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ This program must be saved as a file named HelloWorld.java


▪ Convention: names of classes starts with capital letter.
10

CLASSES

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ A class is a collection of methods.


▪ This program defines a class called HelloWorld which is:
▪ public (we’ll see more about this in later lectures)
▪ defined by what is in between the curly brackets.
11

CURLY BRACES

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ Java uses curly brackets to group things together.


▪ They denote a block of code.
▪ They help us keep track of what parts of the code are related.
▪ If one of them is missing or there’s an extra one
▪ syntax error
12

STATEMENTS

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ A statement is a line of code that performs a basic operation.


▪ All statements in Java end in a semi-colon.
▪ The statement in this program is a print statement: it displays a
message on your screen.
13

METHODS

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ A method is named sequence of statements


▪ These open and close curly brackets tell the computer where the
main method (named block of code) starts and ends.
14

METHODS

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ This program defines a method called main, which is public,


static, and void (but don’t worry about this for now)
▪ The main method is a special one:
▪ The execution of a program always starts from the first statement
in the main method and ends when it finishes the last statement.
15

PRINTING TO THE CONSOLE

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ To print in Java you can use one of the following methods:


▪ System.out.println() – which displays a new line character at the end
▪ System.out.print() – which only display what it receives as input.

▪ NOTE, Java is case-sensitive: System ≠ system ≠ SYSTEM


16

STRINGS

public class HelloWorld {


public static void main (String[] args) {
System.out.println("Hello, World!");
}
}

▪ Phrases that appear in quotation marks are called Strings.

▪ Strings literals must start and end with double quotes.


17

COMMENTS

public class HelloWorld {


// This line is ignored
public static void main (String[] args) {
/* As well as this one
and this one
and this last one */
System.out.println("Hello, World!");
}
}

▪ A single line comment in Java starts with // and ends when you press enter.
▪ A multi-line comment starts with /* and ends with */.
▪ All comments are ignored by the computer.
18

THREE KINDS OF CODE YOU CAN WRITE


Broadly speaking, there are 3 different kinds of ‘lines’ of code you can write:
1. A line of code that does something. These are statements and end with
a semi-colon.

2. Code that defines where a block starts and ends.


These lines either end with an open curly bracket, or the whole line is a
single close curly bracket.

3. A comment.
19

CODE STRUCTURE

▪ All of your methods will be inside a class.

▪ (Almost) all of your statements will be inside of a method.

▪ You can only run a .java file which contains the main method.
20

MOST SPACES ARE OPTIONAL

▪ It is ok to write our program as:

public class HelloWorld { public static void main


(String[] args) { System.out.println("Hello, World!");}}

▪ However, you cannot write

publicstaticvoidmain (String[] args) { ;}}

Indents don’t make a difference! (unlike Python)


21

GOOD PRACTICE
▪ Tabs and newlines are optional, but without them the program becomes
hard to read!
▪ Some editors automatically format the code, but in general it is good
practice to make sure to keep you program organized and easy to read!
▪ Fun video clips: search for “tabs vs spaces silicon valley”.
22

VARIABLES
23

THE LIFE OF A VARIABLE

▪ Declaration

▪ Initialization

▪ Manipulation
24

DECLARATIONS

int aNumber;

▪ When you declare a variable, you give it a name and a type


25

DECLARATIONS

int aNumber;

▪ The type of this variable is int


▪ int is a keyword (reserved word) in Java.
It is short for integer.
26

DECLARATIONS

int aNumber;

▪ The name of this variable is aNumber


▪ This is not a keyword in Java.
▪ aNumber is the name of the place in memory with enough
space to store an integer.
27

ASSIGNMENT – RULES
We can store values inside a variable with an assignment statement.

▪ When we make an assignment we update the variable’s value.


▪ Assignment operator: =
It assigns the value on the right to the variable on the left.

▪ In JAVA, the variable need to have the same type as the value we

assign to it.

▪ Variables must be initialized (assigned for the first time) before they can be
used.
28

ASSIGNMENT – EXAMPLES

Examples:

String today; // the variable "today" is declared

today = "Friday"; // "today" gets initialized

/* the variable "hour" is declared and initialized on the


same line */
int hour = 10;

int date = "Wednesday"; // ILLEGAL!


29

VARIABLES

▪ Declaration:

int a;

a
30

VARIABLES

▪ Declaration:

int a;

▪ Initialization:
a 3
a = 3;
31

VARIABLES

▪ Declaration:

int a;

▪ Initialization:
a 5
a = 3;

▪ New assignment:

a = 5;
32

VARIABLES
We can merge declarations and initializations
▪ Declaration & Initialization:

int a = 3;

a 3
33

NAMING CONVENTIONS

▪ lowerCamelCase for names of variables and methods.


E.g.: catName, isSnowingMethod

▪ UpperCamelCase for names of classes.


E.g.: ShapeClass.
34

OPERATORS
35

STANDARD ARITHMETIC OPERATIONS


▪ Addition ‘+’

▪ Subtraction ‘-’

▪ Multiplication ‘*’
▪ Division ‘/’
▪ The output of the division between two integers is an integer!
▪ Java will always round toward zero.

▪ Modulo (remainder) "%"


▪ It performs integer division and outputs the remainder.
36

THE ‘+’ OPERATOR IS A BIT SPECIAL


▪ If used between numbers, it will add the numbers together

▪ If used between strings, it will concatenate those strings.

▪ What happens in the following example?

Output:
System.out.println( 2 + 3 + "5"); 55
System.out.println("5" + 2 + 3); 523

The two expressions are evaluated from left to right!


37

RELATIONAL OPERATORS

▪ Relational: <, >, <=, >=

▪ Equality: ==, !=

▪ They operates on compatible values (not on String)

▪ Expression containing them evaluate to a boolean value.


38

LOGICAL OPERATORS

▪ Logical operators take boolean expressions (i.e. expressions that


evaluate to a boolean value) as inputs and produce a result of
type boolean

▪ Java has 3 logical operators:


▪ NOT ‘!’
▪ AND ‘&&’
▪ OR ‘||"
39

ORDER OF OPERATIONS
From left to right: ▪ Examples:

1. Parenthesis ▪ 1 + 2 + 3 is treated as

2. ! ▪ (1 + 2) + 3

3. Typecasting ▪ 1 + 2 * 3 is treated as

4. Arithmetic ▪ 1 + (2 * 3)

i. *, /, % ▪ year%4 == 0 && year%100 != 0 || year%400 == 0 is treated as


ii. +, - ▪ ((year%4 == 0) && (year%100 != 0)) || (year%400 == 0)
5. Comparison
▪ Good practice:
i. Relational: <, >, <=, >=
▪ Use parenthesis to write make the code clear
ii. Equality: ==, !=
6. Boolean: &&, ||
40

OPERATION-ASSIGNMENT +=, -=, *=, /=

The following two blocks are equivalent

int x = 2; int x = 2;
x += 5; x = x + 5;

The same notation can be used for subtraction,


multiplication, and division.
41

POST INCREMENT / DECREMENT

▪ Post-increment: x++
▪ Post-decrement: x--
use these notations as statements as well as part of a more complex expression.

The following statements are equivalent:

x++; x = x + 1;

x--; x = x – 1;
42

POST INCREMENT (DECREMENT)

Post Increment: the increment/decrement happens after the statement


is executed.

The following blocks are equivalent:

int x = 5;
int x = 5;
int y = 2*x;
int y = 2*x++; x = x + 1;

y: 10
x: 6
43

PRE INCREMENT / DECREMENT

▪ Pre-increment: ++x
▪ Pre-decrement: --x
use these notations as statements as well as part of a more complex expression.

The following statements are equivalent:

++x; x = x + 1;

--x; x = x – 1;
44

PRE INCREMENT (DECREMENT)

Pre Increment: the increment/decrement happens before the statement


is executed.

The following blocks are equivalent:

int x = 5;
int x = 5;
x = x + 1;
int y = 2*++x; int y = 2*x;

y: 12
x: 6
45

RECOMMENDATION

What are x and y? 8 and 19!


int x = 5;
int y = x++ + ++x + x++;
int x = 5;
int temp1 = x; //5
x = x + 1; //6 (x++)
x = x + 1; //7 (++x)
int temp2 = temp1 + x; // 5 + 7 = 12
y = temp2 + x; // 5 + 7 + 7 = 19
x = x + 1; // 8 (x++)
46

RECOMMENDATION

What are x and y?

int x = 5;
int y = x++ + ++x + x++;

Use ++ or -- by themselves.
DON’T write code with pre/post increment/decrement inside other
expressions. It makes the code harder to read and more error prone.
47

Conditional
Statement and
Loops
48

IF - ELSE IF - ELSE

▪ Only one of these blocks will


if (x > 0) {
get executed. Order matters!
System.out.println("Positive");
▪ As soon as one block is executed,
} else if (x < 0) {
the remaining will be skipped
System.out.println("Negative");
▪ You can have as many else ifs
} else {
as you want
System.out.println("Zero");
▪ The final else is not required.
}
49

IF - ELSE IF - ELSE

▪ The final else is not required.


if (x > 0) {
▪ It is legal (or compilable) without the
System.out.println("Positive"); final else block.
} else if (x < 0) { ▪ The code is equivalent to:
System.out.println("Negative");
if (x > 0) {
} else {
System.out.println("Positive");
System.out.println("Zero");
} else if (x < 0) {
}
System.out.println("Negative");
} else {
}
50

COMMON MISTAKE
What is going to happen?

if (x > 0) ;{
System.out.println("Positive");
} else {
System.out.println("Non positive");
}

▪ Compile-time error!
51

COMMON MISTAKE
What is going to happen?

if (x > 0) ;{
System.out.println("Positive");
}

▪ The statements inside the block will get executed no matter


how the condition evaluates.
52

WHILE LOOP

while (condition) {
// some code
}

The block of code is repeatedly executed as long as


the condition evaluates to true.
53

EXAMPLE

Sum from 0 to 9

int i = 0;
int total = 0;
while (i < 10) {
total += i;
i++;
}
System.out.println(total);
54

COMMON MISTAKE

Forgot to update the variable used in the condition: dead loop

int i = 0;
int total = 0;
while (i < 10) {
total += i;
i++;
}
System.out.println(total);
55

FOR LOOP – GENERAL STRUCTURE

for (statement1; boolean expression; statement2) {


// loop body
}

▪ Any or all of the above statement/expression can be left out.


▪ The semicolons always need to be there.
56

EXAMPLE

for (int i = 1; i <= 10; i++) {


// some code
}
57

EXAMPLE

for (int i = 1; i <= 10; i++) {


// some code
}

The initializer is executed once, before the loop starts.


58

EXAMPLE

for (int i = 1; i <= 10; i++) {


// some code
}

The condition is checked at the beginning of each iteration. If it


evaluates to false, the loop ends. Otherwise, the body is repeated.
59

EXAMPLE

for (int i = 1; i <= 10; i++) {


// some code
}

The update is executed at the end of each iteration.


60

TO RECAP

1) The initializer is executed

2) The condition is checked. If true, the body is executed.


Otherwise, the loop ends.

3) The update is executed and we go back to step 2).


61

JAVA RESOURCES

▪ Check out the free online Java book "How to think like a computer scientist

▪ If you are a Python programmer, you might want to try this documentation

▪ The Java Application Programming Interface (API) is a list of all classes that are
part of the JDK. You can find the complete list
here: https://docs.oracle.com/en/java/javase/21/docs/api/index.html

▪ Codecademy: Free programming language courses in an interacive manner:


https://www.codecademy.com/
62

SUMMARY

▪ Today ▪ Next Time


▪ Java Syntax ▪ Primitive data types
▪ Variables
▪ Operators

▪ Your To-do list


▪ Tutorials start from next week!
▪ Check out myCourses/Ed.
▪ Try to run the code snippets
introduced in class by yourself.
▪ For now, put everything in the main
method!

You might also like