Top Banner
Advanced Programming in Java Peyman Dodangeh Sharif University of Technology Fall 2013
49

Peyman Dodangeh Sharif University of Technology Fall 2013.

Jan 04, 2016

Download

Documents

Piers Wilcox
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Advanced Programming in Java

Advanced Programming in JavaPeyman DodangehSharif University of TechnologyFall 2013AgendaObject CreationMore on ArraysFor EachVarArgsObject StorageParameter Passing

Sharif University of Technology2public class Dog {private String name;public void setName(String n) {name = n;}public void bark(){System.out.println("Hop! Hop!");}}

Dog d = new Dog(); Object Creation (instantiation)d.setName("Fido"); changing the objects stated.bark(); passing message to objectd is an objectd is a reference to an objectSharif 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 stateSharif University of Technology4new Operatornew creates a new object from specified typenew String();new Book();new int(); Primitive types are not referencedSharif University of Technology5

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

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

Sharif University of Technology6Object ReferencesRemember C++ pointersWhen 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

Sharif 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

Sharif University of Technology8newnew creates a piece of memoryReturns its referenceWhere is the piece of memory?In HeapWhere is the Heap?LaterSharif 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 : primitivesSharif University of Technology10Primitive-Type Array SampleSharif University of Technology11

Array SamplesSharif University of Technology12

Array ReferencesThere is three type of variable in this codearray referencearray[i] referencesInitial value: nullarray[i] objectsSharif 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;}}

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

Sharif University of Technology15What Does Happen to Students After f() Method Invocation?void f() {Student[] students = new Student[10];for (int i = 0; i < students.length; i++) {students[i] = new Student();students[i].setId(i);}}void g() {f();}

Sharif University of Technology16For EachSharif University of Technology17

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 Technology18

Variable argument listsSharif University of Technology19

Variable argument listsSometimes they are called varargVarargs are actually arrays

Sharif University of Technology20

Where storage livesRegistersStackHeapConstantsNon-RAMSharif University of Technology21Memory HierarchySharif University of Technology22

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

Sharif University of Technology23The 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

Sharif University of Technology24The 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!Sharif University of Technology25Compile 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!Sharif University of Technology26The 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 heapThe objects may become garbageGarbage collection

Sharif University of Technology27Heap 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 metadataSharif University of Technology28Other storagesConstant values are often placed directly in the program codeNon-RAM StorageStreamed objectsPersistent objects

Sharif University of Technology29Primitive 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 objectSharif University of Technology30Java Primitive TypesSharif University of Technology31

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

Sharif University of Technology32

Example 1Sharif University of Technology33public 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);}

Sharif University of Technology34

Parameter PassingParameter Passing StylesCall by valueCall by referenceCall by pointer

Java style : Call by passing value of references!Lets see!Sharif University of Technology36What happens in a method callSharif University of Technology37

C++ Parameter PassingCall by valueCall by pointerCall by referenceSharif University of Technology38void 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);Sharif University of Technology39This 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);Sharif University of Technology40This 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 pointerSharif University of Technology41public void javaMethod(Person first, Person second, int number){

first.age = 12;number = 5;

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

javaMethod(p1, p2, myInt);Sharif University of Technology42Does 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.SwapSharif University of Technology43

Swap (2)Sharif University of Technology44

Call by reference in C++Sharif University of Technology45

Call by reference in C#Sharif University of Technology46

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 mutableSharif University of Technology47Sharif University of Technology48

Sharif University of Technology49