1 / 55

What is Java? Java is a new programming language from Sun Microsystems. (mid-1995)

Features of Java: Strongly Typed Compiled & Interpreted OO Programming GUI (AWT, Swings) Database Access (JDBC) Network Support (Sockets) Built in Security Run on all computers by layering Lib. on top of any OS

travis
Télécharger la présentation

What is Java? Java is a new programming language from Sun Microsystems. (mid-1995)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Features of Java: Strongly Typed Compiled & Interpreted OO Programming GUI (AWT, Swings) Database Access (JDBC) Network Support (Sockets) Built in Security Run on all computers by layering Lib. on top of any OS Java provides Framework for RE-USABLE components JavaBeans, thin clint/Server JavaRMI, TCP/IP Sockets, Secure browser based software Java Applets. Multi-threading code GC Java has large set of rich libraries. These lib are Building blocks for your systems.Lib are Identical on all java implementations on different computers Robust Language DesignSome common bugs either can’t happen or are caught as soon as they occur. E.g. Array Index bounds,Strongly typedType conversions are checked for validity at run time.The Memory Address Arithmetica common bug in C is not allowed What is Java?Java is a new programming language from Sun Microsystems. (mid-1995) Oracle to take over Sun Microsystems, in a deal worth €5.17 billion ($7.75 billion)

  2. //Rolls colored text across the screen import java.awt.*; Class myframe extends Frame{ static int x=0, y=120; //x,y positions to display message static int i=0; static int LtoR=1; Font fb=new Font(“TimesRoman”, Font.BOLD, 36); String msg[ ]={“java”, “Portable”, “Secure”, “Easy”}; Color color[ ]={Color.blue,Color.yellow,Color.green,Color.red}; public void paint(Graphics g){// called by Run time Lib g.setFont(fb); g.setColor(color[i]); g.drawString(msg[i],x,y); } static public void main(String s[]) throws Exception{ myframe mf= new myframe(); mf.setSize(200,200); int pixelsPerLine=200, totalLines=4; mf.setVisibble(true);

  3. //Rolls colored text across the screen static public void main(String s[]) throws Exception{ myframe mf= new myframe(); mf.setSize(200,200); int pixelsPerLine=200, totalLines=4; mf.setVisibble(true); for (int j=0; j<pixelsPerLine;j++){ Thread.sleep(25); mf.repaint(); if (LtoR==1) { if ( x+=3) < 200) continue; i=++i % 4; // move index to next msg/color x=50;y=0; LtoR=0; } else { if (y+=3 < 200) continue; i= ++i % 4; x=0; y=120, LtoR=1;// move message L to R Next time } }//for }//main } //myframe class

  4. How to Compile… Run? • Get Java kit JDK/SDK form Sun • javac is Java Compiler • java is Java class file executer (JVM) • Save it as myframe.java • Javac myframe.java (compiling….) • Output myframe.class file • Run as java myframe <enter>

  5. Java executables run on all Computers Compile once run it anywhere Windows, Mac, Unix, IBM’s mainframe, Cell Phones, PDA, Smart cards (credit cards with a microprocessor and memory) Java Portability poses a real threat to Microsoft Why software portability matters? MS Office 95,97,2003,XP,2007 are incompatible For Distributed processing over internet portability is Must (Cloud computing) IBM is a strong supporter of Java has 6 incompatible products (Mainframes, Minicomputers, workstations, two kinds of PC and a network computer) Portability offers more choice Software portability is about future proofing your software The biggest Java BenefitJava Portability

  6. Compared with C Memory Address (pointer) arithmetic Preprocessor Automatic Type Conversion Global Functions and variables typedefs Compared with C++ Operator Overloading Multiple Inheritance Multiple ABIs (Application Binary Interface: This is the environment that a program sees at run time e.g format of Executable file; Process address space; hardware details like number, sizes of registers. How Java is Simpler than C/C++Java does not have…

  7. Data Types What are BigInteger and BigDecimal?

  8. Where Storage Lives • Registers: CPU • The Stack: This lives in the General RAM area. Direct Support via Stack Pointer. JVM Know Exact Size, Life time of data to store on stack. Limits on the Flexibility • The Heap: General Purpose pool of memory in RAM area. Java Objects lives there and give flexibility. “new keyword” Takes more time to allocate Heap storage

  9. Static storage: In a fixed loaction (RAM). Available for the entire time a programme is running. • Constant Storage: they can never change • Non-RAM Storage: If data lives completely outside a program it can exist while program is not running. Streamed objects (streams of bytes), persistent objects (objects placed on disk so they hold their state even when the program is terminated.

  10. Scope and Life Time Class Scope { public static void main(String args[ ]){ int x; x=10; if (x=10){ //start new scope int y=20; x=x+y; // both x, y are know here // int x=30; // Compile error System.out.println(“ x and y : ” +x + “ “ + y); } // y=100; // Compile error System.out.println(“ x is= ” +x); } }

  11. Type Conversion and casting Rule 1: The two types are Compatible Rule 2: The Destination type is larger then the source type Widening Conversion e.g. int type is larger enough to hold valid byte, short int a; byte b; b= (byte) a; // narrowing conversion Char and Boolean types are not Compatible with each other and numeric types byte a=40; byte b=50; byte c=100; int d= a* b * c; b=b * 2; // Error b=(byte) (b * 2); Java automatically PROMOTES each byte and short operands to int while evaluating an expression. a* b -> is performed using int If one operand is long then the whole expression is promoted to long

  12. Arrays Length property, Array Index out of Bound Exception double nums[ ]= { 10.1, 11.2, ……. 15.5 } int twoD [ ] [ ]= new int [4] [5]; OR int [ ] [ ] twoD = new int [4] [5]; Equal Length int twoD [ ] [ ]= new int [4] [ ]; for (int i=0; i<4 i++) twoD[0]= new int [5]; for (int j=0; j<5 j++) {…..} twoD[1]= new int [5]; twoD[2]= new int [5]; twoD[3]= new int [5]; Variable Length int twoD [ ] [ ]= new int [4] [ ]; for (int i=0; i<4 i++) twoD[0]= new int [1]; for (int j=0;j< towD[i].length; j++) twoD[1]= new int [2]; {……..} twoD[2]= new int [3]; twoD[3]= new int [4];

  13. The ‘static’ data, method, block & class static data: • It belongs to the Class level, not an individual object level. • Exactly one instance of static data exist • Static data means “Only one for the whole class” class Employee{ String name; long salary; short employee_Id; static int total_employee; // per-class field ……} class StaticTest { static int i=47;} StaticTest st1=new StaticTest();// In some other class or main StaticTest st2=new StaticTest(); both st1.i and st2.i have the same value 47; ref to same memory. bit confusing the better way is StaticTest.i++;

  14. Static methods: • Static methods also called class methods that do some class-wide operations • They operates on Static Data • Unlike per-instance methods they do not apply to an individual object • ClassName.MethodName() • or ObjectRef.MethodName() is Confusing Class Employee{ String name; long salary; short employeeId; static int total_employee; // per-class field static void clear(){ total_employee=0; } static void newHire(){ total_employee++; } ……} Objref.newHire(); //confusing Employee.newHire();// better: ref through the class name

  15. Static Blocks: • A block of code is a series of statements contained in a pair of {…..} • Inside a Class and outside all methods • static block belongs to a class • Static blocks can only access static data Class Employee{ String name; long salary; static int total_payroll; static { System.out.println(“Processing Payroll total “); if (condition) total_payroll=….//some value else total_payroll=….//some value } …} It is executed once when class is first loaded into the JVM. Loading a class means reading in and converting a stream of bits from a file or URL into as known class inside the JVM. A class is loaded on demand when another class refrences it. The bug was fixed in JDK 1.2 Classes are guaranteed not to be Unloaded unless the class that loaded them is also Unloaded.

  16. Static Classes: • Static class also known as “Nested Top Level Class” • A static class is just a declaration of an entire class: • Constructers • Methods • Fields etc. as a Static member of another class A nested top level class is typically used as a handy way to group some related classes more tightly together.

  17. Static Class Java Run Time Lib: Netsed Entry class is used to organization that Everything to do with a hashtable entry is put into the nested class, and any thing to do with the hashtable as a whole is in the hashtable Class. class Hashtable{ private Entry[ ] myTable; //FORWARD REFERENCE to nested class private int count=0; Object get(){ return myTable[--count];} void put(Object key, Object val){ Entry e= new Entry(key,Val); myTable[count++]=e; } static class Entry{ // Nested top level class int hash; Object key, data; Entry(Object k, Object v) { //Constructor.} int hashCode(){…….} } // end of nested class ‘Entry’ …..// other methods of hashtable class } Outside Access: Hashtable.Entry hEntry = new Hashtable.Entry(myKey, MyVal); int Hcode =hEntry.hashCode();

  18. Arithmetic + add - subtract * multiply / div % mod = assign Shorthand += add assign -= sub assign *= mult. assign /= div assign %= mod assign ++ increment -- decrement Arithmetic Bitwise Relational And logical Operators You can not use them on boolean types

  19. << Shift left >> Shift Right >>> Shift right Zero fill Shorthand >>= >>>= <<= ~= &= |= ^= Bitwise ~ Not & AND | OR ^ XOR All integer types except char are signed integers. High order bit is SIGN bit (1=negative or 0=Positive) Java use two’s compliment encoding to store negative numbers. byte b= 42 0010 1010 byte c= -42 1101 0101 (~b) add 1 = 1101 0110 int a=3 // 0011 in binary int b= ~a & 0x0f; // (0000 1111 in binary) What is ? System.out.print(b)= ? In bitwise operations turning On high bit to 1 will cause the resulting value to be interpreted as a negative number.

  20. Example: int val = 0xFFFFFFE; val<<=1; val<<=1; val<<=1; val<<=1; val is NOW negative value F F F F F F E Val= 0000 1111 1111 1111 1111 1111 1111 1110 Val= 0001 1111 1111 1111 1111 1111 1111 1100 Val= 0011 1111 1111 1111 1111 1111 1111 1000 Val= 0111 1111 1111 1111 1111 1111 1111 0000 Val= 1111 1111 1111 1111 1111 1111 1110 0000 -ve of (take compliment (~val)+ add 1) 0000 0000 0000 0000 0000 0000 0001 1111 + 0000 0000 0000 0000 0000 0000 0000 0001 -ve of 0000 0000 0000 0000 0000 0000 0010 0000 val is -32 Bitwise << Shift left (Each time you shift a value to left it double the value)

  21. Each time you shift a value to the right it divides that value by 2 (discard the remainder) +8 -> 0000 1000 >> 1 +4 = 0000 0100 -8 -> 1111 1000 >> 1 -4 = 1111 1100 Right Shifting is with Sign extension i.e. it preserve the sign of negative numbers during right shift. What will you get if you right shift -1 int a= -1; a>>=24; = ? The unsigned right shift is a special case of right shift which is designed for non numeric values like working on some pixel-based values and graphics coordinates. Unsigned right shift fills Zero into the high-order bit. int a= -1; -> 1111 1111 1111 1111 1111 1111 1111 1111 a>>>=24; -> 0000 0000 0000 0000 0000 0000 1111 1111= 255 Bitwise >> Shift Right >>> Shift right Zero fill

  22. The outcome of these operators is boolean value. == equal, != not equal, <, <=, >, >= Testing Object Equivalence: Class TestValue{ int i; } Public class Test{ public static void main(String a[ ]){ Integer n1=new Integer(127); Integer n2=new Integer(127); System.out.println(n1==n2); //1 System.out.println(n1!=n2);// 2 System.out.println(n1.equals(n2));// 3 TestValue v1= new TestValue(); TestValue v2=new TestValue(); v1.i=v2.i=100; System.out.println(v1.equals(v2));//4 } } Logical boolean Operators &,|,^,! Short-circuit && logical || logical

  23. Control Statements if(condition){…} if(condition){….} else {….} if(condition){..} else if(cond2) {..} else {….} switch(exp1){ case val1:Statements; break;//jump out case val2:Statements; break; default: Statements; } while(cond1){……} do{……} while(cond1) for(init;condition;iteration){……} for(i=0,j=5;i<j;i++,j--){…….} //two control var i=comlexExpression(); for( ;!flag;) {…. flag=true;…i+=nonSequentialWay()…..} // complex style for ( ; ; ){ infinite loop } Using break as a form of Goto label1{ label2:{ label3:{ if(true) break label2; } statements1 // will not execute } statements2 }

  24. SECTION-A Completed

  25. An application is created from classes. • A class is similar to a struct in the C language in that it stores related data in fields, where the fields can be different types. So you could, for example, store a text string in one field, an integer in another field, and a floating point in a third field. The difference between a class and a struct is that a class also defines the methods to work on the data. • For example, a very simple class might store a string of text and define one method to set the string and another method to get the string and print it to the console. Methods that work on the data are called accessor methods. • Every application needs one class with a main method. This class is the entry point for the program, and is the class name passed to the java interpreter command to run the application. • The code in the main method executes first when the program starts, and is the control point from which the controller class accessor methods are called to work on the data. class ExampleProgram { public static void main(String[] args){ System.out.println("I'm a Simple Program"); } }

  26. The public static void keywords mean the Java virtual machine (JVM) interpreter can call the program's main method to start the program (public) without creating an instance of the class (static), and the program does not return data to the Java VM interpreter (void) when it ends. • An instance of a class is an executable copy of the class While the class describes the data and behavior, you need a class instance to acquire and work on data. The diagram shows three instances of the ExampleProgram class by the names: FirstInstance, SecondInstance and ThirdInstance. • The main method for the simple example does not create an instance of the ExampleProgram class because none is needed. The ExampleProgram class has no other methods or fields, so no class instance is needed to access them from the main method. The Java platform lets you execute a class without creating an instance of that class as long as its static methods do not call any non-static methods or fields. • The ExampleProgram class just calls System.out.println. The java.lang.System class, among other things, has a static out field of type PrintStream that is used to invoke the println methods in the PrintStream class.

  27. class LessonTwoB { String text = "I'm a Simple Program"; static String text2 = "I'm static text"; String getText(){ return text; } String getStaticText(){ return text2; } public static void main(String[] args){ LessonTwoB progInstance = new LessonTwoB(); String retrievedText = progInstance.getText(); String retrievedStaticText = progInstance.getStaticText(); System.out.println(retrievedText); System.out.println(retrievedStaticText); } } class LessonTwoC { static String text = "I'm a Simple Program"; //Accessor method static String getText(){ return text; } public static void main(String[] args){ String retrievedText = getText(); System.out.println(retrievedText); } } class methods can operate only on class fields, and instance methods can operate on class and instance fields

  28. Important Note: • Object variables holds refrence to objects not Objects • Declaring an object variable does not create a corresponding object • Comparing two object variables with == opeartor really compares the pointes held in the variables, not the objects pointed to. • An object is passed as a parameter by pushing a copy of the reference to it on the stack • It is easy to declare a class that has an instance of itself as a field e.g. Linklist, binary tree contains two binary trees • Class bTree{ class Node { bTree left; int info; bTree right; Node ptr; } } • A reference variable is DEreferenced automatically to get the contents of fields in the Object. But remember that assignments and comparisons are of pointes, not Objects

  29. Constructors Constructor is like a special kind of method that can be used only to create and initialize a new object. Constructor functions always have the same name as the class Access_Modifiers Classname(param) optional_throws{.....} No return type

  30. Constructor class LessonTwoD { String text; //Constructor LessonTwoD(){ text = "I'm a Simple Program"; } //Accessor method String getText(){ return text; } public static void main(String[] args){ LessonTwoD progInst = new LessonTwoD(); String retrievedText = progInst.getText(); System.out.println(retrievedText); } }

  31. Constructor and “this” class LessonTwoD { String text; //Constructor LessonTwoD(){ this("I'm a Simple Program“); } LessonTwoD(String s){ text =s; } //Accessor method String getText(){ return text; } public static void main(String[] args){ LessonTwoD progInst = new LessonTwoD(); String retrievedText = progInst.getText(); System.out.println(retrievedText); } }

  32. Garbage collection (GC) The automatic reclaiming of memory that is no longer in use is called GC in java. Java has a runtime storage manager and one sub system of storage manages is called GC. Java has a thread in the background whose task is to do GC It looks at the memory and when it finds objects that are no longer refrenced, it reclaims them by telling the heap that memory is available to reuse. Languages with dynamic data structures need more memory we do that like malloc() in C, “new” in Java To reuse/freeing free() in C, Java approach is GC Why GC? Memory Leak: • Its all too easy to create a memory leak by not freeing memory before overwriting last pointer to it. • It can then neither be referenced nor freed and that amount of memory is lost to further use for as long as the program runs

  33. Garbage collection (GC) GC Algorithms Reference Counting: Keeps a counter for each chunk of memory allocated. Adv: steady constant overhead Dis-Adv: 1) A -> B and B -> A, nothing else point to A and B, Then reference count of A and B >0 Hence A, B will not be free. 2) Ref. Count must be locked for Mutual exclusion in multi-threading

  34. Garbage collection (GC) Mark & Sweep The marker start from the root and mark (say red) every object that is reachable. Then sweep phase starts, everything not marked (not red) swept back to free space. Stop & copy: Stops all other threads completely The heap is split into two parts: the Current active part and the new part called “semi-space”. It copy all non-garbage stuff to new semi-space and at the end current active space is just discarded completely.

  35. Garbage collection (GC) Protected void finalize(){ //Action about to reclame memory }

  36. Method Overloading class Tree{ int height; Tree(){ prt(“Planting a Seedling”); height=0; } Tree(int i) { prt(“Creating new Tree of “ + i + “feet”); height=i; } void info(){ prt(“Tree of “ + i + “ feet”);} void info(String s){ prt(s+“: Tree of “ + i + “ feet”);} static void prt(String s){ System.out.println(s); } }// class Tree ends

  37. Method Overloading Public class Test{ public static void main(String[] args){ for (int i=0;i<5; i++){ Tree t=new Tree(i) t.info(); t.info(“Overloaded method”); } //overloaded constructor new Tree(); } }// class ends

  38. Method Overloading Order Public class Test{ static void print(String s, int i){ System.out.println(“String: “ + s + “, int:”+i) } static void print(int i, String s){ System.out.println(“int:”+ i + “String: “ + s ) } public static void main(String[] args){ print(“String first arg”, 10); print(11,”String Second arg”); } }// class ends Overloading with Return types void f() { …} int f() {….} Object f() {…..} Consider the call int x = f(); Calling a method for its Side effect i.e. don’t care return type f(); Which f()????

  39. This keyword Public class Banana{ void f(int i){ … } void f2(){ f(10); …} // not this.f(10) Banana getB() { return this;} }// class ends …. Banana a new Banana(), b=new Banana(); a.f(1); === Banana.f(a,1); b.f(2); = Banana.f(b,2);

  40. Java Initialization Java provide guaranteed initialization. Even though the values are not specified they automatically get initialized. Data type Initial value boolean false char null char byte 0 short 0 int 0 long 0 float 0.0 double 0.0 Object references are initialized to null pointer class TestInit{ int k; boolean flag=true; Myclass o= new Myclass(); int i= f(); int j=g(i); // int j=g(i); // int i=f(); }

  41. Order of Initialization OUTPUT=? class Tag{ Tag(int marker){ System.out.println(“Tag(“+marker+”)”); } } class Card { Tag t1=new Tag(10); Card() { System.out.println(“CARD()”); t3= new Tag(33); // re-initialize } Tag t2=new Tag(2); void f(){ System.out.println(“f()”); } Tag t3= new Tag(3); } public class InitTest{ public static void main(String[] arg){ Card c=new Card(); c.f(); } }

  42. Order of Initialization OUTPUT Tag(10) Tag(2) Tag(3) class Tag{ Tag(int marker){ System.out.println(“Tag(“+marker+”)”); } } class Card { Tag t1=new Tag(1); Card() { System.out.println(“CARD()”); t3= new Tag(33); // re-initialize } Tag t2=new Tag(2); void f(){ System.out.println(“f()”); } Tag t3= new Tag(3); } public class InitTest{ public static void main(String[] arg){ Card c=new Card(); c.f(); } }

  43. Order of Initialization OUTPUT Tag(10) Tag(2) Tag(3) CARD() Tag(33) f() class Tag{ Tag(int marker){ System.out.println(“Tag(“+marker+”)”); } } class Card { Tag t1=new Tag(1); Card() { System.out.println(“CARD()”); t3= new Tag(33); // re-initialize } Tag t2=new Tag(2); void f(){ System.out.println(“f()”); } Tag t3= new Tag(3); } public class InitTest{ public static void main(String[] arg){ Card c=new Card(); c.f(); } }

  44. Access Specifier public: everybody, everywhere, can access it. <no access modifier>: Make the member friendly by leaving off any access specifier. The other classes only in the same package can access it. package access protected: Inherited classes can access a protected member as well as public members. No private members. It can access friendly members only if the two are in the same package. private: Members are not accessible outside the class.

  45. Access Specifier Note: • Making a constructor private prevents the class being instantiated • Making a member private means it can only be called from within the class • Protected is Less protected as protected members are accessible in the package and in subclasses of the class. Protected in Java is automatically friendly • A class can be given a package or public access

  46. Final Modifier Final makes something constant final static int myMax= 99999; final Fruit banana= new Fruit(); If reference variable is declared final, it menas that you cannot make that variable point to some other object By using final reference variable you can change the object values. Reference is final, not the reference object void f(final Fruit o, final int a[]){ o.color=‘red’; a[0]=100; o=new Fruit(); a=new int[130]; } NOTE: final is a clue to the compiler that certain optimizations can be made. In case of final primitive data the compiler can substitute the value at each place The blank final variable initialized only once (jdk 1.1) final String consumer;

  47. Assignment-2 • What is AWT? • Introduction to AWT Classes • What are Jcomponents? • Write a Java Program for drawing: • text, • Lines and • Shapes

  48. Inheritance Vs Composition • Compositions generally used when you want the features of an existing class inside your new class but not the interface. • During composition you embed an object so that you can use it to implement the features of your new class, but the user of your new class sees the interface you have defined rather than the interface from the embed object. For this effect you embed PRIVATE objects of existing classes inside your new class. • The “has-a” relationship is expressed with composition • When you inherit, you take an existing class and make a special version of it. In general, this means you are taking a general-purpose class specialized it for a particular need. • The “is-a” relationship is expressed with inheritance. • Both inheritance and composition allow you to place sub-objects inside your new class. • It is very common to use composition with inheritance

  49. public class Car{ public Engine engine=new Engine(); public Wheel[ ] wheels= new Wheel[4]; public Door left= new Door(), right=new Door(); Car(){ for (int i=0; i<4;i++) wheels[i]=new Wheel(); } public static void main(String s[]){ Car car=new Car(); car.left.window.rollup(); car.wheels[0].air(32); } } With a little thought, you will see that it would make NO sense to composite a car using a vehicle object. A car does not contain a vehicle, it “is-a” vehicle. //Car.java class Engine{ public void start(){ } public void rev(){ } public void stop(){ } } class Wheel{ public void air (int psi){ } } class Window{ public void rollup (){ } public void rolldown (){ } } class Door{ public Window o=new Window(); public void open (){ } public void close (){ } }

  50. Constructors with arguments class Game { Game(int id) { System.out.println(“Game Constructor”); } } class BoardGame extends Game { BoardGame(int id){ super(id); System.out.println(“BoardGame”); } } public class Chess extends BoardGame{ chess(){ super(101); System.out.println(“Chess”); } public ststic void main(String s[]){ Chess obj= new Chess(); } } • If you do not call the base class contractor in BoardGame(), the Compiler will complain that it cannot find a constructor of the form Game() • The call to the base class constructor must be the first thing you do in the derived class constructor

More Related