Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming  Anahita Mohseni Kabir 1/1 04/08/2016.

Similar presentations


Presentation on theme: "Java Programming  Anahita Mohseni Kabir 1/1 04/08/2016."— Presentation transcript:

1 Java Programming  Anahita Mohseni Kabir 1/1 04/08/2016

2 Java Language Platform independent programming language → portable
Similar to C++ in syntax Object-oriented Concurrent programming → multi-threading

3 Features Type checking Garbage collection
No direct access to memory (no pointers) Person[] femaleFamily = family; for (int i=0;i<family.length;i++){ if (family[i].getGender() == 'm'){ ; } for file in os.listdir(dir+"new/"): if file.endswith(".bag"): StartTime = None CSVFile = open(dir,'w') bag = rosbag.Bag(dir+"new/"+file) for topic, msg, t in … bag.close() Java Python

4 Java Bytecode Locally or through network
How it works? Java Source (.java) Java Compiler Java Bytecode (.class) Java Bytecode Locally or through network Class loader/ Bytecode Verifier Java Class Libraries Java Interpreter Just in Time Compiler Runtime System Operating System Hardware Java Virtual Machine or

5 Object Oriented Design (OOD)

6 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 Attributes: Name Age Height Weight Gender Behaviors: Walking Talking Texting Person

7 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

8 OOD: Inheritance Person Teacher Student
Inheritance: each subclass inherits all variables of its superclass Removes duplicated code Subclass can override some of the functions of its superclass Subclass Superclass Person Teacher Student Attributes: Name Age Height Weight Gender Behaviors: Walking Talking Texting

9 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 Creature Person Animal Cat Dog Creatures: A human A cat A dog Talk()

10

11 Java Syntax & Programming Paradigm

12 Reserved Words abstract float super assert for switch boolean goto
synchronized byte if this break implements throw import throws case instanceof transient catch int try char interface void class long volatile const native while continue new default package false do private true double protected null else public enum return extends short final static finally strictfp

13 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

14 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 class Person{ } Person.java

15 Class Definition

16 … package edu.wpi.lecture.personExample; 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 computeBodyMassIndex() throws ArithmeticException{ 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 ArithmeticException("Division by zero!");

17 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.personExample; import java.lang.Math; public class Person implements Creature{ private String name; private float height; private float weight;

18 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.personExample; import java.lang.Math; public class Person implements Creature{ public double computeBodyMassIndex() throws ArithmeticException{ if (this.height != 0){ double bmi = this.weight / Math.pow((double)this.height,2); The import is needed if the class is in another package ???

19 How to Make a Project? Project name Package name Classes

20 Encapsulation Access Modifiers
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:

21 … package edu.wpi.lecture.personExample; 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 computeBodyMassIndex() throws ArithmeticException{ 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 ArithmeticException("Division by zero!");

22 Variables Define the state of a class Have primitive or class type
Can be private, public or protected public package edu.wpi.lecture.personExample; import java.lang.Math; public class Person implements Creature{ private String name; private float height; private float weight;

23 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

24 Method’s Signature public double computeBodyMassIndex(){
accessSpecifier returnType name argumentList public double computeBodyMassIndex(){ 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)

25 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 no- argument) constructor Have the same name as the class Don’t have returnType 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; }

26 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.computeBodyMassIndex();

27 Inheritance Inheritance Removes duplicated code
Superclass – subclass, parent – child Java only supports single inheritance: any class can have at most one superclass, but a class can have any number of subclasses java.lang.Object is at the top of this hierarchy: this is assumed for all the classes equals() toString() clone() Wait() Creature (Interface) Person Animal Cat Dog

28 Creature (Interface) Person Animal Cat Dog
Explicitly call superclass’s constructor other than the default constructor package edu.wpi.lecture.personExample; public class Cat extends Animal{ double meanness = 1.0; public Cat(int numOfLegs,double meanness) { super(numOfLegs); this.meanness = meanness; } @Override public String talk() { return "Meow Meow!"; Creature (Interface) Person Animal Cat Dog package edu.wpi.lecture.personExample; public class Animal implements Creature{ int numOfLegs = 4; public Animal(int numOfLegs) { super(); this.numOfLegs = numOfLegs; } @Override public String talk() { return "Random animal sounds!";

29 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

30 package edu.wpi.lecture.personExample; public interface Creature {
Animal Cat Dog package edu.wpi.lecture.personExample; public interface Creature { public String talk(); } package edu.wpi.lecture.personExample; public class Animal implements Creature{ int numOfLegs = 4; public Animal(int numOfLegs) { super(); this.numOfLegs = numOfLegs; } @Override public String talk() { return "Random animal sounds!";

31 Polymorphism package edu.wpi.lecture.personExample;
import java.util.ArrayList; import java.util.List; public class TestPoly { 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 ArrayList<Creature>(); creatures.add(anahita); creatures.add(cat); for (Creature creature:creatures){ System.out.println(creature.talk()); } Polymorphism

32 Basics

33 Operators Operators Arithmetic 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) ==, !=, >=, <=, >, <

34 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 computeBodyMassIndex() throws ArithmeticException{ 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 ArithmeticException("Division by zero!");

35 Flow of Control Each statement is executed in the order they are written Flow control statements: Conditional: if, if else, else, switch Loop: for, while, do while Escapes: break, continue, return

36 If, Else If, Else public double computeBodyMassIndex(){
if (this.height != 0){ IF-Statement } else{ Else-Statement public double computeBodyMassIndex(){ (this.height != 0) ? IF-Statement : Else-Statement; }

37 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].getName()); } for (Person p:family){ System.out.println(p.getName()); }

38 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].getName()); i++; }

39 Break Causes an exit from the innermost while, for and switch
Person[] femaleFamily = family; for (int i=0;i<family.length;i++){ // System.out.println(family[i].getName()); if (family[i].getGender() == 'm'){ System.out.println( family[i].getName() + " cannot be part of this list! :D"); break; }

40 Continue Can be used with while and for
Causes the innermost loop to start the next iteration Person[] femaleFamily = family; for (int i=0;i<family.length;i++){ if (family[i].getGender() == 'm'){ continue; } System.out.println(family[i].getName());

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

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

43 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

44 Try, Catch & Finally public double computeBodyMassIndex() throws ArithmeticException{ 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 ArithmeticException("Division by zero!"); try{ Double bmi = anahita.computeBodyMassIndex(); FileInputStream file = new FileInputStream("anahita.txt"); int output = file.read(); } catch(ArithmeticException e){ System.out.println(e.getMessage()); } catch (Exception e){ } finally{ System.out.println("Test is done."); }

45 What has not covered? I/O stream Filters Object serialization
Nested classes and anonymous classes Regular expressions Generics Enum types Reflection JavaBeans

46 Reserved Words abstract for switch assert goto synchronized boolean if
this byte implements throw break import throws case instanceof transient catch int try char interface void class long volatile const native while continue new default package false do private true double protected null else public enum return extends short final static finally strictfp float super

47 References


Download ppt "Java Programming  Anahita Mohseni Kabir 1/1 04/08/2016."

Similar presentations


Ads by Google