Java Programming Anahita Mohseni Kabir 11 04082016 1
Java Programming Anahita Mohseni Kabir 1/1 04/08/2016 1
Java Language • Platform independent programming language → portable • Similar to C++ in syntax • Object-oriented • Concurrent programming → multi-threading 2
Features • Type checking • Garbage collection • No direct access to memory (no pointers) Person[] female. Family = family; for (int i=0; i<family. length; i++){ if (family[i]. get. Gender() == 'm'){ ; } } Java for file in os. listdir(dir+"new/"): if file. endswith(". bag"): Start. Time = None CSVFile = open(dir, 'w') bag = rosbag. Bag(dir+"new/"+file) for topic, msg, t in … bag. close() Python 3
How it works? Class loader/ Bytecode Verifier Java Source (. java) Java Class Libraries Java Virtual Machine Java Compiler Java Bytecode Locally or through network Java Interpreter or Just in Time Compiler Runtime System Java Bytecode (. class) Operating System Hardware 4
Object Oriented Design (OOD) 5
Object Oriented Design (OOD) • Structured-Programming: data is separate from program instructions • Object-oriented programming: combines data and program instructions • What is an object: • Contains attributes and behavior Person Attributes: • Name • Age • Height • Weight • Gender • … Person Behaviors: • Walking • Texting • … 6
OOD: Encapsulation • Encapsulation: objects hide their methods (functions) and data (variables) • In java, encapsulation is enabled by using access modifiers such as: public, private and protected 7
OOD: Inheritance • Inheritance: each subclass inherits all variables of its superclass • Removes duplicated code • Subclass can override some of the functions of its superclass Attributes: • Name • Age • Height • Weight • Gender • … Superclass Subclass Person Teacher Student Behaviors: • Walking • Texting • … 8
OOD: Polymorphsim • Polymorphism: objects that belong to the same branch of a hierarchy, when told to do the same thing, can manifest that behavior differently • Java uses inheritance/interfaces to implement polymorphism Creatures: • A human • A cat • A dog Creature Person Animal Cat Talk() Dog 9
10
Java Syntax & Programming Paradigm 11
Reserved Words • • • • • abstract assert boolean byte break byte case catch char class const continue default do double else enum extends finally • • • • • float for goto if implements import instanceof interface long native new package private protected public return short static strictfp • • • • super switch synchronized this throws transient try void volatile while -------false true null 12
Primitive Types • boolean, char, byte, short, int, long, float, double, … • Better performance in comparison to their JDK counterpart (non-primitives) • Primitive values are initialized to zero or false • Non-primitive values (objects) are initialized to NULL Primitive JDK counterpart boolean java. lang. Boolean int java. lang. Integer double java. lang. Double … … 13
Class (Non-primitive Types) • A class is a blueprint for a discrete entity (object) that contains attributes and behavior → Object definition • Each class definition is a separate. java file • Name of the file must match class/object name Person. java class Person{ } … 14
Class Definition 15
package edu. wpi. lecture. person. Example; import java. lang. Math; public class Person implements Creature{ private String name; private float height; private float weight; … public Person(String name, int age, float height, float weight, char gender) { this. name = name; this. age = age; this. height = height; this. weight = weight; this. gender = gender; } public double compute. Body. Mass. Index() throws Arithmetic. Exception{ if (this. height != 0){ double bmi = this. weight / Math. pow((double)this. height, 2); System. out. print(this. name + "'s " + "BMI is: " + bmi); return bmi; } else{ throw new Arithmetic. Exception("Division by zero!"); } 16 }
Packages • A Java package is a mechanism for providing a namespace— an area inside of which names are unique, but outside of which they might not be. • Each dot-separated part is stored as a folder package edu. wpi. lecture. person. Example; import java. lang. Math; public class Person implements Creature{ private String name; private float height; private float weight; … 17
Import statements • Any non-trivial class uses other classes for some functionality, and the import statement is how you tell the Java compiler about them package edu. wpi. lecture. person. Example; import java. lang. Math; public class Person implements Creature{ … ? ? ? The import is needed if the class is in another package public double compute. Body. Mass. Index() throws Arithmetic. Exception{ if (this. height != 0){ double bmi = this. weight / Math. pow((double)this. height, 2); … 18
How to Make a Project? Project name Package name Classes 19
Access Modifiers En ca ps ula • Maintain a boundary between the object’s state and behavior and the outside world • Use private, public, protected or no modifier • Members of a class access levels: tio n 20
package edu. wpi. lecture. person. Example; import java. lang. Math; public class Person implements Creature{ private String name; private float height; private float weight; … public Person(String name, int age, float height, float weight, char gender) { this. name = name; this. age = age; this. height = height; this. weight = weight; this. gender = gender; } public double compute. Body. Mass. Index() throws Arithmetic. Exception{ if (this. height != 0){ double bmi = this. weight / Math. pow((double)this. height, 2); System. out. print(this. name + "'s " + "BMI is: " + bmi); return bmi; } else{ throw new Arithmetic. Exception("Division by zero!"); } 21 }
Variables • Define the state of a class • Have primitive or class type • Can be private, public or protected package edu. wpi. lecture. person. Example; import java. lang. Math; public class Person implements Creature{ private String name; private float height; private float weight; … 22
Methods • A class's methods define its behavior • Takes some parameters, performs some computations, and then optionally returns a value/object • Two main categories: • Constructors: used only to create an instance of a class • All the others: used for any application behavior
Method’s Signature access. Specifier return. Type name argument. List public double compute. Body. Mass. Index(){ double bmi = weight / Math. pow((double)height, 2); System. out. print(this. name + "'s " + "BMI is: " + bmi); return bmi; } Methods can have the same name but they should differ in their argument list (the right method is selected at runtime) 24
Constructor Methods • Specify how to instantiate a class • Default constructor: if you don't provide a constructor, the compiler provides one for you, called the default (or noargument) constructor • Have the same name as the class • Don’t have return. Type public class Person implements Creature{ … public Person(String name, int age, float height, float weight, char gender) { this. name = name; this. age = age; this. height = height; this. weight = weight; this. gender = gender; } … 25
Objects vs. Classes • An object is created by calling one of the constructor methods of a class • Each object is an instance of a class • The dot operator allows you to access public/protected variables and methods of a class • Objects are passed by reference – not value! Person anahita = new Person("Anahita", 24, 0, 90, 'f'); double bmi = anahita. compute. Body. Mass. Index(); 26
In he ri Inheritance • Removes duplicated code Creature • Superclass – subclass, parent – child (Interface) Person ta n ce • Java only supports single inheritance: any class can have at most one superclass, but a class can have any number of subclasses Animal • java. lang. Object is at the top of this hierarchy: this is assumed for all the classes Cat Dog • • equals() to. String() clone() Wait() 27
Explicitly call superclass’s constructor other than the default constructor Creature (Interface) Person Animal Cat Dog package edu. wpi. lecture. person. Example; public class Cat extends Animal{ double meanness = 1. 0; public Cat(int num. Of. Legs, double meanness) { super(num. Of. Legs); this. meanness = meanness; } @Override public String talk() { return "Meow!"; } } package edu. wpi. lecture. person. Example; public class Animal implements Creature{ int num. Of. Legs = 4; public Animal(int num. Of. Legs) { super(); this. num. Of. Legs = num. Of. Legs; } @Override public String talk() { return "Random animal sounds!"; } } 28
Interfaces • An interface specifies the behavior that the implementation provides, but not how it is accomplished • A single class can implement as many interfaces as it wants to 29
Creature (Interface) Person package edu. wpi. lecture. person. Example; public interface Creature { public String talk(); } Animal Cat Dog package edu. wpi. lecture. person. Example; public class Animal implements Creature{ int num. Of. Legs = 4; public Animal(int num. Of. Legs) { super(); this. num. Of. Legs = num. Of. Legs; } @Override public String talk() { return "Random animal sounds!"; } } 30
Po package edu. wpi. lecture. person. Example; import java. util. Array. List; import java. util. List; public class Test. Poly { lym or ph ism public static void main(String[] args) { Person anahita = new Person("Anahita", 24, 0, 90, 'f'); Animal cat = new Cat(4, 0. 9); List<Creature> creatures = new Array. List<Creature>(); creatures. add(anahita); creatures. add(cat); for (Creature creature: creatures){ System. out. println(creature. talk()); } } } 31
Basics 32
Operators • Unary operators: only one operand is needed • Binary operators: two operands are needed • Arithmetic operators: • • ++, -- (higher priority) *, /, %, +=, -=, *=, /= +, Example: a + b % d – c * d / ++b • Relational and conditional operators • Boolean operators: &&, ||, ! (Unary) • ==, !=, >=, <=, >, < 33
Statements and blocks • Statements terminate with ; • A block is a compound statement enclosed in curly brackets • Blocks may contain other blocks and define scope of the variables public double compute. Body. Mass. Index() throws Arithmetic. Exception{ if (this. height != 0){ double bmi = this. weight / Math. pow((double)this. height, 2); System. out. print(this. name + "'s " + "BMI is: " + bmi); return bmi; } else{ throw new Arithmetic. Exception("Division by zero!"); } } 34
Flow of Control • Each statement is executed in the order they are written • Flow control statements: • Conditional: if, if else, switch • Loop: for, while, do while • Escapes: break, continue, return 35
If, Else public double compute. Body. Mass. Index(){ if (this. height != 0){ IF-Statement } else{ Else-Statement } } public double compute. Body. Mass. Index(){ (this. height != 0) ? IF-Statement : Else-Statement; } 36
For Loop Person anahita = new Person("Anahita", 24, 0, 90, 'f'); Person arman = new Person("Arman", 27, 6, 120, 'm'); Person nazanin = new Person("Nazanin", 26, 6, 85, 'f'); Person[] family = {anahita, arman, nazanin}; for (int i=0; i<family. length; i++){ System. out. println(family[i]. get. Name()); } for (Person p: family){ System. out. println(p. get. Name()); } 37
While Loop Person anahita = new Person("Anahita", 24, 0, 90, 'f'); Person arman = new Person("Arman", 27, 6, 120, 'm'); Person nazanin = new Person("Nazanin", 26, 6, 85, 'f'); Person[] family = {anahita, arman, nazanin}; int i=0; while(i<family. length){ System. out. println(family[i]. get. Name()); i++; } 38
Break • Causes an exit from the innermost while, for and switch Person[] female. Family = family; for (int i=0; i<family. length; i++){ // System. out. println(family[i]. get. Name()); if (family[i]. get. Gender() == 'm'){ System. out. println( family[i]. get. Name() + " cannot be part of this list! : D"); break; } } 39
Continue • Can be used with while and for • Causes the innermost loop to start the next iteration Person[] female. Family = family; for (int i=0; i<family. length; i++){ if (family[i]. get. Gender() == 'm'){ continue; } System. out. println(family[i]. get. Name()); } 40
Collections • Iterable • Most commonly used collection classes: • Arrays: fixed size • Lists (interface): length is not fixed -> add, remove functions • Sets (interface): contain unique items • Maps: a set of (key, value). key is unique. 41
Arrays • A list of similar objects/primitives • Has fixed name, type, length • The elements are accessed by their index (starting from 0) Person anahita = new Person("Anahita", 24, 0, 90, 'f'); Person arman = new Person("Arman", 27, 6, 120, 'm'); Person nazanin = new Person("Nazanin", 26, 6, 85, 'f'); Person[] family = {anahita, arman, nazanin}; Person[] family = new Person[3]; family[0] = anahita; family[1] = arman; family[2] = nazanin; 42
Exceptions • Handle situations in which your code doesn't work exactly as planned • Two types: • Checked exceptions: are checked by the compiler (meaning the compiler makes sure that they get handled somewhere in your code). • Unchecked exceptions (also called runtime exceptions): are not checked by the compiler. Shlomo Hershkop 43
Try, Catch & Finally public double compute. Body. Mass. Index() throws Arithmetic. Exception{ if (this. height != 0){ double bmi = this. weight / Math. pow((double)this. height, 2); System. out. print(this. name + "'s " + "BMI is: " + bmi); return bmi; } else{ throw new Arithmetic. Exception("Division by zero!"); } } try{ Double bmi = anahita. compute. Body. Mass. Index(); File. Input. Stream file = new File. Input. Stream("anahita. txt"); int output = file. read(); } catch(Arithmetic. Exception e){ System. out. println(e. get. Message()); } catch (Exception e){ System. out. println(e. get. Message()); } finally{ System. out. println("Test is done. "); } 44
What has not covered? • I/O stream • Filters • Object serialization • Nested classes and anonymous classes • Regular expressions • Generics • Enum types • Reflection • Java. Beans • … 45
Reserved Words • • • • • abstract assert boolean byte break case catch char class const continue default do double else enum extends finally float • • • • • for goto if implements import instanceof interface long native new package private protected public return short static strictfp super • • • • switch synchronized this throws transient try void volatile while -------false true null 46
References • https: //www. ibm. com/developerworks/java/tutorials/j-introtojava 1/ • https: //docs. oracle. com/javase/tutorial/java. OO/accesscontrol. html • http: //www. slideshare. net/intelligotech/java-tutorial-ppt-7189933 47
- Slides: 47