introduction to java

116
Introduction to Java By:- Ajay Sharma ajkush- ws.blogspot.com 7decret.com

Upload: ajay-sharma

Post on 26-May-2015

589 views

Category:

Education


0 download

DESCRIPTION

Introduction to java

TRANSCRIPT

  • 1. By:- Ajay Sharmaajkush-ws.blogspot.com7decret.com

2. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build stand-alone Java programs Java applets, which run within browsers e.g. Netscape Example programs7decret.com2 3. Why Java? Its almost entirely object-oriented It has a vast library of predefined objects and operations Its more platform independent this makes it great for Web programming Its more secure Open Source 7decret.com 3 4. Building Standalone JAVAPrograms Prepare the file foo.java using an editor Invoke the compiler: javac foo.java This creates foo.class Run the java interpreter: java foo7decret.com 4 5. Java Virtual Machine The .class files generated by the compiler are not executable binaries so Java combines compilation and interpretation Instead, they contain byte-codes to be executed by the Java Virtual Machine other languages have done this, e.g. UCSD Pascal This approach provides platform independence, and greater security 7decret.com 5 6. HelloWorld (standalone)public class HelloWorld {public static void main(String[] args) {System.out.println("Hello World!");}} Note that String is built in println is a member function for the System.outclass7decret.com 6 7. Comments are almost like C++ /* This kind of comment can span multiple lines */ // This kind is to the end of the line /*** This kind of comment is a special* javadoc style comment*/7decret.com7 8. Primitive data types are like C Main data types are int, double, boolean, char Also have byte, short, long, float boolean has values true and false Declarations look like C, for example, double x, y; int count = 0; 7decret.com 8 9. Expressions are like C Assignment statements mostly look like those in C;you can use =, +=, *= etc. Arithmetic uses the familiar + - * / % Java also has ++ and -- Java has boolean operators && || ! Java has comparisons < = > Java does not have pointers or pointer arithmetic 7decret.com 9 10. Control statements are like C if (x < y) smaller = x; if (x < y){ smaller=x;sum += x;}else { smaller = y; sum += y; } while (x < y) { y = y - x; } do { y = y - x; } while (x < y) for (int i = 0; i < max; i++) sum += i; BUT: conditions must be boolean ! 7decret.com10 11. Control statements IIswitch (n + 1) {case 0: m = n - 1; break;case 1: m = n + 1;case 3: m = m * n; break;default: m = -n; break;} Java also introduces the try statement, about whichmore later 7decret.com 11 12. Java isnt C! In C, almost everything is in functions In Java, almost everything is in classes There is often only one class per file There must be only one public class per file The file name must be the same as the name of that public class, but with a .java extension 7decret.com12 13. Java program layout A typical Java file looks like: Package asdf ; import java.awt.*; import java.util.*;public class SomethingOrOther {// object definitions go here...must be in a file named SomethingOrOther.java ! This }7decret.com 13 14. What is a class? Early languages had only arrays all elements had to be of the same type Then languages introduced structures (calledrecords, or structs) allowed different data types to be grouped 7decret.com 14 15. So, what is a class? A class consists of a collection of fields, or variables, very much like the named fields of a struct all the operations (called methods) that can be performed on those fields can be instantiated A class describes objects and operations defined onthose objects 7decret.com15 16. Name conventions Java is case-sensitive; maxval, maxVal, and MaxVal arethree different names Class names begin with a capital letter All other names begin with a lowercase letter Subsequent words are capitalized: theBigOne Underscores are not used in names These are very strong conventions!7decret.com16 17. The class hierarchy Classes are arranged in a hierarchy The root, or topmost, class is Object Every class but Object has at least one superclass A class may have subclasses Each class inherits all the fields and methods of its(possibly numerous) superclasses 7decret.com17 18. An example of a class class Person { String name; int age; void birthday ( ) { age++; System.out.println (name +is now+ age); } }7decret.com18 19. Another example of a class class Driver extends Person { long driversLicenseNumber; Date expirationDate; }7decret.com19 20. Creating and using an object Person john;john = new Person ( );john.name = "John Smith";john.age = 37; Person mary = new Person ( );mary.name = "Mary Brown";mary.age = 33;mary.birthday ( ); 7decret.com20 21. An array is an object Person mary = new Person ( ); int myArray[ ] = new int[5]; or: int myArray[ ] = {1, 4, 9, 16, 25}; String languages [ ] = {"Prolog", "Java"};7decret.com 21 22. Applets and Servlets An applet is designed to be embedded in a Webpage, and run by a browser A servlet is designed to be run by a web server 7decret.com22 23. Method 7decret.com 23 24. Constructor 7decret.com 24 25. Static keyword Instance methods are associated with an object anduse the instance variables of that object. This is thedefault. A servlet is designed to be run by a web server Static methods use no instance variables of anyobject of the class they are defined in.(Security reason) Can only call from static method. 7decret.com25 26. Final Keyword You can declare some or all of a classs methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. Methods called from constructors should generally be declared final. Note that you can also declare an entire class final this prevents the class from being subclassed.7decret.com 26 27. Access Modifier Public Private Default Protected7decret.com 27 28. Public Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. 7decret.com28 29. Private The private (most restrictive) fields or methods cannotbe used for classes and Interfaces. It also cannot be used for fields and methods within aninterface. they cannot be accesses by anywhere outside theenclosing class 7decret.com29 30. Protected The protected fields or methods cannot be used forclasses and Interfaces. It also cannot be used for fields and methods within aninterface. methods and constructors declared protected in asuperclass can be accessed only by subclasses in otherpackages. 7decret.com30 31. Protected Cont.. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected members class.7decret.com 31 32. Default Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.7decret.com 32 33. Inheritance Inheritance is a compile-time mechanism in Javathat allows you to extend a class (called the baseclass or superclass ) with another class (called thederived class or subclass). 7decret.com 33 34. Types of Inheritance Single Inheritance Multi Level Inheritance Hierarchicval Inheritance 7decret.com 34 35. 7decret.com 35 36. 7decret.com 36 37. 7decret.com 37 38. 7decret.com 38 39. Interfaces An interface is a group of related methods with empty bodies. Implement all method of interface otherwise class become abstract functions are public and abstract fields are public and final .7decret.com39 40. Abstract Class An abstract class is a class that is declared abstractit may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.7decret.com40 41. Abstract method An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon) If a class includes abstract methods, the class itself must be declared abstract.7decret.com 41 42. Abstract method cont.. When an abstract class is subclassed, the subclassusually provides implementations for all of theabstract methods in its parent class. However, if itdoes not, the subclass must also be declaredabstract. 7decret.com 42 43. Abstract class or Interface ? ? 7decret.com43 44. Dynamic Method Dispatch Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. 7decret.com 44 45. Nested classes Static nested classes Non-static inner classes.7decret.com45 46. Dynamic Method Dispatch Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. 7decret.com 46 47. Package A package is a grouping of related types providingaccess protection and name space management. 7decret.com47 48. Creating a package To create a package, you choose a name for thepackage and put a package statement with thatname at the top of every source file that containsthe types (classes, interfaces, enumerations, andannotation types) that you want to include in thepackage. 7decret.com 48 49. Name Convention Package names are written in all lowercase to avoidconflict with the names of classes or interfaces. 7decret.com 49 50. Exception Exception is a run-time error which arises duringthe execution of java program. The term exceptionin java stands for an exceptional event. 7decret.com 50 51. 7decret.com 51 52. Exception Exception is a run-time error which arises duringthe execution of java program. The term exceptionin java stands for an exceptional event. 7decret.com 52 53. Thread A thread is a thread of execution in a program. The Java Virtual Machine allows an application tohave multiple threads of execution runningconcurrently.7decret.com53 54. Run() method When a thread is created, it must be permanentlybound to an object with a run() method. When thethread is started, it will invoke the objects run()method. More specifically, the object must implementthe Runnable interface. 7decret.com54 55. Extending thread class By creating thread class(extend thread class) By concerting a class into thread(implementing arunnable interface) 7decret.com55 56. Extending the thread class Extend a thread class Implement the run() method Create a thread object and call the start method. 7decret.com56 57. Lifecycle of Thread Multithreading refers to two or more tasks executingconcurrently within a single program.Many threadscan run concurrently within a program. Every threadin Java is created and controlled by thejava.lang.Thread class. A Java program can havemany threads, and these threads can runconcurrently, either asynchronously or synchronously.7decret.com 57 58. Lifecycle of Thread7decret.com 58 59. Stop/Block thread. tThread.stop() Sleep() ..(miliseconds) Suspend() (resume()) Wait() (wait()) 7decret.com59 60. Multithreading Multithreading refers to two or more tasks executingconcurrently within a single program.Many threadscan run concurrently within a program. Every threadin Java is created and controlled by thejava.lang.Thread class. A Java program can havemany threads, and these threads can runconcurrently, either asynchronously or synchronously.7decret.com 60 61. States New state After the creations of Thread instancethe thread is in this state but before the start()method invocation. At this point, the thread isconsidered not alive. 7decret.com61 62. States Runnable (Ready-to-run) state A thread start itslife from Runnable state. A thread first entersrunnable state after the invoking of start() methodbut a thread can return to this state after eitherrunning, waiting, sleeping or coming back fromblocked state also. On this state a thread is waiting fora turn on the processor.7decret.com62 63. States Running state A thread is in running state thatmeans the thread is currently executing. There areseveral ways to enter in Runnable state but there isonly one way to enter in Running state: the schedulerselect a thread from runnable pool.7decret.com63 64. States Dead state A thread can be considered dead whenits run() method completes. If any thread comes onthis state that means it cannot ever run again. 7decret.com 64 65. States Blocked - A thread can enter in this state because ofwaiting the resources that are hold by another thread.7decret.com65 66. Thread Exception Sleep method must be in try catch block IllegalThreadStateExceprtion(Whenever we invoke the method not in given state) InterruptedException IllegalArgumentException 7decret.com66 67. Thread Priority Threadneme.setPriority() MIN_PRIORITY NORM_PRIORITY MAX_PRIORITY 7decret.com67 68. Inter-Thread Communication A process where, a thread is paused running in its critical region and another thread is allowed to enter (or lock) in the same critical section to be executed. This technique is known as Interthread communication which is implemented by some methods. These methods are defined in "java.lang" package7decret.com 68 69. Inter-Thread Cont.. wait() notify() notifyAll() 7decret.com 69 70. Thread Exception Sleep method must be in try catch block IllegalThreadStateExceprtion(Whenever we invoke the method not in given state) InterruptedException IllegalArgumentException 7decret.com70 71. String length String Lengthint length( ) String ConcatenationString age = "9";String s = "He is " + age + " years old.";System.out.println(s);7decret.com71 72. String methods String Conversion and toString( ) 7decret.com72 73. Character Extraction char ch;ch = "abc".charAt(1);assigns the value b to ch. void getChars(int sourceStart, int sourceEnd, chartarget[ ], int targetStart) toCharArray( ) char[ ] toCharArray( ) 7decret.com 73 74. String Comparison equals( ) and equalsIgnoreCase( ) boolean equals(Object str) startsWith( ) and endsWith( ) 7decret.com74 75. equals( ) Versus == The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.7decret.com 75 76. compareTo( ) A string is less than another if it comes before theother in dictionary order. int compareTo(String str)7decret.com76 77. Searching Strings String class provides two methods indexOf( ) Searches for the first occurrence of acharacter or substring. lastIndexOf( ) Searches for the last occurrence of acharacter or substring. 7decret.com 77 78. Modifying a String Because String objects are immutable:- either copy it into a StringBuffer use one of the following String methods7decret.com78 79. String methods String substring(int startIndex) String substring(int startIndex, int endIndex) String s1 = "one"; String String s="Hello".replace(l,w);s2=s1.concat("two");7decret.com79 80. String methods String s = " Hello World ".trim(); 7decret.com 80 81. Data Conversion Using valueOf( ) String valueOf(double num) String valueOf(long num) String valueOf(Object ob) String valueOf(char chars[ ]) String toLowerCase( ) String toUpperCase( )7decret.com81 82. Reading Console Input To obtain a character-based stream that is attached to theconsole, you wrap System.in in a BufferedReader object, tocreate a character stream. BuffereredReader supports abuffered input stream. Reader is an abstract class. One of its concrete subclasses isInputStreamReader, which converts bytes to characters. 7decret.com 82 83. Reading Strings To read a string from the keyboard, use the version ofreadLine( ) that is a member of theBufferedReader class. Its general form is shownhere: String readLine( ) throws IOException 7decret.com 83 84. Writing Console Output write( ) can be used to write to the console. Thesimplest form of write( ) defined by PrintStream isshown here: void write(int byteval) 7decret.com84 85. PrintWriter PrintWriter is one of the character-based classes.Using a character-based class for console outputmakes it easier to internationalize your program PrintWriter(OutputStream outputStream, booleanflushOnNewline) 7decret.com 85 86. Reading and Writing Files Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an object of one of these classes, specifying the name of the file as an argument to the constructor. While both classes support additional, overridden constructors, the following are the forms that we will be using cont..7decret.com 86 87. Reading and Writing Files FileInputStream(String fileName) throwsFileNotFoundException FileOutputStream(String fileName) throwsFileNotFoundException To write to a file, you will use the write( ) method defined byFileOutputStream. Its simplest form is shown here: void write(int byteval) throws IOException 7decret.com87 88. Native Methods you may want to call a subroutine that is written in alanguage other than Java. Typically, such a subroutineexists as executable code for the sCPU andenvironment in which you are workingthatis, native code. 7decret.com 88 89. Window Fundamentals The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame7decret.com89 90. Component Component is an abstract class that encapsulates all of theattributes of a visual component. All user interface elementsthat are displayed on the screen and that interact with theuser are subclasses of Component. A Component object is responsible for remembering thecurrent foreground and background colors and the currentlyselected text font.7decret.com90 91. 7decret.com 91 92. Container Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system. A container is responsible for laying out (that is, positioning) any components that it contains. It does this through the use of various layout managers, 7decret.com92 93. Panel The Panel class is a concrete subclass of Container. It doesntadd any new methods; it simply implements container. APanel may be thought of as a recursively nestable,concretescreen component. a Panel is a window that does not contain a title bar, menubar, or border. This is why you dont see these items when anapplet is run inside a browser 7decret.com93 94. Panel Components can be added to a Panel object by its add( ) method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by Component. 7decret.com94 95. Window The Window class creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally, you wont create Window objects directly. Instead, you will use a subclass of Window called Frame7decret.com95 96. Frame It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners.7decret.com96 97. Canvas Canvas encapsulates a blank window upon whichyou can draw. it is not part of the hierarchy for applet or framewindows7decret.com 97 98. Working with Frame Windows Frame( ) Frame(String title) 7decret.com 98 99. Setting the Windows Dimensions The setSize( ) method is used to set the dimensions ofthe window. Its signature is shown here: void setSize(int newWidth, int newHeight) void setSize(Dimension newSize) The getSize( ) method is used to obtain the current sizeof a window. Its signature is shown here: Dimension getSize( ) 7decret.com 99 100. Hiding and Showing a Window After a frame window has been created, it will not bevisible until you call setVisible( ). Its signature is shown here: void setVisible(boolean visibleFlag) 7decret.com100 101. Setting a Windows Title You can change the title in a frame window usingsetTitle( ), which has this general form: void setTitle(String newTitle) 7decret.com 101 102. Closing a Frame Window When using a frame window, your program must remove that window from the screen when it is closed, by calling setVisible(false). To intercept a window-close event, you must implement the windowClosing( ) method of the WindowListener interface.7decret.com 102 103. Setting the Paint Mode The paint mode determines how objects are drawn in awindow. By default, new output to a windowoverwrites any preexisting contents. However, it ispossible to have new objects XORed onto the windowby using setXORMode( ), as follows: void setXORMode(Color xorColor)7decret.com 103 104. Setting the Paint Mode. To return to overwrite mode, call setPaintMode( ), shownhere: void setPaintMode( ) In general, you will want to use overwrite mode for normaloutput, and XOR mode for special purposes.7decret.com 104 105. Creating and Selecting a Font To select a new font, you must first construct a Font objectthat describes that font.One Font constructor has thisgeneral form: Font(String fontName, int fontStyle, int pointSize) The size, in points, of the font is specified by pointSize. Touse a font that you have created, you must select it usingsetFont( ), which is defined by Component. It has thisgeneral form: void setFont(Font fontObj) 7decret.com 105 106. Using Buttons Button( ) Button(String str) void setLabel(String str) String getLabel( )7decret.com 106 107. Applying Check Boxes Checkbox( ) Checkbox(String str) Checkbox(String str, boolean on) Checkbox(String str, boolean on, CheckboxGroupcbGroup) Checkbox(String str, CheckboxGroupcbGroup, boolean on) 7decret.com 107 108. CheckboxGroup Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox which)7decret.com108 109. Choice Controls String getSelectedItem( ) int getSelectedIndex( ) 7decret.com109 110. Using a TextField TextField( ) TextField(int numChars) TextField(String str) TextField(String str, int numChars) 7decret.com110 111. Using a TextArea TextArea( ) TextArea(int numLines, int numChars) TextArea(String str) TextArea(String str, int numLines, int numChars) TextArea(String str, int numLines, int numChars, intsBars)7decret.com111 112. BorderLayout The BorderLayout class implements a common layoutstyle for top-level windows. It has four narrow, fixed-widthcomponents at the edges and one large area in the center. The four sides are referred to as north, south, east, and west.The middle area is called the center. Here are the constructors defined byBorderLayout:7decret.com 112 113. GridLayout GridLayout lays out components in a two-dimensionalgrid. When you instantiate a GridLayout, you define thenumber of rows and columns. The constructorssupported by GridLayout are shown here: GridLayout( ) GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, intvert)7decret.com113 114. CardLayout The CardLayout class is unique among the other layout managers in that it stores several different layouts. Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input.7decret.com114 115. CardLayout You can prepare the other layouts and have themhidden,ready to be activated when needed. CardLayout provides these two constructors: CardLayout( ) CardLayout(int horz, int vert)7decret.com 115 116. Using a TextArea TextArea( ) TextArea(int numLines, int numChars) TextArea(String str) TextArea(String str, int numLines, int numChars) TextArea(String str, int numLines, int numChars, intsBars)7decret.com116