0% found this document useful (0 votes)
25 views

Slides Java 2

Uploaded by

frankycoc667
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Slides Java 2

Uploaded by

frankycoc667
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Basics of Java Programming

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

public class Hello {

public static void main(String[] args) {


System.out.println("Hello, world"); Class declaration
}

Note: every statement ends with semi-colon ;


NMCGJ
2024-2025
Basics of Java Programming


A simple Java program (1)

compiler interpreter

Source code Byte code


javac java
(*.java) (*.class)

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

Note: every statement ends with semi-colon ;


NMCGJ
2024-2025
Basics of Java Programming


Comments
– Intended for the reader as documentation
– Two possibilities

Multi-line comment between /* and */

/* This is a comment that


* continues across lines
*/


Single-line comment after //

// This is a one-line comment

NMCGJ
2024-2025
Basics of Java Programming


Declaration of classes
<modifiers> class <class name> {
<variable declarations>
<method declarations>
}

– Collection of variables (storage of data) and methods (actions on data)


– In our example:

Modifiers: public (3 access modifiers: public – private – protected)

Name: HelloDate

Fields: no class variables

Methods: main
NMCGJ
2024-2025
Basics of Java Programming


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)

– Exiting method with value return <variable> ;


NMCGJ
2024-2025
Basics of Java Programming


Variables: primitive types
– Same syntax and operations as in C++
Type Meaning Memory size
byte very small integer (-128,...,127) 8 bits
integers

short small integer 16 bits


int integer 32 bits
long long integer 64 bits
float single-precision floating point number 32 bits
reals

double double-precision floating point number 64 bits


char character (Unicode) 16 bits
boolean true or false

NMCGJ
2024-2025
Basics of Java Programming


Variables: primitive types
– Declaration and assignment
<data type> <variables> ; <variable> = <expression> ;

final <data type> <variable> = <expression> ; constant variable

– 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

– Creating an object with the new keyword


<object name> = new <class name> (<arguments>) ;

– Example: creating a String object


String str = new String("abc"); a String “behaves”
String str = "abc"; like a primitive
NMCGJ
2024-2025
Basics of Java Programming


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

– Default constructor: automatic, when no other constructors


public <class name> () { no parameters
} empty body
NMCGJ
2024-2025
Basics of Java Programming


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

<object name> . <method name> (<arguments>) ;

– Example: let's make a baby object


Baby david = new Baby("David", true, 4.0);
System.out.println(david.name);
david.eat(0.1);
david.poop();
NMCGJ
2024-2025
Basics of Java Programming


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

<type>[] <array name> = new <type>[<integer>] ;

an array is an object

– Example: index of first position


in an array is zero
Baby[] twin = new Baby[2];
twin[0] = new Baby("Oliver", true, 4.0);
twin[1] = new Baby("Olivia", false, 4.0);
NMCGJ
2024-2025
Basics of Java Programming


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

package mypackage; import mypackage.*;

public class MyClass { ...


... MyClass m = new MyClass();
} ...
NMCGJ
2024-2025
Basics of Java Programming


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

– Keywords: public – private – protected



Public: visible to the world (everybody outside and inside the class)

Private: visible only to the class

Protected: visible to the package and all subclasses (inheritance)

Default (friendly), no keyword: visible to the package
NMCGJ
2024-2025
Basics of Java Programming


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;

public Baby(String n, boolean m, double w) { ... }


public void sayHi() { ... }
public void eat(double food) { ... }
public void poop() { ... }
}
NMCGJ
2024-2025
Basics of Java Programming


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

– Step 1: what do we need ?



A class BankAccount
– Each individual account = object
– Keep track of balance
– Make deposits and withdrawals
– Compute interest
– ...

...
NMCGJ
2024-2025
Basics of Java Programming


Making a (simple) Java program
– Step 2.1: defining interfaces
BankAccount myAccount = new BankAccount();

double amount1 = 100, amount2 = 50;


myAccount.deposit(amount1);
myAccount.withdraw(amount2);

double rate = 0.01;


double interest = myAccount.addInterest(rate);

double balance = myAccount.getBalance();


...

NMCGJ
2024-2025
Basics of Java Programming


Making a (simple) Java program
– Step 2.2: UML class diagram

BankAccount UML diagrams help you


understand, discuss, and
design software programs
−balance:double

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

public BankAccount(double initBalance) {


balance = initBalance;
}
...
}
NMCGJ
2024-2025
Basics of Java Programming


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

public void withdraw(double amount) {


balance = balance − amount;
}
...
}
NMCGJ
2024-2025
Basics of Java Programming


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.*;

public class BankProgram {


public static void main(String[] args) {
BankAccount account = new BankAccount();
Scanner reader = new Scanner(System.in);
System.out.print("Deposit in Euro: ");
account.deposit(reader.nextDouble());
reader.close();
System.out.println("Account Balance: "
+ account.getBalance() + "EUR");
}
}
NMCGJ
2024-2025
Basics of Java Programming


Methods: visibility of variables

public double addInterest(double rate) {


double interest = balance * rate;
balance = balance + interest;
return interest;
}

class variable: parameter: local variable:


balance rate interest


Variables inside scope of method

Available during method execution
NMCGJ
2024-2025
Basics of Java Programming


Methods: interchanging data

public double addInterest(double rate) {


double interest = balance * rate;
balance = balance + interest;
return interest;
}

primitives: pass by value


objects: pass by reference

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

You might also like