Introduction to java
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
631
On Slideshare
631
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
53
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

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 programs 7decret.com 2
  • 3. Why Java?  It’s almost entirely object-oriented  It has a vast library of predefined objects and operations  It’s more platform independent  this makes it great for Web programming  It’s 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 foo 7decret.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.out class 7decret.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.com 7
  • 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.com 10
  • 11. Control statements II switch (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 which more 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.com 12
  • 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 (called records, 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 on those objects 7decret.com 15
  • 16. Name conventions Java is case-sensitive; maxval, maxVal, and MaxVal are three 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.com 16
  • 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.com 17
  • 18. An example of a class class Person { String name; int age; void birthday ( ) { age++; System.out.println (name + is now + age); } } 7decret.com 18
  • 19. Another example of a class class Driver extends Person { long driversLicenseNumber; Date expirationDate; } 7decret.com 19
  • 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.com 20
  • 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 Web page, and run by a browser A servlet is designed to be run by a web server 7decret.com 22
  • 23. Method 7decret.com 23
  • 24. Constructor 7decret.com 24
  • 25. Static keyword Instance methods are associated with an object and use the instance variables of that object. This is the default. A servlet is designed to be run by a web server Static methods use no instance variables of any object of the class they are defined in.(Security reason) Can only call from static method. 7decret.com 25
  • 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 Protected 7decret.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.com 28
  • 29. Private The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. they cannot be accesses by anywhere outside the enclosing class 7decret.com 29
  • 30. Protected The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. 7decret.com 30
  • 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 member’s 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 Java that allows you to extend a class (called the base class or superclass ) with another class (called the derived 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.com 39
  • 40. Abstract Class  An abstract class is a class that is declared abstract—it may or may not include abstract methods.  Abstract classes cannot be instantiated, but they can be subclassed. 7decret.com 40
  • 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 subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract. 7decret.com 42
  • 43. Abstract class or Interface ? ? 7decret.com 43
  • 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.com 45
  • 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 providing access protection and name space management. 7decret.com 47
  • 48. Creating a package  To create a package, you choose a name for the package and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package. 7decret.com 48
  • 49. Name Convention  Package names are written in all lowercase to avoid conflict with the names of classes or interfaces. 7decret.com 49
  • 50. Exception  Exception is a run-time error which arises during the execution of java program. The term exception in java stands for an exceptional event. 7decret.com 50
  • 51. 7decret.com 51
  • 52. Exception  Exception is a run-time error which arises during the execution of java program. The term exception in 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 to have multiple threads of execution running concurrently. 7decret.com 53
  • 54. Run() method  When a thread is created, it must be permanently bound to an object with a run() method. When the thread is started, it will invoke the objects run() method. More specifically, the object must implement the Runnable interface. 7decret.com 54
  • 55. Extending thread class  By creating thread class(extend thread class)  By concerting a class into thread(implementing a runnable interface) 7decret.com 55
  • 56. Extending the thread class  Extend a thread class  Implement the run() method  Create a thread object and call the start method. 7decret.com 56
  • 57. Lifecycle of Thread  Multithreading refers to two or more tasks executing concurrently within a single program.Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously. 7decret.com 57
  • 58. Lifecycle of Thread 7decret.com 58
  • 59. Stop/Block thread.  tThread.stop()  Sleep() …..(miliseconds)  Suspend() ……(resume())  Wait() ……………(wait()) 7decret.com 59
  • 60. Multithreading  Multithreading refers to two or more tasks executing concurrently within a single program.Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously. 7decret.com 60
  • 61. States  New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 7decret.com 61
  • 62. States  Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 7decret.com 62
  • 63. States  Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 7decret.com 63
  • 64. States  Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. 7decret.com 64
  • 65. States  Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread. 7decret.com 65
  • 66. Thread Exception  Sleep method must be in try catch block  IllegalThreadStateExceprtion(Whenever we invoke the method not in given state)  InterruptedException  IllegalArgumentException 7decret.com 66
  • 67. Thread Priority  Threadneme.setPriority()  MIN_PRIORITY  NORM_PRIORITY  MAX_PRIORITY 7decret.com 67
  • 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" package 7decret.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.com 70
  • 71. String length String Length int length( ) String ConcatenationString age = "9";String s = "He is " + age + " years old.";System.out.println(s); 7decret.com 71
  • 72. String methods String Conversion and toString( ) 7decret.com 72
  • 73. Character Extraction char ch; ch = "abc".charAt(1); assigns the value “b” to ch. void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) toCharArray( )  char[ ] toCharArray( ) 7decret.com 73
  • 74. String Comparison equals( ) and equalsIgnoreCase( ) boolean equals(Object str) startsWith( ) and endsWith( ) 7decret.com 74
  • 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 the other in dictionary order. int compareTo(String str) 7decret.com 76
  • 77. Searching Strings String class provides two methods indexOf( ) Searches for the first occurrence of a character or substring. lastIndexOf( ) Searches for the last occurrence of a character 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 methods 7decret.com 78
  • 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.com 79
  • 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.com 81
  • 82. Reading Console Input To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. 7decret.com 82
  • 83. Reading Strings To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general form is shown here: String readLine( ) throws IOException 7decret.com 83
  • 84. Writing Console Output write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here: void write(int byteval) 7decret.com 84
  • 85. PrintWriter PrintWriter is one of the character-based classes. Using a character-based class for console output makes it easier to internationalize your program PrintWriter(OutputStream outputStream, boolean flushOnNewline) 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) throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException To write to a file, you will use the write( ) method defined by FileOutputStream.  Its simplest form is shown here: void write(int byteval) throws IOException 7decret.com 87
  • 88. Native Methods you may want to call a subroutine that is written in a language other than Java. Typically, such a subroutine exists as executable code for the sCPU and environment in which you are working—that is, 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 Frame 7decret.com 89
  • 90. Component Component is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. A Component object is responsible for remembering the current foreground and background colors and the currently selected text font. 7decret.com 90
  • 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.com 92
  • 93. Panel The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements container. A Panel may be thought of as a recursively nestable,concrete screen component. a Panel is a window that does not contain a title bar, menu bar, or border. This is why you don’t see these items when an applet is run inside a browser 7decret.com 93
  • 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.com 94
  • 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 won’t create Window objects directly. Instead, you will use a subclass of Window called Frame 7decret.com 95
  • 96. Frame It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. 7decret.com 96
  • 97. Canvas Canvas encapsulates a blank window upon which you can draw. it is not part of the hierarchy for applet or frame windows 7decret.com 97
  • 98. Working with Frame Windows Frame( ) Frame(String title) 7decret.com 98
  • 99. Setting the Window’s Dimensions The setSize( ) method is used to set the dimensions of the 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 size of 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 be visible until you call setVisible( ). Its signature is shown here: void setVisible(boolean visibleFlag) 7decret.com 100
  • 101. Setting a Window’s Title You can change the title in a frame window using setTitle( ), 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 a window. By default, new output to a window overwrites any preexisting contents. However, it is possible to have new objects XORed onto the window by using setXORMode( ), as follows: void setXORMode(Color xorColor) 7decret.com 103
  • 104. Setting the Paint Mode…. To return to overwrite mode, call setPaintMode( ), shown here: void setPaintMode( ) In general, you will want to use overwrite mode for normal output, 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 object that describes that font.One Font constructor has this general form: Font(String fontName, int fontStyle, int pointSize) The size, in points, of the font is specified by pointSize. To use a font that you have created, you must select it using setFont( ), which is defined by Component. It has this general 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, CheckboxGroup cbGroup) Checkbox(String str, CheckboxGroup cbGroup, boolean on) 7decret.com 107
  • 108. CheckboxGroup Checkbox getSelectedCheckbox( ) void setSelectedCheckbox(Checkbox which) 7decret.com 108
  • 109. Choice Controls String getSelectedItem( ) int getSelectedIndex( ) 7decret.com 109
  • 110. Using a TextField TextField( ) TextField(int numChars) TextField(String str) TextField(String str, int numChars) 7decret.com 110
  • 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, int sBars) 7decret.com 111
  • 112. BorderLayout The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width components 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 by BorderLayout: 7decret.com 112
  • 113. GridLayout GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout, you define the number of rows and columns. The constructors supported by GridLayout are shown here: GridLayout( ) GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, int vert) 7decret.com 113
  • 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.com 114
  • 115. CardLayout You can prepare the other layouts and have them hidden,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, int sBars) 7decret.com 116