Basics of Java Programming. Hendrik Speleers

Similar documents
Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

OOSD. Introduction to JAVA. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. September 12, 2011

OOSD. Introduction to JAVA. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. September 29, 2010

Computational Expression

CS 231 Data Structures and Algorithms, Fall 2016

Java Bytecode (binary file)

Array. Prepared By - Rifat Shahriyar

Introduction to Programming Using Java (98-388)

Java Identifiers, Data Types & Variables

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

c) And last but not least, there are javadoc comments. See Weiss.

( &% class MyClass { }

Getting started with Java

Object Declaration. <class name>: the name of the class to which the object belongs <object name>: the name of the object (any valid identifier)

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

1 Shyam sir JAVA Notes

Software and Programming 1

Implementing Classes

Programming Language Concepts: Lecture 2

STUDENT LESSON A5 Designing and Using Classes

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Object-Oriented Programming, Part 2

Software and Programming 1

From C++ to Java. Duke CPS

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Java Fundamentals (II)

Games Course, summer Introduction to Java. Frédéric Haziza

4: Initialization & Cleanup. Guaranteed Initialization with the Constructor. Nuance

Implementing Classes (P1 2006/2007)

Full file at

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Chapter 5 Names, Bindings, Type Checking, and Scopes

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Lec 3. Compilers, Debugging, Hello World, and Variables

Classes and Methods: Classes

Identifiers and Variables

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Object-Oriented Programming

Datatypes, Variables, and Operations

VARIABLES AND TYPES CITS1001

Gaddis: Starting Out with Java: From Control Structures through Objects, 6/e

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Agenda: Notes on Chapter 3. Create a class with constructors and methods.

4. If the following Java statements are executed, what will be displayed?

1B1b Classes in Java Part I

Key Differences Between Python and Java

Object Oriented Programming with Java

Programming with Java

Starting Out with Java: From Control Structures through Data Structures 3e (Gaddis and Muganda) Chapter 2 Java Fundamentals

Introduction to Java

Full file at

Problem Grade Total

Introduction To C#.NET

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Simple Java Reference

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

CS260 Intro to Java & Android 03.Java Language Basics

7. C++ Class and Object

Fall 2017 CISC124 9/16/2017

Elementary Programming

STRUCTURING OF PROGRAM

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

More on Java. Object-Oriented Programming

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

Brief Summary of Java

Encapsulation. Mason Vail Boise State University Computer Science

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Computer Components. Software{ User Programs. Operating System. Hardware

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

PROGRAMMING FUNDAMENTALS

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Computer Components. Software{ User Programs. Operating System. Hardware

The Java programming environment. The Java programming environment. Java: A tiny intro. Java features

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

PIC 20A The Basics of Java

CHAPTER 7 OBJECTS AND CLASSES

Section 2.2 Your First Program in Java: Printing a Line of Text

Java Foundations Certified Junior Associate

LECTURE 2 (Gaya College of Engineering)

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

Programming Language Concepts: Lecture 2

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

Lesson 35..Inheritance

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Full file at

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Java Basic Syntax. Java vs C++ Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

CSC 1214: Object-Oriented Programming

Fundamentals of Programming Data Types & Methods

Transcription:

Hendrik Speleers

Overview Building blocks of a Java program Classes Objects Primitives Methods Memory management Making a (simple) Java program Baby example Bank account system

A Java program Consists of classes (existing ones and/or new ones) Has one class with a main method (to start the program) Each class contains Comments and embedded documentation Import from libraries (by default: java.lang.*) Class declaration Compiling and running javac Hello.java java Hello

A simple Java program (1) // Hello.java // Print "Hello, world" to the console Comments public class Hello { public static void main(string[] args) { System.out.println("Hello, world"); Class declaration Note: every statement ends with semi-colon ;

A simple Java program (1) compiler interpreter Source code (*.java) javac Byte code (*.class) java Hello.java Hello.class

A simple Java program (2) // HelloDate.java import java.util.*; public class HelloDate { public static void main(string[] args) { System.out.println("Hello, it is"); Date date = new Date(); System.out.println(date.toString()); Comments Import from library Class declaration Note: every statement ends with semi-colon ;

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

Declaration of classes <modifiers> class <class name> { <variable declarations> <method declarations> In our example: Modifiers: public (3 access modifiers: public private protected) Name: HelloDate Fields: no class variables Methods: main

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

Variables: primitive types Same syntax and operations as in C++ Type Meaning Memory size integers reals byte very small integer (-128,...,127) 8 bits short small integer 16 bits int integer 32 bits long long integer 64 bits float single-precision floating point number 32 bits double double-precision floating point number 64 bits char character (Unicode) 16 bits boolean true or false

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;

Baby example A class for babies containing name sex (m/f) public class Baby { String name = "Unknown"; boolean ismale = true; double weight = 0.0; int nbpoops = 0; Variables weight (kg) # poops so far How to make Baby objects? void poop() { nbpoops = nbpoops + 1; System.out.println( "Mam, I have pooped." + " Ready the diaper." ); Methods

Declaration and creation of objects Creating an object variable (object declaration) <class name> <object name> ; object: 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"); String str = "abc"; a String behaves like a primitive

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

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;

Using objects 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();

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; Baby(String n, boolean m, double w) { name = n; ismale = m; weight = w; nbbabiesmade = nbbabiesmade + 1;

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

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;

...... 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 Primitive types in the stack stack pointer Object declaration in the stack (a pointer) Object creation in the heap (with the new keyword) david Baby

Memory management Working with primitives int i = 10, j; final double PI = 3.141592; i j PI 10? 3.14

Memory management Working with primitives int i = 10, j; final double PI = 3.141592; j = i; i = 5; pass by value: value is copied i j PI 5 10 3.14

Memory management Working with objects: be careful Baby alex, bob; alex = new Baby(...); bob = alex; pass by reference: only reference is copied, not the entire object alex bob Baby

Memory management Working with objects: be careful Baby alex, bob; alex = new Baby(...); // (1) bob = alex; // (1) bob = new Baby(...); // (2) alex bob Baby (2) Baby (1)

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

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)

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; public class MyClass {... import mypackage.*;... MyClass m = new MyClass();...

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

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() {...

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() {...

UML class diagram Each class is represented by a box Sections: name, variables, methods Special codes for modifiers: public (+), private ( ), protected (#) static (underlined) Relationships between classes Keep it simple Complete diagram is heavy Display only the info required for your purpose -name:string -ismale:boolean -weight:double -nbpoops:int -nbbabiesmade:int Baby +Baby(n:String, m:boolean, w:double) +sayhi() +eat(food:double) +poop() +getname():string...

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

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

Making a (simple) Java program Step 2: 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();...

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

Making a (simple) Java program Step 3.2: constructors public class BankAccount { private double balance; // balance (EUR)... public BankAccount() { balance = 0.0; constructor overloading: unique set of parameters public BankAccount(double initbalance) { balance = initbalance;...

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

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;

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

Making a (simple) Java program UML class diagram balance:double BankAccount UML diagrams help you understand, discuss, and design software programs +BankAccount() +BankAccount(initBalance:double) +getbalance():double +deposit(amount:double) +withdraw(amount:double) +addinterest(rate:double):double

Methods: visibility of variables public double addinterest(double rate) { double interest = balance * rate; balance = balance + interest; return interest; class variable: balance parameter: rate local variable: interest Variables inside scope of method Available during method execution

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

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) {...

Ready for an exercise...