Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter...

49
Advanced Programming in Java Presented by: Mojtaba Khezrian

Transcript of Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter...

Advanced Programming in Java

Advanced Programming in JavaPresented by: Mojtaba KhezrianAgendaObject CreationObject StorageMore on ArraysParameter PassingFor EachVarArgsSpring 2014Sharif University of Technology2public class Student{private String name;public void setName(String n) {name = n;}public void Research(){System.out.println(Studing!");}}

Student d = new Student(); Object Creation (instantiation)d.setName(Ali"); changing the objects stated.research(); passing message to objectd is an objectd is a reference to an objectSpring 2014Sharif University of Technology3Class DeclarationObject MemoryRemember : an object has state, behavior and identityEach object is stored in memoryMemory address object identityMemory content object stateThe behavior of an object is declared in its class Class declaration is also stored in memoryBut class declaration is stored once for each classFor each object a separate piece of memory is neededTo store its stateSpring 2014Sharif University of Technology4Object ReferencesWhen you declare an object, you declare its referenceString s;Book b;Exception: ?Primitive typesPrimitive types are not actually objectsThey can not have referencesJava references are different from C++ pointersJava references are different from C++ references

Spring 2014Sharif University of Technology5new Operatornew creates a new object from specified typenew String();new Book();new int(); Primitive types are not referencedSpring 2014Sharif University of Technology6

newnew operator creates a new object from the specified typeReturns the reference to the created object

String s = new String();Student d = new Student();Rectangle rectangle = new Rectangle();

Spring 2014Sharif University of Technology7Create ObjectsThis code will not create an object:String str;It just creates a referenceThis is a key difference between Java and C++You can not use str variablestr is nullnull value in javaYou should connect references to real objectsHow to create objects?new

Spring 2014Sharif University of Technology8newnew creates a piece of memoryReturns its referenceWhere is the piece of memory?In HeapWhere is the Heap?LaterSpring 2014Sharif University of Technology9Array in javaArray elements are stored in heapInteger[] inumbers;Person[] people = new Person[5];int N = float[] realNumbers = new float[N];Array elements are references not objectsException : primitivesSpring 2014Sharif University of Technology10Primitive-Type Array SampleSpring 2014Sharif University of Technology11

Array SamplesSpring 2014Sharif University of Technology12

Array ReferencesThere is three type of variable in this codearray referencearray[i] referencesInitial value: nullarray[i] objectsFall 2010Sharif University of Technology13

public class Student {private String name;private Long id;

public String getName() {return name;}public void setName(String name) {this.name = name;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}}

Spring 2014Sharif University of Technology14Array SampleStudent[] students = new Student[10];for (int i = 0; i < students.length; i++) {students[i] = new Student();students[i].setId(i);}

Spring 2014Sharif University of Technology15ReviewRealityObject class (category, type)Person, Book, Ball, Object instanceAli Daei, my laptop, Object AbstractionAbstract Data TypeObject Declaration (Class Declaration)Object InstantiationnewObject in MemorySpring 2014Sharif University of Technology16ExampleReality : PersonSpring 2014Sharif University of Technology17

ExampleObject AbstractionAbstract Data TypeObject Declaration (Class Declaration)

public class Person {private String name;private int age;public void run(){...}public void talk(){...}}Spring 2014Sharif University of Technology18Object Instances in RealityJafarAgha ObjectSpring 2014Sharif University of Technology19

Object Instances in RealityAzamKhanoom ObjectSpring 2014Sharif University of Technology20

ExampleObject Instantiationnew

Person JafarAgha = new Person();JafarAgha.setAge(50);JafarAgha.setName("Jafar");JafarAgha.talk();Person AhmadReza= new Person();

Spring 2014Sharif University of Technology21Objects in Memory50Spring 2014Sharif University of Technology22J|a|f|a|rParameter Passing StylesCall by valueCall by referenceCall by pointer

Java style : Call by passing value of references!Lets see!Fall 2010Sharif University of Technology23What happens in a method callFall 2010Sharif University of Technology24

C++ Parameter PassingCall by valueCall by pointerCall by referenceSpring 2014Sharif University of Technology25void cppMethod(Person byValue, Person*byPointer, Person& byReference){byValue.name = "ali";byPointer->name = "ali";byReference.name = "ali";}Person p1, p3; Person* p2;p2 = new Person();cppMethod(p1, p2, p3);Spring 2014Sharif University of Technology26This is a C++ codeThis is NOT a java code!Does p1.name change?noDoes p2->name change?yesDoes p3.name change?yesvoid cppMethod(Person byValue, Person*byPointer, Person& byReference){Person* newP = new Person;byValue = *newP;byPointer = newP;byReference = *newP;}

cppMethod(p1, p2, p3);Spring 2014Sharif University of Technology27This is a C++ codeThis is NOT a java code!Does p1 change?noDoes p2 change?noDoes p3 change?yesJava Parameter PassingJava has no pointerJava references are different from C++ referencesJava references are more like C++ pointers than C++ referencesA Java reference is something like a limited pointerSpring 2014Sharif University of Technology28public void javaMethod(Person first, Person second, int number){

first.age = 12;number = 5;

Person newP = new Person();second = newP; }

javaMethod(p1, p2, myInt);Spring 2014Sharif University of Technology29Does p1.age change?yesDoes myInt change?noDoes p2 change?noIn java, primitive variables are passed to methods by their valuesReference values are passed by their reference values.SwapFall 2010Sharif University of Technology30

Swap (2)Fall 2010Sharif University of Technology31

Call by reference in C++Fall 2010Sharif University of Technology32

Call by reference in C#Fall 2010Sharif University of Technology33

In javaEverything is passed by valuePrimitive-types are passed by valueReferences are passed by valueBut not the value of the objectthe value of the referenceIf you want to pass something by referenceWrap it in an objectAnd make it mutableFall 2010Sharif University of Technology34Fall 2010Sharif University of Technology35

For eachFor EachFall 2010Sharif University of Technology37

For Each (2)In for each expression, each element is assigned to another variable

If X is a primitive type, element values are copied into item variable

Fall 2010Sharif University of Technology38

Where storage livesRegistersStackHeapConstantsNon-RAMSpring 2014Sharif University of Technology39Memory HierarchySpring 2014Sharif University of Technology40

RegistersFastestInside the CPUNumber of registers are limitedYou dont have direct control over registersIn assembly you have direct access to registersC and C++ have access to this storage to some extent

Spring 2014Sharif University of Technology41The StackIn RAMSlower than register but less limitedMechanism of function call in CPUStack pointer (cp)Support of CPUJava references are (usually) placed on stackPrimitive data types are also (usually) located in stackJava compiler must know the lifetime and size of all the items on the stackJava objects themselves are not placed on the stack

Spring 2014Sharif University of Technology42The stack (cont.)C++ allows allocation of objects on the stackE.g. this code creates an object on the stackPerson p;In C++ it creates an object on the stackIn Java it creates only a reference on the stackThe actual object will be on HeapC++ allows arrays of known size on stackJava does not!Spring 2014Sharif University of Technology43Compile time vs. Run timeSome information are available at compile timeStack elements should be specified in compile timeSo C++ allows these variables on stack:int array[10];Person p;Some information are not available at compile timeSo variable length variables can not be on stackIf n is a variable int array[n] is not allowed in C++Java is simple! No object on stack!Spring 2014Sharif University of Technology44The HeapThis is a general-purpose pool of memory Also in the RAM area All Java objects live hereThe compiler doesnt need to know the length of the variablesnew operator the storage is allocated on the heap

Spring 2014Sharif University of Technology45Heap GenerationsThe heap is split up into generationsThe young generation stores short-lived objects that are created and immediately garbage collectedThe Old generationObjects that persist longer are moved to the old generation also called the tenured generationThe permanent generation (or permgen) is used for class definitions and associated metadataSpring 2014Sharif University of Technology46Other storagesConstant values are often placed directly in the program codeNon-RAM StorageStreamed objectsPersistent objects

Spring 2014Sharif University of Technology47Primitive Typesnew is not efficient for these small variablesint a;char ch;In these cases, automatic variable is created that is not a referenceThe variable holds the value directlyIts placed on the stackMuch more efficientThese primitives are stored on stack, when?When they are inside an objectSpring 2014Sharif University of Technology48Java Primitive TypesSpring 2014Sharif University of Technology49

Primitive Wrapper ClassesUsed to represent primitive values when an Object is requiredAll of them are immutableJava 5 added some shortcuts for their assignment

Spring 2014Sharif University of Technology50

SampleInteger i = new Integer(2);Integer j = new Integer(2);System.out.println(i==j);//Prints false. Why?i = j;//Reference Assignmenti = 2;//OK. A new shortcut in Java5+Long l = 2;//Syntax Error. Why?Long l = 2L;//OKl = i;//Syntax Error. Why?

Spring 2014Sharif University of Technology51

Example 1Spring 2014Sharif University of Technology52public static void main(String[] args) { A parent = new A();}class A { B child = new B(); int e;}class B { int c; int d;}

Example 2public static void foo(String bar){ Integer baz = new Integer(bar);}

Spring 2014Sharif University of Technology53