Slides Java 2
Slides Java 2
Hendrik Speleers
Basics of Java Programming
●
Overview
– Building blocks of a Java program
●
Classes
●
Objects
●
Primitives
●
Methods
– Memory management
– Making a (simple) Java program
●
Baby example
●
Bank account system
NMCGJ
2024-2025
Basics of Java Programming
●
A Java program
– Consists of classes (existing ones and/or new ones)
– Has one class with a main method (to start the program)
●
Syntax of a class
– Comments and embedded documentation
– Import from libraries (by default: java.lang.*)
– Class declaration: collection of variables and methods
●
Compiling and running
– javac Hello.java
– java Hello NMCGJ
2024-2025
Basics of Java Programming
●
A simple Java program (1)
// Hello.java
Comments
// Print "Hello, world" to the console
●
A simple Java program (1)
compiler interpreter
Hello.java Hello.class
NMCGJ
2024-2025
Basics of Java Programming
●
A simple Java program (2)
// HelloDate.java Comments
import java.util.*; Import from library
public class HelloDate {
public static void main(String[] args) {
System.out.println("Hello, it is");
Date date = new Date();
Class declaration
System.out.println(date.toString());
}
}
●
Comments
– Intended for the reader as documentation
– Two possibilities
●
Multi-line comment between /* and */
●
Single-line comment after //
NMCGJ
2024-2025
Basics of Java Programming
●
Declaration of classes
<modifiers> class <class name> {
<variable declarations>
<method declarations>
}
●
Declaration of methods
<modifiers> <return type> <method name> (<parameters>) {
<method body>
}
– In our example:
●
Modifiers: public static (it belongs to the class instead of a specific object)
●
Return type: void (= no return value)
●
Name: main
●
Parameters: String args[] (array of strings)
●
Variables: primitive types
– Same syntax and operations as in C++
Type Meaning Memory size
byte very small integer (-128,...,127) 8 bits
integers
NMCGJ
2024-2025
Basics of Java Programming
●
Variables: primitive types
– Declaration and assignment
<data type> <variables> ; <variable> = <expression> ;
– Examples:
int i = 10, j;
j = i + 5;
final double PI = 3.141592;
NMCGJ
2024-2025
Basics of Java Programming
●
Baby example
Class Baby
Baby
Baby Baby
Baby
Baby
Baby Baby
Objects
NMCGJ
2024-2025
Basics of Java Programming
●
Baby example
public class Baby {
– A class for babies String name = "Unknown";
containing boolean isMale = true;
Variables
double weight = 0.0;
●
name
int nbPoops = 0;
●
sex (m/f)
●
weight (kg) void poop() {
nbPoops = nbPoops + 1;
●
# poops so far
System.out.println(
"Mam, I have pooped." Methods
+ " Ready the diaper."
– How to make );
}
Baby objects ? }
NMCGJ
2024-2025
Basics of Java Programming
●
Declaration and creation of objects
– Creating an object variable (object declaration) object:
<class name> <object name> ; an instance of a class
●
Initialization of objects
– The constructor: a special method with class name
<access modifier> <class name> (<parameters>) {
<constructor body>
}
●
Purpose: giving valid values to the class variables for the specific object
●
No return type
●
Baby example
– Let's update the baby class with constructor and some methods
public class Baby {
...
Baby(String n, boolean m, double w) {
name = n; isMale = m; weight = w;
}
void sayHi() {
System.out.println("Hi, my name is " + name);
}
void eat(double food) {
weight = weight + food;
}
}
NMCGJ
2024-2025
Basics of Java Programming
●
Using objects
– Externally accessing a variable + sending a message to an object
<object name> . <variable name> ;
●
Static types and methods
– The static keyword implies
●
The variable/method is part of the class declaration
●
It is unique for the class and NOT for each instance (object)
– Example: keeping track of number of babies made
public class Baby {
static int nbBabiesMade = 0; External acces
Baby(String n, boolean m, double w) { via class name
name = n; isMale = m; weight = w;
nbBabiesMade = nbBabiesMade + 1;
}
}
NMCGJ
2024-2025
Basics of Java Programming
●
Arrays
– An array is a sequence of elements of same type (primitives / objects)
– Declaration and creation
an array is an object
●
Baby example
– Let's make a nursery
public class Nursery {
final int CAPACITY = 25;
Baby[] babies = new Baby[CAPACITY];
int nbBabies = 0;
...
void addBaby(Baby baby) {
// Assume: nbBabies < CAPACITY
babies[nbBabies] = baby;
nbBabies = nbBabies + 1;
}
}
NMCGJ
2024-2025
Basics of Java Programming
●
Memory management
– Different places to store data
...
●
Register: inside the processor, very fast but very limited
●
The stack: in RAM, direct support from processor (stack pointer)
●
The heap: in RAM, general-purpose pool of memory
stack pointer
...
– Primitive types in the stack
– Object declaration in the stack (a pointer)
Object creation in the heap (with the new keyword)
david Baby
NMCGJ
2024-2025
Basics of Java Programming
●
Memory management
– Working with primitives
int i = 10, j;
final double PI = 3.141592;
i 10
j ?
PI 3.14
NMCGJ
2024-2025
Basics of Java Programming
●
Memory management
– Working with primitives
int i = 10, j;
final double PI = 3.141592;
j = i; pass by value:
i = 5; value is copied
i 5
j 10
PI 3.14
NMCGJ
2024-2025
Basics of Java Programming
●
Memory management
– Working with objects: be careful
Baby alex, bob;
bob = new Baby(...);
alex ? bob
Baby
NMCGJ
2024-2025
Basics of Java Programming
●
Memory management
– Working with objects: be careful
Baby alex, bob;
bob = new Baby(...); pass by reference:
alex = bob; only reference is copied,
not the entire object
alex bob
Baby
NMCGJ
2024-2025
Basics of Java Programming
●
Memory management
– Working with objects: be careful
Baby alex, bob;
bob = new Baby(...); // (1)
alex = bob; // (1)
bob = new Baby(...); // (2)
alex bob
Baby (2)
Baby (1)
NMCGJ
2024-2025
Basics of Java Programming
●
Memory management
– Working with primitives: pass by value
– Working with objects: pass by reference
●
Lifetime of objects
– Garbage collector: automatic release of memory after use
– No memory leaks (cf. C++)
NMCGJ
2024-2025
Basics of Java Programming
●
Scoping: visibility and lifetime of variables
– Indicated by curly brackets
– Primitives
int x = 10;
{
int y = 15; both x and y available
}
...
only x available
– Objects
●
Same behavior for object reference (in the stack)
●
Object itself survives the scope (in the heap)
NMCGJ
2024-2025
Basics of Java Programming
●
Package: the library unit
– A package is a collection of class files
●
A mechanism to manage “namespaces” and to avoid clashes with names
– Loading a package with the import keyword
– Adding a class to a package with the package keyword
●
File must belong to the directory specified by package structure
●
Access modifiers
– Purpose: enforcing rules to work with classes/objects
●
Protection of data / methods for internal use
– separation between interface and implementation
●
Prevention of abuse
– keep integrity of objects
●
Baby example
– Let's update the baby class with access control
public class Baby {
private String name = "Unknown";
private boolean isMale = true;
private double weight = 0.0;
private int nbPoops = 0;
private static int nbBabiesMade = 0;
●
Baby example
– Let's update the baby class with access control
public class Baby {
private String name = "Unknown";
...
private static int nbBabiesMade = 0;
...
public String getName() { return name; }
public double getWeight() { return weight; }
public int getNbPoops() { return nbPoops; }
...
public static int getNbBabies() { ... }
}
NMCGJ
2024-2025
Basics of Java Programming
●
UML class diagram
– Each class is represented by a box Baby
●
Sections: name, variables, methods
●
Special codes for modifiers: -name:String
-isMale:boolean
– public (+), private (−), protected (#) -weight:double
– static (underlined) -nbPoops:int
-nbBabiesMade:int
– Relationships between classes
+Baby(n:String, m:boolean, w:double)
– Keep it simple
+sayHi()
●
Complete diagram is heavy +eat(food:double)
●
Display only the info required +poop()
+getName():String
for your purpose
...
NMCGJ
2024-2025
Basics of Java Programming
●
Correct use of names
– Rules:
●
Sequence of Unicode letters and digits, dollar sign “$”, underscore “_”
●
Beginning with a letter and case-sensitive
– Naming conventions:
●
Class names are a collection of nouns, with the first letter of each word capitalized
●
Variable names (object references, arguments, …) have the
first letter lowercase, and first letter of other words capitalized
●
Method names are verbs with the first letter lowercase, and
first letter of other words capitalized
●
Constants are all uppercase, words separated by underscores
●
Package names are all lowercase
NMCGJ
2024-2025
Basics of Java Programming
●
Making a (simple) Java program
– Objective
●
A program that can manage bank accounts
●
E.g., changing balance by deposits and withdrawals, computing interests, ...
●
Making a (simple) Java program
– Step 2.1: defining interfaces
BankAccount myAccount = new BankAccount();
NMCGJ
2024-2025
Basics of Java Programming
●
Making a (simple) Java program
– Step 2.2: UML class diagram
+BankAccount()
+BankAccount(initBalance:double)
+getBalance():double
+deposit(amount:double)
+withdraw(amount:double)
+addInterest(rate:double):double
NMCGJ
2024-2025
Basics of Java Programming
●
Making a (simple) Java program
– Step 3.1: internal data (class variables) + get/set methods
public class BankAccount {
private double balance; // balance (EUR)
/**
* Gets the current balance of the bank account.
* @return the current balance
*/ Javadoc standard
public double getBalance() {
(skipped later on)
return balance;
}
...
}
NMCGJ
2024-2025
Basics of Java Programming
●
Making a (simple) Java program
– Step 3.2: constructors
public class BankAccount {
private double balance; // balance (EUR)
...
public BankAccount() { constructor overloading:
balance = 0.0; unique set of parameters
}
●
Making a (simple) Java program
– Step 3.3: other methods
public class BankAccount {
private double balance; // balance (EUR)
...
public void deposit(double amount) {
balance = balance + amount;
}
●
Making a (simple) Java program
– Step 3.3: other methods
public class BankAccount {
...
/**
* Adds interest to the bank account.
* @param rate – the interest rate
* @return the computed interest
*/
public double addInterest(double rate) {
double interest = balance * rate;
balance = balance + interest;
return interest;
}
}
NMCGJ
2024-2025
Basics of Java Programming
●
Making a (simple) Java program
– Step 4: the main program
import java.util.*;
●
Methods: visibility of variables
●
Variables inside scope of method
●
Available during method execution
NMCGJ
2024-2025
Basics of Java Programming
●
Methods: interchanging data
interest = myAccount.addInterest(rate);
NMCGJ
2024-2025
Basics of Java Programming
●
Methods: overloading
– We can deduce meaning from the context
“wash the shirt” “washShirt the shirt”
“wash the car” instead of “washCar the car”
“wash the dog” “washDog the dog”
– Methods can have the same name, but unique set of parameter types
public void withdraw(double amount) {
...
}
public void withdraw(double amount, double fee) {
...
}
NMCGJ
2024-2025
Basics of Java Programming
●
Ready for an exercise...
NMCGJ
2024-2025