UNIT I chapter 2 : Java Evolution 1. Java History 2. Java Features 3. How Java differs from C and C++ 4. Java and Internet 5. Java and World Wide Web 6. Web Browsers 1. Java History • Java is a general-purpose, OOP language developed by Sun Microsystems of USA in 1991. • Originally called Oak by James Gosling • Java was originally designed for the development of Software for Consumer electronic devices like TVs, VCRs… Goal : Make the language simple, portable and highly reliable. • Java team included the existing languages like C & C++. • But it had limitations in terms of both reliability and portability. • They modeled their new language Java on C & C++ • But removed number of features of C & C++ • And made Java a really simple, reliable, portable and powerful language. 2. Java Features • The inventors of Java wanted to design a language which could offer solutions to some of the problems encountered in modern programming •The Java not only reliable, portable and distributed but also simple, compact and interactive. (Table diagram) b) Platform-Independent and Portable •The most significant features of Java is its portability. •Java programs can be easily moved from one computer system to another, anywhere and anytime.
•Changes and upgrades in Oss, Processors and System resources will not force any changes in Java programs. •This is the reason java has become a popular language for programming on Internet which interconnects different kinds of systems worldwide. •We can download a Java applet from a remote computer onto our local system via internet and execute it locally. b) Platform-Independent and Portable • The most significant features of Java is its portability. • Java programs can be easily moved from one computer system to another, anywhere and anytime. • Changes and upgrades in Oss, Processors and System resources will not force any changes in Java programs. • This is the reason java has become a popular language for programming on Internet which interconnects different kinds of systems worldwide. • We can download a Java applet from a remote computer onto our local system via internet and execute it locally. • Java ensures portability in 2 ways • First, Java compiler generates bytecode instructions that can be implemented on any machine. • Secondly, the size of the primitive data types are machine-independent. Java ensures portability in 2 ways • First, Java compiler generates bytecode instructions that can be implemented on any machine. • Secondly, the size of the primitive data types are machine-independent. c) Object-Oriented • Java is a true OO language. • Almost everything in Java is an Object. • All program code and data reside within objects and classes. • Java comes with an extensive set of lasses, arranged in packages, that can use in our programs by inheritance.
• The Object model in Java is simple and easy to extend. d) Robust and Secure Robust • Java is a robust language. • It provides many safeguards to ensure reliable code. • It has strict compile time and run time checking for data types. • It is designed as a garbage-collected language relieving the programmers virtually all memory management problems. • Java also incorporates the concept of Exception handling which captures serious and eliminates any risk of crashing the system. Security • It becomes an important issue for a language that is used for programming on Internet. • Threat of Viruses and abuse of resources are everywhere. • Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet. • The absence of pointers in Java ensures that programs cannot gain access to memory locations without proper authorization. e) Distributed • Java is designed as a distributed language for creating applications on networks. • It has the ability to share both data & programs • Java applications can open & access remote a bjects on Internet as easily as they can do in a local system. • It enables multiple programmers at multiple remote locations to collaborate and work together on a single project. f) Simple, Small and Familiar Simple & Small • Java is a small and simple language. • Many features of C & C++ that are earlier redundant or sources of unreliable code are not part of java. • Ex: no pointers, processor header files, goto and many others.
• Also eliminates Operator Overloading and multiple inheritance. Familiar • To make the language look familiar to the existing programmers. • It was modeled on C & C++ languages. • It used many constructs of C & C++ • In fact, Java is a simplified version of C++. g) Multithreaded and Interactive • Multithreaded means handling multiple tasks simultaneously. • Java supports multithreaded programs • We need not wait for the application to finish one task before beginning another. • It improves the interactive performance of graphical applications. • The Java runtime comes with tools that support multiprocess synchronization and construct smoothly running interactive systems. h) High Performance • Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode. • Java speed is comparable to the native C/C++. • Java architecture is also designed to reduce overheads during runtime. • The incorporation of multithreading enhances the overall execution speed of Java programs. i) Dynamic and Extensible • Java is a dynamic language. • Java is capable of dynamically linking in new class libraries, methods, and objects. • Java can also determine the type of class through a query, making it possible to either dynamically link or abort the program, depending on the response. • Java programs support functions written in other languages such as C & C++. • These functions known as native methods. • This facility enables the programmers to use the efficient functions available in these languages. • Native methods are linked dynamically at runtime.
II) Additional Features of J2SE 5.0 a) Ease of Development • Java 2 Standard Edition (J2SE) 5.0 supports features, such as Generics, enhanced for Loop. Autoboxing or unboxing., Typesafe Enums, Varargs, Static import and Annotation. • It reduce the work of the programmer by shifting the responsibility ofcreating the reusable code to the compiler. • The resulting source code is free from bugs because the errors made by the compiler are less when compared to those made by programmers. • Thus, each of the linguistic features is designed to develop java programs in a easier way. b) Scalability and Performance • J2SE 5.0 assures a significant increase in scalability and perfoemance by improving the startup time and reducing the amount of memory used in Java 2 runtime environment. • For example, the introduction of the class, data sharing in the Hotspot Java Virtual Machine(JVM) improves the startup time by loading the core classes from the jar files into a shared archive. • Memory utilization is reduced by sharing data in the shared archive multiple JVM processes. c) Monitoring and Manageability • Java supports a number of APIs, such as JVM Monitoring and Management API, Sun Management Platform Extension, Logging, Monitoring and Management Interface and Java Management Extension (JMX) to monitor and mange java applications. d) Desktop client • J2SE 5.0 provides enhanced features to meet to meet the requirements and challenges of the java desktop users. • It provides an improved Swing look and feel called Ocean. • This feature is mainly used for developing graphics applications that require OpenGL hardware acceleration. • Miscellaneous Features J2SE 5.0 supports the following features: e) Core XML Support
• J2SE 5.0 adds a powerful XML feature to the Java platform. • Java contains some special packages for interface to instantiate Simple API for XML(SAX) and Document Object Model (DOM) parsers to parse an XML document, transform the content of an XML document, and validate an XML document against the schema. f) Supplementary Character Support • Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support. • The supplementary characters are encoded with UTF-16 values to generate a different character called surrogate code point. g) JDBC RowSet • To send data in a tabular format between the remote components of a distributed enterprise application. • Contains CacheRowSet & WebRowSet. • This object contains a number of rows of data, which are retrieved from the database. • The data stored in the CacheRowtSet can be directly accessed without connecting to the database or any other data source. • The rows of data that are retrieved from the database can be synchronized later. • The WebRowSet object can operate without being connected to the database or data source and it uses XML format to read and write the rowset. • III) Enhancement in Java SE 6 • Some of the Key enhancements in Java SE 6 are : • a) Scripting Language Support • Java SE 6 integrates various scripting languages such as Java Script and PHP Script into the Java platform. • It allows scripts to be embedded in Java programs and compiled and executed with the help of appropriate scripting engine. • b) XML Processing and Web services • It allows development of web services and clients that communicate using XML • c) JDBC 4.0 Support • For developing database-centric applications
• As a result, programmers can leverage the various features of JDBX 4.0 such as automatic loading of JDBC driver class, connection management features etc., • d) Annotation-based Programming • It allows programmers to define annotations(meta-tags) for various program elements so that the same can be used by the compiler or other tools to generate ready code whenever necessary. • e) Dynamic compilation • The Java compiler API allows dynamic compilation of Java source code form a running Java application. IV) Enhancement in Java SE 7 Some of the Key enhancements in Java SE 7 are : a) Language Enhancements • Java SE 7adds several language features aimed at helping the programmers implement difficult functionality with ease. • The new language features include strings in switch statement, multiple handling, diamond syntax etc. b) NIO 2.0 • The new file system API(NIO 2.0) in Java SE 7 makes it a lot easier to work with the systems. • It contains several enhancements to the standard file operations such as open, read, write etc. • In addition, it also allows the programmers to create custom file systems. c) Parallel Programming • Java SE 7 facilitates Parallel Programming through the use of Fork/join Framework. • While the conventional multithreaded programming allowed programmers to use a single processor for multitasking. d) Dynamic Language Support • The Java SE 7 supports dynamically typed languages in the JVM. • The invoked dynamic instruction is used to define customized linkage mechanisms for these languages. 3. How Java Differs from C and C++ • Although Java was modeled after C & C++languages
• It differs from C and C++ in many ways • Java does not incorporate a number of features available in C & C++. • For the benefit of C & C++ programmers, we point out here a few major differences between C/C++ & Java languages. Java and C Major Difference : • Java is an OOP and has mechanism to define classes and objects. • In an effort to build a simple and safe language, the java team did not include some of the C features in Java i) Java does not include the C unique statement keywords sizeof and typedef. ii) Java does not contain the data types strut and union. iii) Java does not define the type modifiers keyword auto, extern, register, signed and unsigned. iv) Java does not support an explicit pointer type. v) Java does not have a preprocessor and therefore we cannot use #define, #include and #ifdef statements. vi) Java requires that the functions with no arguments must be declared with empty parenthesis and not with the void keyword as done in C. vii) Java adds new operators such as instance of and >>>. viii) Java adds labeled break and continue statements. ix) Java adds many features required for OOP. Java and C++ Major Difference : • Java is an true OOP language while C++ is basically C with OO extension. i) Java does not support operator overloading. ii) Java does not have template classes as in C++. iii) Java does not support multiple inheritance of classes. But it is accomplished using new feature called “interface”.
iv) Java does not support global variables. Every variable and method is declared within a class and form part of that class. v) Java does not use pointers. vi) Java has replaced the destructor function with a finalize( ) function. vii) There are no header files in Java. Java also add some new features : • While C++ is a superset of C • Java is neither a superset nor a subset of C or C++. • Java may be considered as a first cousin of C++ and a second cousin of C. Diagram Overlapping of C, C++ and Java 4. Java and Internet • Java is strongly associated with the Internet because of the fact that the first application program written in Java was HotJava, a Web browser to run applets on Internet. • Internet users can use Java to create applet programs and run them locally using a “java-enabled browser” such as HotJava. • They can also use a Java-enabled browser to download an applet located on a computer anywhere in the internet and run it on his local computer. • In fact, java applets have made the Internet a true extension of the storage system of the local computer. • Internet users can also set up their web sites containing Java applets that could be used by other remote users of Internet. • The ability of Java applets to hitch a ride on the information superhighway has made Java a unique programming language for the Internet. • Java is popularly known an Internet language. Diagram 5. Java and WWW WWW
• WWW is an open-ended information retrieval system designed to be used in the internet’s distributed environment. • Contains web pages that provide both information and controls. • Unlike a menu-driven system where we are guided through a particular direction using a decision tree structure • The web system is open-ended and we can navigate to a new document in any direction. • It is made possible with the help of a language called HTML • Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide. Diagram • Java was meant to be used in distributed environment such as internet. • Since, both the Web and Java share the same philosophy, java could be easily incorporated into the web system. • Before java, the WWW limited to the display of still images and texts. • However, the incorporation of java into web pages has made it capable of supporting animation, graphics, games and a wide range of special effects. • With the support of java , the web has become more interactive and dynamic. • We can run a java program on someone else’s computer across the internet. Diagram Communication Steps • The user sends a request for an HTML document to the remote computer’s web server. The web server is a program that accepts a request, and sends the required document. • The HTML document is returned to the user’s browser. The document contains the APPLET tag, which identifies the applet. • The corresponding Applet bytecode is transferred to the user’s computer. This bytecode had been previously created by the java compiler using the java source code file for that applet. • The java-enabled browser on the user’s computer interprets the bytecodes and provides output.
• The user may have further interaction with the applet but with no further downloading from the provider’s web server. This is because the bytecode contains all the information necessary to interpret the applet. 6. Web Browsers • The internet is a vast sea of information in many formats and stored on many computers. • A large portion of the internet is organized as the WWW which uses hypertext. • Web Browsers are used to navigate through the information found on the net. • They allow us to retrieve the information spread across the internet and display using the HTML. • Examples i) HotJava ii) Netscape Navigator iii) Internet Explorer i) HotJava • is the web browser from Sun Microsystems that enables the display of interactive content on the Web using the Java Language. • Written entirely in Java and demonstrates the capabilities of the java programming language. • When the java language was first developed and ported to the Internet, no browsers were available that could run java applets. • Although we can view a web page that includes java applets with a regular browser, we will not gain any of java’s benefits. ii) Netscape Navigator • From netscape communication corporation, is a general-purpose browser that can run java applets. • With version available for Windows, Solaris and Apple Macintosh, Netscape Navigator was one of the most widely used browsers of its time. • But with increasing popularity of IE browser, the use of NN decreased over a period of time.
• Even Netscape communication has stopped further development of this browser after its latest stable release 9.0 in March 2008 iii) Internet Explorer • It is another popular browser developed by Microsoft for Windows 95, NT and XP workstations. • Both the NN & IE use tool bars, menus and dialog boxes for easy navigation. • IE uses a just-in-time(JIT) compiler which greatly increases the speed of execution. 7. H/W & S/W Requirements : • Platform – Solaris, windows intel architecture 32-bit, Linux 32-bit etc., • Memory - 64/128 MB • Browsers – Mozila, IE • Disk Space – 98/110/58/56 MB 8. Java Support Systems : • Internet connection • Web Server • Web Browser • HTML • APPLET Tag • Java Code • Byte code • Proxy server • Mail Server 9. Java Environment : i) JDK (Java Development Kit)
comes with a collection of tools that are used for developing and running java programs. • Appletviewer – for viewing java applets • Javac – java compiler • Java – java interpreter • Javap – jave disassembler • Javah – for C header files • Javadoc – for creating HTML documents • Jdb – java debugger ii) API (Application Programming Interface) includes 100s of classes and methods grouped into several functional packages. • Language support Package – implementing basic features of Java • Utilities Package – provide utility functions such as date and time functions • I/O Package – for I/O manipulation • Networking Package – for communicating with other computers via the internet • AWT Package – implements platform-independent GUI • Applet Package – allows us to create java applets iii) JRE (Java Runtime Environment) facilitates the execution of programs developed in Java • JVM – it is a program that interprets the intermediate Java byte code and generates the desired o/p. • Runtime class libraries – a set of core class libraries that are required for the execution of java programs. • User interface toolkit – support varied i/p methods for the users to interact with the application program. • Deployment technologies – comprises a) Java plug-in – enbles the execution of a java applet on the browser b) Java web start – enables remote-deployment of an application. OVERVIEW OF JAVA LANGUAGE
To create a simple java program, you need to create a class that contains main method. Let's understand the requirement first. REQUIREMENT FOR HELLO JAVA EXAMPLE: For executing any java program, you need to • install the JDK if you don't have installed it, download the JDK and install it. • set path of the jdk/bin directory. • create the java program • compile and run the java program CREATING HELLO JAVA EXAMPLE : class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } save this file as Simple.java To compile : javac Simple.java To execute :java Simple JAVA PROGRAM STRUCTURE • Let’s use example of HelloWorld Java program to understand structure and features of class. • This program is written on few lines, and its only task is to print “Hello World from Java” on the screen. Refer the following picture. 1.“PACKAGES”:
2. “PUBLIC CLASS HELLOWORLD”: 3. COMMENTS SECTION: 4. “PUBLIC STATIC VOID MAIN (STRING [ ] ARGS)”: 5. SYSTEM.OUT.PRINTLN("HELLO WORLD FROM JAVA") JAVA TOKENS • A Java program is basically a collection of classes. • A class is defined by a set of declaration statements and methods containing executable statements. • Most statements contain expressions, which describe the actions carried out on data. • Smallest individual unit in a program are known as tokens. • The compiler recognizes them for building up expressions and statements. 5 Types of Tokens i. Reserved keywords ii. Identifiers iii. Literals iv. Operators v. Separators Diagram JAVA CHARACTER SET • The smallest units of Java language are the characters used to write Java tokens. • These characters are defined by the Unicode character set. • Emerging standard that tries to create characters for a large number of scripts worldwide. • The Unicode is a 16-bit character coding system and currently supports more than 34,000 defined characters. • That is derived from 24 languages
KEYWORDS IN JAVA • Java Keywords also called a reserved word. Keywords are identifiers that Java reserves for its own use. • Since keywords have specific meanings • These identifiers have built-in meanings that cannot change. • There are 50 reserved keywords currently defined in the Java language and they are shown in the below table. • Eg. Boolean, interface, abstract • We cannot use them as names for variables, classes, methods etc.,. JAVA STATEMENT: • Statements are roughly equivalent to sentences in natural languages. • A statement is an executable combination of token ending with a semicolon(;) mark. • A statement forms a complete unit of execution. • The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). • Statements are usually executed in sequence in the order in which they appear. • So it control flow of execution • If necessary , using special statements. • Assignment expressions • Any use of ++ or -- • Method invocations • Object creation expressions • Such statements are called expression statements. • Here are some examples of expression statements. // assignment statement aValue = 8933.234;
// increment statement aValue++; // method invocation statement System.out.println("Hello World!"); // object creation statement Bicycle myBike = new Bicycle(); Diagram Summary of Java Statements : Statement Description Remarks Empty Statement These do nothing and are used during program development as a place holder Same as C & C++ Labelled Statement Any Statement may begin with a lebel. Such label not be keywords Identical to C & C++ except jump Expression Statement Most Statements are expression Statements. 7 Types : Assignment, Pre-increment, Pre-Decrement, post-increment. Post- Decrement, Method call and Allocation Expression Same as C++ Selection Statement Select one of several control flows: if, if-else. Same as C & C++ Iteration Statement How and when looping will take place Identical to C & C++ except jump& label
2 Diagrams WHAT JVM DOES? The JVM performs following operation: Loads code Verifies code Executes code Provides runtime environment JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc. VARIABLES IN JAVA 1. Introduction 2. Declaration of Variables 3. Giving Values to Variables 4. Scope of Variables Jump Statement Pass control to the beginning or end of the current block C & C++ do not use labels with jump Synchronization Statement These are used fro handling issues with multithreading Now available in C & C++ Guarding Statement For safe handling of code that may cause exceptions. Try, catch, finally… Same as in C++ except finally statement
5. Getting Values of variables 6. Standard Default Values 7. Type casting 1. INTRODUCTION : • A variable is an identifier that denotes a storage location used to store a data value. • Constants – that remain unchanged during the execution of a program • Variable – may take different values of different times during the execution of the program • variable is chosen by the programmer in a meaningful way. • Consists of alphabets, digits, underscore and dollar characters Conditions : • They must not begin with a digit • Uppercase & Lowercase are distinct. • Not be a keyword • White space is not allowed • Any length 2. Declaration of Variables : • Variables hold one value at a time, but that value can change • After defining suitable names, declare them to the compiler. 3 things i. It tells the compiler what the variable name is ii. Specifies type of the data variable iii. Scope of the variable Syntax:
dataType identifier; or dataType var1, var2, … varn; • Variables are separated by commas Ex: int x; float y; 3. Giving Values to Variables : A variable must be given a value after it has been declared but before used Achieved in 2 Ways : i) By using an Assignment statement ii) By using a read statement By using an Assignment statement - A simple method of giving value to a variable Syntax: variableName = value; Ex : x = 5; - Also possible to assign a value to a variable at the time of declaration Syntax: type variableName = value; Ex : int x = 5; By using a read statement - through the keyboard using the readLine( ) method Ex : System.out.printline(“Enter vale”); x = Integer.parseInt(in.readLine( )); readLine( ) – reads the i/p from the keyboard as a string which is then converted to the corresponding data type using the data type wrapper classes.
i) By using a read statement Reading I/p from Keyboard a) Use System.Console class – to read lines Ex : System.out.printline(“Enter value”); int x = System.Console().readLine( ); System.out.printline(“The valu is :” + x); b) Use java.util.Scanner class and System.in Ex : Scanner sc=new Scanner(System.in); String s = sc.nextLine(); -> read the line System.out.println(“ the string is” + s); By using a read statement Reading I/p from Keyboard c) Use BufferedReader class – to read lines Ex : InputStreamReader isr = new InputStreamReader(System.in) BufferedReader br = new BufferedReader(isr); 4. Scope of Variables : 3 Kinds : a) instance variables b) class variables c) local variables Instance and class variables are declared inside a class a) instance variables - created when the objects are instantiated and they are associated with the objects.
- take different values for each objects. b) class variables - global to a class & belong to the entire set of objects that class creats - only one memory location is created. c) local variables - variables declared and used inside methods are called local variables -not available for outside the method definition -declared inside a program blocks - defined b/w { } . 5. Getting Values of Variables : Java supports 2 o/p methods - i) print( ) method - ii) println( ) method i) print( ) method - sends information into a buffer -This buffer is not flused until a newline character in sent - prints o/p on one line until a newline is encountered Ex : System.out.print(“Hi”); ii) println( ) method - stake the information provided and displays it on a line followed by a line feed Ex : System.out.println(“Hi”); 6. Standard Default Variables : - Every variable has a default value.
7. TYPE CASTING : - To store a value of one type into a variable of another type Syntax: type var1 = (type) var2; Ex : int m = 10; byte n = (byte) m; Automatic Conversion - assign a value of one type to a variable of a different type without a cast. Type of variable Default value byte Zero:0 short Zero:0 int Zero:0 long Zero:0L float 0.0f double 0.0d char null character boolean false reference null
- the conversion of the assigned value automatically known as automatic-type conversion Ex : byte b =10; int a =b; From To byte Short, char, int, long, float, double short Int, long, float, double char Int, long, float, double int long, float, double long float, double float double VARIABLE ARGUMENT (VARARGS): The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach. ADVANTAGE OF VARARGS: WE DON'T HAVE TO PROVIDE OVERLOADED METHODS SO LESS CODE. SYNTAX OF VARARGS: The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows: 1. return_type method_name(data_type... variableName){} SIMPLE EXAMPLE OF VARARGS IN JAVA: 1. 2. class VarargsExample1{ 3. 4. static void display(String... values){ 5. System.out.println("display method invoked "); 6. } 7. 8. public static void main(String args[]){ 9.
10. display();//zero argument 11. display("my","name","is","varargs");//four arguments 12. } 13. } 14. Test it Now Output:display method invoked display method invoked ANOTHER PROGRAM OF VARARGS IN JAVA: 1. 2. class VarargsExample2{ 3. 4. static void display(String... values){ 5. System.out.println("display method invoked "); 6. for(String s:values){ 7. System.out.println(s); 8. } 9. } 10. 11. public static void main(String args[]){ 12. 13. display();//zero argument 14. display("hello");//one argument 15. display("my","name","is","varargs");//four arguments 16. } 17. } 18. Test it Now Output:display method invoked display method invoked hello display method invoked my name is varargs download this example
Rules for varargs: While using the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows: o There can be only one variable argument in the method. o Variable argument (varargs) must be the last argument. EXAMPLES OF VARARGS THAT FAILS TO COMPILE: 1. 2. void method(String... a, int... b){}//Compile time error 3. 4. void method(int... a, String b){}//Compile time error 5. EXAMPLE OF VARARGS THAT IS THE LAST ARGUMENT IN THE METHOD: 1. 2. class VarargsExample3{ 3. 4. static void display(int num, String... values){ 5. System.out.println("number is "+num); 6. for(String s:values){ 7. System.out.println(s); 8. } 9. } 10. 11. public static void main(String args[]){ 12. 13. display(500,"hello");//one argument 14. display(1000,"my","name","is","varargs");//four arguments 15. } 16. } 17. Test it Now Output:number is 500 hello number is 1000
my name is varargs Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body } In order to define vararg, ... (three dots) is used in the formal parameter of a method. A method that takes variable number of arguments is called a variable-arity method, or simply a varargs method. First, let’s look at the example without using varargs: class NoVararg { public int sumNumber(int a, int b){ return a+b; } public int sumNumber(int a, int b, int c){ return a+b+c; } public static void main( String[] args ) { NoVararg obj = new NoVararg(); System.out.println(obj.sumNumber(1, 2)); System.out.println(obj.sumNumber(1, 2, 3)); }
} When you run this program, the output will be: 3 6 As you can clearly see, you had to overload sumNumber() method to make it work for 3 arguments. THINGS TO REMEMBER WHILE USING VARARGS Here are a couple of things you should remember while working with Java vargars: 1. While defining method signature, always keep varargs at last. The variable argument must be the last argument passed to the method. Let's consider, you invoked doSomething() method like this: doSomething(1, 2, 3, 4); And, your doSomething() method is defined as: // incorrect method declaration public void doSomething(int ... nums, int p){ // method body } In this case, compiler cannot figure out the number of arguments passed to nums. However, if you define your method as: public void doSomething(int p, int ... nums) { // method body } The Java compiler assigns the first argument to p, and the remaining int arguments are assigned to nums. 2. A method can have only one varargs parameter. For example, this method declaration is incorrect:
int doSomething(int p, float ... floatNums, double ... doubleNums) { // code } AMBIGUITY IN VARARGS METHOD OVERLOADING Let’s consider you overloaded test() method like this: class Demo { static void test(int ... vargs) { // method body } static void test(int n, int ... vargs) { // method body } } In the above program, the compiler gets confused if you try to invoke the test() method even though test() methods are overloaded and accepts different number of arguments. OPERATORS IN JAVA : 2 )
1 ) 3 ) 4 )
5 ) 6 ) 7) 8 )
9 ) 10 ) 11 ) 12 )
13 ) 14 ) 15 ) 16 )
17 ) 18 )
19 ) EXPRESSIONS IN JAVA : Definition : • An expression in java is a combination of operators , variables ,constants & method invocations. • Expression is used to perform the computation indicated by the elements of the expression and return some value. Example : int a=5; // returns 5 if(a==b) // returns Boolean value c = a + b; // returns a manipulated values System.in.read(); // evaluate a single value TYPES OF EXPRESSIONS : There are three types of expressions in java. They are, 1. Expression that produce a value 2. Expression that assign a variable 3. Expressions with no result EXPRESSIONS THAT PRODUCE A VALUE :
• It uses operators to produce a value such a Arithmetic operators ,Conditional operator, Comparison operator , etc… • Example: C=3+2 A=10/5 B= 2*4/5 EXPRESSIONS THAT ASSIGN A VARIABLE : • It is a expression that assigns a value to the variable. • Example: Int A=0; // assigns integer value B= true; // assigns boolean value EXPRESSIONS WITH NO RESULT : • Some expressions does not produce result but give a side effect which occurs when an expression changes the Value of an operands. • Example: P = a*b; Here value of variable ‘p’ is changed when calculated , but value of variable ‘a’ and ‘b’ does not change. This is called side effect. • a++ • Here ,value of variable ‘a’ is changed according to the program. Unit – II Classes, Objects and Methods 1. Introduction 2. 2. Defining a Class 3. Methods Declaration
4. Creating Objects 5. Accessing Class Members 6. Constructors 7. Method Overloading 8. Static Members 9. Nesting of Methods 10. Inheritance : Extending a Class 11. Overriding Methods 12. Final Variables and Methods 13. Final Classes 14. Finalizer Methods 15. Abstract Methods and Classes 16. Methods with Varargs 17. Visibility Control INTRODUCTION : • Java is a true OOPL • The underlying structure of all Java programs is classes. • Anything represented in a class • Class defines the state and behavior of the basic program components known as objects • Classes create objects and objects use methods to communicate between them • Classes provide a convenient method for packing together a group of logically related data items and functions • In Java The data items are called fields and the functions are called methods. DEFINING A CLASS : • A class is a user-defined data type with a template that serves to define its properties
• These variables are called instance variables because they are created whenever an object of the class is instantiated. Ex : class A { int length; Int width; } 3. FIELDS DECLARATION : • Data is encapsulated in a class by placing data fields inside the body of the class definition • Once the class type has been defined, we can create variables of that type using declarations that are similar to the basic-type declarations. • These termed as instances of classes, which are the actual objects. Syntax class classname [extends superclasname] { [ fields declaration; ] [methods declaration;] } Ex : class A { } 4. METHODS DECLARATION : • A class with only data fields & without methods that operate on that data has no life. • The objects created by such a class cannot respond to any messages. Syntax type methodname (parameter-list) { Method-body;
} 4 basic parts : i) The name of the method – method name ii) The type of the value the method returns – type iii) A list of parameters(parameter-list) iv) The body of the method Ex : Class Rect { Int len, wid; Void getdata(int x, int y) { len=x; Wid=y; } } 5. CREATING OBJECTS : • An object in java is essentially a block of memory that contains space to store all the instance variables. • object in java are created using the new operator • The new operator creates an object of the specified class and returns a reference to that object. Ex: Rect r1; R1=new Rect( ); (or) Rect r1 = new Rect( ); Diagram Diagram 6. ACCESSING CLASS MEMBERS :
• All variables must be assigned values before they are used. • Outside of the class cannot access the instance variables and methods directly. • so, we must use the concerned object and the dot operator Syntax : objectname.variablename = value; objectname.methodname(parameter-list); Variablename -> name of the instance variable inside the object we wish to access Methodname -> the method we wish to call Parameter list-> actual values that must match in type and number Ex: Rect r1 = new Rect( ); Rect r2=r1; r1.getdata(25, 30) r1.length = 10; r2.length = 12; Ex: void getdata(int x, int y) { length = x; width = y; } ….main( ) { Rect r1 = new Rect( ); r1.getdata(25, 30) } 7. CONSTRUCTORS : 2 approaches ( objects created) : i) Uses the dot operator to access the instance vars & assign values to them immediately. - difficult to initialize all the vars to all the objs ii) Takes the help of a method like r1.getdata(15,20); - simple one iii) But java supports special type of method called a constructor. - It enables an object to initialize itself when it is created. Constructor :
• Have the same name as the class itself • Do not specify a return type not even void • Because it return the instance of the class itself. Ex : class Rect { int length; int width; Rect(int x, int y) { length = x; width = y; } int rectArea() { return(length * width); }} 8. METHOD OVERLOADING : Definition – Method Overloading In java, possible to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading. • It is used when objects are required to perform similar task but using different input parameters • When we call a method, it follows - first matches the method name - then the number of parameters - type of parameters • This process is known as polymorphism. • Ex : – Method Overloading class Rect { int length; int width; Rect(int x, int y) // Constructor 1 { length = x; width = y }
Rect(int x) // Constructor 2 { length = width=x; } int rectArea() { return(length * width); }} 9. STATIC MEMBERS : Class contains 2 sections i) declares variables ii) declares methods - these variables & methods are called instance variables & instance methods. - because every time the class is instantiated, a new copy of each of them is created. - they are accessed using the objects with dot operator. • Assume, we want to define a member that is common to all the objects and accessed without using a particular object. • ie., the member belongs to the class as whole rather than the objects created from the class. Ex: static int c; static int area(int x, int y); - the members are declared as static are called static members. - these members associated with the class itself rather than individual objects. - the static vars & methods referred to as class vars & methods. - Static vars are used when we want to have a var common to all instances of a class. Ex : class Operation { static float mul(float x, float y) { return x*y; } static float div(float x, float y) { return x/y; }} Class MathOp
{ public void static main(String args[]) { float a = Operation.mul(5.0,2.0); float b = Operation.div(6.0,2.0); System.out.ptintln(“a=“+a); System.out.ptintln(“b=“+b) }} 10. NESTING OF METHODS : Def : A method can be called by using only its name by another method of the same class is known as nesting of methods. class Nest { int large() { …. } class display( ) { int l = large( ); } Class Ntest { public void static main(String args[]) { ….. } INHERITANCE IN JAVA : 1. Inheritance 2. Types of Inheritance 3. Why multiple inheritance is not possible in Java in case of class? Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability. Terms used in Inheritance o Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass. Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Test it Now Programmer salary is:40000.0 Bonus of programmer is:10000 In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
Note: Multiple inheritance is not supported in Java through class. When one class inherits multiple classes, it is known as multiple inheritance. For Example: Single Inheritance Example When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. TestInheritance.java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat();
}} Output: barking... eating... Multilevel Inheritance Example When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }} Output: weeping... barking... eating... Hierarchical Inheritance Example When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. TestInheritance3.java
class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class Cat extends Animal{ void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//C.T.Error }} Output: meowing... eating... Q) Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{//suppose if it were
public static void main(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } } Test it Now Compile Time Error Method Overriding Method Overloading and Method Overriding are the topics that should be on your to-do list before appearing for the interview. In this post, I will share what is method overriding, the rules of method overriding, and examples. So let's dive in and understand method overriding in java. What is Method Overriding When the child class(subclass) has the method which has the same name, same parameters and same return type (or covariant return type) as a method in its parent class(or super-class), then the child method has overridden the parent class method. Runtime polymorphism can be achieved through method overriding. Remember that at runtime, Object type (not reference variable's type) determines which overridden method is used. If the parent class object is used to invoke the method, then the parent class method will be executed. Otherwise, if, a child class object is used to invoke the method, then the child class method will be executed. Example of Method Overriding
// Method Overriding Example //Base class class Parent { public void display() { System.out.println("parent method is executed"); }} //Derived or Inherited class class Child extends Parent { //Below method overrides the Parent display() method @Override public void display() { System.out.println("child method is executed"); }} //Driver class public class MethodOverriding1 { public static void main(String args[]) { // If a Parent type reference refers // to a Parent object, then Parent's // display() is called Parent parentObject = new Parent(); parentObject.display(); // If a Parent type reference refers // to a Child object Child's display() // is called. This is called RUN TIME // POLYMORPHISM. Parent childObject = new Child(); childObject.display(); }} Output: parent method is executed child method is executed RULES FOR METHOD OVERRIDING IN JAVA 1. ACCESS MODIFIERS AND OVERRIDING
The access level can't be more restrictive than the overridden method. The access level can be less restrictive than that of the overridden method. For example, a protected instance method in the parent class(superclass) can be made public but not private in the child class(subclass). If you try to make a child class private then it will give the compile- time error.
// Access Modifiers and Overriding Example //Base class class Parent { //Access modifier of parent's display() method is protected protected void display() { System.out.println("parent method is executed"); } } //Derived class class Child extends Parent { //Below method overrides the Parent display() method //Access modifier public is less restrictive than protected @Override public void display() { System.out.println("child method is executed"); } } //Driver class public class MethodOverriding2 { public static void main(String args[]) { Parent parentObject = new Parent(); parentObject.display(); Parent childObject = new Child(); childObject.display(); }} Output : parent method is executed child method is executed 2. Private methods can not be overridden Another rule regarding access modifiers is you can not override private methods in the parent class. If subclass tries to override the private method of a parent class then the program will throw a compile-time error as shown below. // Access Modifiers and Overriding Example //Base class or Superclass
class Parent { //Access modifier of parent method is private // This method can not override the child class method private void display() { System.out.println("parent method is executed"); } } //Derived class or Subclass class Child extends Parent { //Below method can not overrides the Parent display() method //This method is unique to the child class private void display() { System.out.println("child method is executed"); } } //Driver class public class MethodOverriding3 { public static void main(String args[]) { Parent parentObject = new Parent(); parentObject.display(); // this line when execute will throw compiler error Parent childObject = new Child(); childObject.display(); // this line when execute will throw compiler error } } 3. FINAL METHODS CAN NOT BE OVERRIDDEN IN JAVA You can not override a method marked final. It will throw a compile-time error if you try to do so. // Simple Java program showing // final methods cannot be overridden //Parent class or Superclass class Parent {
// Can't be overridden final void display() { } } //Child class or Subclass class Child extends Parent { // This would produce compile time error void display() { } } Output : /Main.java:13: error: display() in Child cannot override display() in Parent void display() { } ^ overridden method is final 1 error 4. STATIC METHODS CAN NOT BE OVERRIDDEN You can not override a method mark static. If you define a static method in the subclass (child class) with the same method signature as the superclass(parent class) then it is called method hiding. // Method hiding example //Base class or SuperClass class Parent { static void display() { System.out.println("parent static method is executed"); } void show() { System.out.println("parent non-static (instance) method is executed"); } }
//Derived class or SubClass class Child extends Parent { //This method hides the Parent display() method static void display() { System.out.println("child static method is executed"); } // This method overrides the Parent show() method void show() { System.out.println("child non-static (instance) method is executed"); } } //Driver Class public class MethodOverriding4 { public static void main(String args[]) { Parent childObject = new Child(); // static method can not be overridden, // so below line calls parent display() method childObject.display(); // Expected child method will run childObject.show(); } } Output: parent static method is executed child non-static (instance) method is executed 5. Invoking a superclass (Parent class) version of overridden method It's easy to call the superclass(Parent class) version of overridden method by using the super keyword. // Invoking SuperClass version of Overridden Method Example //Base class or SuperClass class Parent { void display() {
System.out.println("parent method is executed"); } } //Derived class or SubClass class Child extends Parent { //This method overrides the Parent display() method @Override void display() { super.display(); System.out.println("child method is executed"); } } public class MethodOverriding5 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(); } } Output : parent method is executed child method is executed 6. Overriding method must have the same return type (or Covariant return type) The method return type must be the same, or a subtype of, the return type declared in the original overridden method in the superclass. Since java 5.0 it is made possible to have a different return type for an overriding method in a child class. But child's return type should be a subtype of the parent's return type. This phenomenon is called covariant return type. Example of Covariant Return Type class Alpha { Alpha doStuff(char c) { return new Alpha();
} } class Beta extends Alpha { Beta doStuff(char c) { // legal override in Java 1.5 return new Beta(); } } public class MethodOverriding6 { public static void main(String args[]) { Alpha childObject = new Beta(); childObject.doStuff('a'); } } The above code will compile and run. 7. CONSTRUCTOR AND OVERRIDING You can not override the constructor as the constructor name of the base class and child class can never be the same. (Constructor name is always the same as the class name). 8. Exception Handling and Overriding Rule 1. The overriding method can throw any unchecked(runtime) exception regardless of whether the overridden method declares the exception. // Overriding when superclass does not throw an exception //Base class or SuperClass class Parent { //overridden method void display() { System.out.println("parent method is executed"); } } //Derived class or SubClass
class Child extends Parent { //This method overrides the Parent display() method //It throws unchecked exception i.e Arithmetic Exception @Override void display() throws ArithmeticException{ System.out.println("child method is executed"); } } public class MethodOverriding7 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(); } } Output: child method is executed Rule 2. The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException can not be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException. Note : The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares. 9. Abstract method and Overriding Abstract methods can only be overridden by the first concrete class (classes that have no abstract methods) otherwise a compiler error will be thrown. //Abstract class abstract class Parent { public abstract void display( int x, String j);
} //Subclass or Derived Class class Child extends Parent { @Override public void display( int x, String j ) { System.out.println("child method is executed"); } } //Driver class public class MethodOverriding8 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(1, "Alive is Awesome"); } } Output : child method is executed 10. SYNCHRONIZED/STRICTFP METHOD AND OVERRIDING Synchronized or strictfp methods do not have any impact on the overriding method. It's possible that a non-synchronized or non-strictfp method can override a synchronized/strictfp method or vice versa. MultiLevel Method Overriding in Java In the multilevel method overriding we create a grandchild class and override the display() method of the parent class. Let's find out what will happen if we perform runtime polymorphism in multilevel overriding. // MultiLevel Overriding //Base class or SuperClass class Parent { //overridden method void display() {
System.out.println("parent method is executed"); } } //Derived class or SubClass class Child extends Parent { //This method overrides the Parent display() method @Override void display() { System.out.println("child method is executed"); } } //Inherited Class class GrandChild extends Child { // This method overrides the Parent display() method @Override void display() { System.out.println("grand child method is executed"); } } //Driver Class public class MethodOverriding9 { public static void main(String args[]) { Parent grandchildObject = new GrandChild(); grandchildObject.display(); } } Output: grand child method is executed EXAMPLES OF LEGAL/ILLEGAL METHOD OVERRIDES Let's have a simple class Animal with the eat() method.
public class Animal { public void eat() { } } Below is the list of the legal/illegal overrides of the Animal eat() method 1. private void eat() {} - Illegal override code. Access modifier is more restrictive. 2. public void eat() throws IOException {} - Illegal override code. It declares a checked exception not defined by the superclass version. 3. public void eat(String food) {} - A legal overload, not an override because the argument list changed. 4. public String eat() {} - Not an override because of the return type, not an overload either because there's no change in the argument list. ADVANTAGES OF USING @OVERRIDE ANNOTATION IN THE CODE According to Oracle docs, @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. // mark method as a superclass method // that has been overridden @Override int overriddenMethod() { } While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error. Overloading vs Overriding
1. Overloading is an example of compile-time polymorphism while Overriding is an example of run- time polymorphism. 2. In the method overloading parameters must be different. In overriding parameters must be the same (different if covariant return type). 3. Method overloading increases the readability of the program. Meanwhile, method overriding provides a specific implementation of the method. Difference between method overloading and method overriding in java There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below: N o . Method Overloading Method Overriding 1) Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2) Method overloading is Method overriding occurs in two classes
performed within class. that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4) Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. 5) In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding. Java Method Overloading example class OverloadingExample{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } Java Method Overriding example class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} }
java full.docx

java full.docx

  • 1.
    UNIT I chapter 2: Java Evolution 1. Java History 2. Java Features 3. How Java differs from C and C++ 4. Java and Internet 5. Java and World Wide Web 6. Web Browsers 1. Java History • Java is a general-purpose, OOP language developed by Sun Microsystems of USA in 1991. • Originally called Oak by James Gosling • Java was originally designed for the development of Software for Consumer electronic devices like TVs, VCRs… Goal : Make the language simple, portable and highly reliable. • Java team included the existing languages like C & C++. • But it had limitations in terms of both reliability and portability. • They modeled their new language Java on C & C++ • But removed number of features of C & C++ • And made Java a really simple, reliable, portable and powerful language. 2. Java Features • The inventors of Java wanted to design a language which could offer solutions to some of the problems encountered in modern programming •The Java not only reliable, portable and distributed but also simple, compact and interactive. (Table diagram) b) Platform-Independent and Portable •The most significant features of Java is its portability. •Java programs can be easily moved from one computer system to another, anywhere and anytime.
  • 2.
    •Changes and upgradesin Oss, Processors and System resources will not force any changes in Java programs. •This is the reason java has become a popular language for programming on Internet which interconnects different kinds of systems worldwide. •We can download a Java applet from a remote computer onto our local system via internet and execute it locally. b) Platform-Independent and Portable • The most significant features of Java is its portability. • Java programs can be easily moved from one computer system to another, anywhere and anytime. • Changes and upgrades in Oss, Processors and System resources will not force any changes in Java programs. • This is the reason java has become a popular language for programming on Internet which interconnects different kinds of systems worldwide. • We can download a Java applet from a remote computer onto our local system via internet and execute it locally. • Java ensures portability in 2 ways • First, Java compiler generates bytecode instructions that can be implemented on any machine. • Secondly, the size of the primitive data types are machine-independent. Java ensures portability in 2 ways • First, Java compiler generates bytecode instructions that can be implemented on any machine. • Secondly, the size of the primitive data types are machine-independent. c) Object-Oriented • Java is a true OO language. • Almost everything in Java is an Object. • All program code and data reside within objects and classes. • Java comes with an extensive set of lasses, arranged in packages, that can use in our programs by inheritance.
  • 3.
    • The Objectmodel in Java is simple and easy to extend. d) Robust and Secure Robust • Java is a robust language. • It provides many safeguards to ensure reliable code. • It has strict compile time and run time checking for data types. • It is designed as a garbage-collected language relieving the programmers virtually all memory management problems. • Java also incorporates the concept of Exception handling which captures serious and eliminates any risk of crashing the system. Security • It becomes an important issue for a language that is used for programming on Internet. • Threat of Viruses and abuse of resources are everywhere. • Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet. • The absence of pointers in Java ensures that programs cannot gain access to memory locations without proper authorization. e) Distributed • Java is designed as a distributed language for creating applications on networks. • It has the ability to share both data & programs • Java applications can open & access remote a bjects on Internet as easily as they can do in a local system. • It enables multiple programmers at multiple remote locations to collaborate and work together on a single project. f) Simple, Small and Familiar Simple & Small • Java is a small and simple language. • Many features of C & C++ that are earlier redundant or sources of unreliable code are not part of java. • Ex: no pointers, processor header files, goto and many others.
  • 4.
    • Also eliminatesOperator Overloading and multiple inheritance. Familiar • To make the language look familiar to the existing programmers. • It was modeled on C & C++ languages. • It used many constructs of C & C++ • In fact, Java is a simplified version of C++. g) Multithreaded and Interactive • Multithreaded means handling multiple tasks simultaneously. • Java supports multithreaded programs • We need not wait for the application to finish one task before beginning another. • It improves the interactive performance of graphical applications. • The Java runtime comes with tools that support multiprocess synchronization and construct smoothly running interactive systems. h) High Performance • Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode. • Java speed is comparable to the native C/C++. • Java architecture is also designed to reduce overheads during runtime. • The incorporation of multithreading enhances the overall execution speed of Java programs. i) Dynamic and Extensible • Java is a dynamic language. • Java is capable of dynamically linking in new class libraries, methods, and objects. • Java can also determine the type of class through a query, making it possible to either dynamically link or abort the program, depending on the response. • Java programs support functions written in other languages such as C & C++. • These functions known as native methods. • This facility enables the programmers to use the efficient functions available in these languages. • Native methods are linked dynamically at runtime.
  • 5.
    II) Additional Featuresof J2SE 5.0 a) Ease of Development • Java 2 Standard Edition (J2SE) 5.0 supports features, such as Generics, enhanced for Loop. Autoboxing or unboxing., Typesafe Enums, Varargs, Static import and Annotation. • It reduce the work of the programmer by shifting the responsibility ofcreating the reusable code to the compiler. • The resulting source code is free from bugs because the errors made by the compiler are less when compared to those made by programmers. • Thus, each of the linguistic features is designed to develop java programs in a easier way. b) Scalability and Performance • J2SE 5.0 assures a significant increase in scalability and perfoemance by improving the startup time and reducing the amount of memory used in Java 2 runtime environment. • For example, the introduction of the class, data sharing in the Hotspot Java Virtual Machine(JVM) improves the startup time by loading the core classes from the jar files into a shared archive. • Memory utilization is reduced by sharing data in the shared archive multiple JVM processes. c) Monitoring and Manageability • Java supports a number of APIs, such as JVM Monitoring and Management API, Sun Management Platform Extension, Logging, Monitoring and Management Interface and Java Management Extension (JMX) to monitor and mange java applications. d) Desktop client • J2SE 5.0 provides enhanced features to meet to meet the requirements and challenges of the java desktop users. • It provides an improved Swing look and feel called Ocean. • This feature is mainly used for developing graphics applications that require OpenGL hardware acceleration. • Miscellaneous Features J2SE 5.0 supports the following features: e) Core XML Support
  • 6.
    • J2SE 5.0adds a powerful XML feature to the Java platform. • Java contains some special packages for interface to instantiate Simple API for XML(SAX) and Document Object Model (DOM) parsers to parse an XML document, transform the content of an XML document, and validate an XML document against the schema. f) Supplementary Character Support • Java adds the 32-bit supplementary character support as part of the Unicode 4.0 support. • The supplementary characters are encoded with UTF-16 values to generate a different character called surrogate code point. g) JDBC RowSet • To send data in a tabular format between the remote components of a distributed enterprise application. • Contains CacheRowSet & WebRowSet. • This object contains a number of rows of data, which are retrieved from the database. • The data stored in the CacheRowtSet can be directly accessed without connecting to the database or any other data source. • The rows of data that are retrieved from the database can be synchronized later. • The WebRowSet object can operate without being connected to the database or data source and it uses XML format to read and write the rowset. • III) Enhancement in Java SE 6 • Some of the Key enhancements in Java SE 6 are : • a) Scripting Language Support • Java SE 6 integrates various scripting languages such as Java Script and PHP Script into the Java platform. • It allows scripts to be embedded in Java programs and compiled and executed with the help of appropriate scripting engine. • b) XML Processing and Web services • It allows development of web services and clients that communicate using XML • c) JDBC 4.0 Support • For developing database-centric applications
  • 7.
    • As aresult, programmers can leverage the various features of JDBX 4.0 such as automatic loading of JDBC driver class, connection management features etc., • d) Annotation-based Programming • It allows programmers to define annotations(meta-tags) for various program elements so that the same can be used by the compiler or other tools to generate ready code whenever necessary. • e) Dynamic compilation • The Java compiler API allows dynamic compilation of Java source code form a running Java application. IV) Enhancement in Java SE 7 Some of the Key enhancements in Java SE 7 are : a) Language Enhancements • Java SE 7adds several language features aimed at helping the programmers implement difficult functionality with ease. • The new language features include strings in switch statement, multiple handling, diamond syntax etc. b) NIO 2.0 • The new file system API(NIO 2.0) in Java SE 7 makes it a lot easier to work with the systems. • It contains several enhancements to the standard file operations such as open, read, write etc. • In addition, it also allows the programmers to create custom file systems. c) Parallel Programming • Java SE 7 facilitates Parallel Programming through the use of Fork/join Framework. • While the conventional multithreaded programming allowed programmers to use a single processor for multitasking. d) Dynamic Language Support • The Java SE 7 supports dynamically typed languages in the JVM. • The invoked dynamic instruction is used to define customized linkage mechanisms for these languages. 3. How Java Differs from C and C++ • Although Java was modeled after C & C++languages
  • 8.
    • It differsfrom C and C++ in many ways • Java does not incorporate a number of features available in C & C++. • For the benefit of C & C++ programmers, we point out here a few major differences between C/C++ & Java languages. Java and C Major Difference : • Java is an OOP and has mechanism to define classes and objects. • In an effort to build a simple and safe language, the java team did not include some of the C features in Java i) Java does not include the C unique statement keywords sizeof and typedef. ii) Java does not contain the data types strut and union. iii) Java does not define the type modifiers keyword auto, extern, register, signed and unsigned. iv) Java does not support an explicit pointer type. v) Java does not have a preprocessor and therefore we cannot use #define, #include and #ifdef statements. vi) Java requires that the functions with no arguments must be declared with empty parenthesis and not with the void keyword as done in C. vii) Java adds new operators such as instance of and >>>. viii) Java adds labeled break and continue statements. ix) Java adds many features required for OOP. Java and C++ Major Difference : • Java is an true OOP language while C++ is basically C with OO extension. i) Java does not support operator overloading. ii) Java does not have template classes as in C++. iii) Java does not support multiple inheritance of classes. But it is accomplished using new feature called “interface”.
  • 9.
    iv) Java doesnot support global variables. Every variable and method is declared within a class and form part of that class. v) Java does not use pointers. vi) Java has replaced the destructor function with a finalize( ) function. vii) There are no header files in Java. Java also add some new features : • While C++ is a superset of C • Java is neither a superset nor a subset of C or C++. • Java may be considered as a first cousin of C++ and a second cousin of C. Diagram Overlapping of C, C++ and Java 4. Java and Internet • Java is strongly associated with the Internet because of the fact that the first application program written in Java was HotJava, a Web browser to run applets on Internet. • Internet users can use Java to create applet programs and run them locally using a “java-enabled browser” such as HotJava. • They can also use a Java-enabled browser to download an applet located on a computer anywhere in the internet and run it on his local computer. • In fact, java applets have made the Internet a true extension of the storage system of the local computer. • Internet users can also set up their web sites containing Java applets that could be used by other remote users of Internet. • The ability of Java applets to hitch a ride on the information superhighway has made Java a unique programming language for the Internet. • Java is popularly known an Internet language. Diagram 5. Java and WWW WWW
  • 10.
    • WWW isan open-ended information retrieval system designed to be used in the internet’s distributed environment. • Contains web pages that provide both information and controls. • Unlike a menu-driven system where we are guided through a particular direction using a decision tree structure • The web system is open-ended and we can navigate to a new document in any direction. • It is made possible with the help of a language called HTML • Web pages contain HTML tags that enable us to find, retrieve, manipulate and display documents worldwide. Diagram • Java was meant to be used in distributed environment such as internet. • Since, both the Web and Java share the same philosophy, java could be easily incorporated into the web system. • Before java, the WWW limited to the display of still images and texts. • However, the incorporation of java into web pages has made it capable of supporting animation, graphics, games and a wide range of special effects. • With the support of java , the web has become more interactive and dynamic. • We can run a java program on someone else’s computer across the internet. Diagram Communication Steps • The user sends a request for an HTML document to the remote computer’s web server. The web server is a program that accepts a request, and sends the required document. • The HTML document is returned to the user’s browser. The document contains the APPLET tag, which identifies the applet. • The corresponding Applet bytecode is transferred to the user’s computer. This bytecode had been previously created by the java compiler using the java source code file for that applet. • The java-enabled browser on the user’s computer interprets the bytecodes and provides output.
  • 11.
    • The usermay have further interaction with the applet but with no further downloading from the provider’s web server. This is because the bytecode contains all the information necessary to interpret the applet. 6. Web Browsers • The internet is a vast sea of information in many formats and stored on many computers. • A large portion of the internet is organized as the WWW which uses hypertext. • Web Browsers are used to navigate through the information found on the net. • They allow us to retrieve the information spread across the internet and display using the HTML. • Examples i) HotJava ii) Netscape Navigator iii) Internet Explorer i) HotJava • is the web browser from Sun Microsystems that enables the display of interactive content on the Web using the Java Language. • Written entirely in Java and demonstrates the capabilities of the java programming language. • When the java language was first developed and ported to the Internet, no browsers were available that could run java applets. • Although we can view a web page that includes java applets with a regular browser, we will not gain any of java’s benefits. ii) Netscape Navigator • From netscape communication corporation, is a general-purpose browser that can run java applets. • With version available for Windows, Solaris and Apple Macintosh, Netscape Navigator was one of the most widely used browsers of its time. • But with increasing popularity of IE browser, the use of NN decreased over a period of time.
  • 12.
    • Even Netscapecommunication has stopped further development of this browser after its latest stable release 9.0 in March 2008 iii) Internet Explorer • It is another popular browser developed by Microsoft for Windows 95, NT and XP workstations. • Both the NN & IE use tool bars, menus and dialog boxes for easy navigation. • IE uses a just-in-time(JIT) compiler which greatly increases the speed of execution. 7. H/W & S/W Requirements : • Platform – Solaris, windows intel architecture 32-bit, Linux 32-bit etc., • Memory - 64/128 MB • Browsers – Mozila, IE • Disk Space – 98/110/58/56 MB 8. Java Support Systems : • Internet connection • Web Server • Web Browser • HTML • APPLET Tag • Java Code • Byte code • Proxy server • Mail Server 9. Java Environment : i) JDK (Java Development Kit)
  • 13.
    comes with acollection of tools that are used for developing and running java programs. • Appletviewer – for viewing java applets • Javac – java compiler • Java – java interpreter • Javap – jave disassembler • Javah – for C header files • Javadoc – for creating HTML documents • Jdb – java debugger ii) API (Application Programming Interface) includes 100s of classes and methods grouped into several functional packages. • Language support Package – implementing basic features of Java • Utilities Package – provide utility functions such as date and time functions • I/O Package – for I/O manipulation • Networking Package – for communicating with other computers via the internet • AWT Package – implements platform-independent GUI • Applet Package – allows us to create java applets iii) JRE (Java Runtime Environment) facilitates the execution of programs developed in Java • JVM – it is a program that interprets the intermediate Java byte code and generates the desired o/p. • Runtime class libraries – a set of core class libraries that are required for the execution of java programs. • User interface toolkit – support varied i/p methods for the users to interact with the application program. • Deployment technologies – comprises a) Java plug-in – enbles the execution of a java applet on the browser b) Java web start – enables remote-deployment of an application. OVERVIEW OF JAVA LANGUAGE
  • 14.
    To create asimple java program, you need to create a class that contains main method. Let's understand the requirement first. REQUIREMENT FOR HELLO JAVA EXAMPLE: For executing any java program, you need to • install the JDK if you don't have installed it, download the JDK and install it. • set path of the jdk/bin directory. • create the java program • compile and run the java program CREATING HELLO JAVA EXAMPLE : class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } save this file as Simple.java To compile : javac Simple.java To execute :java Simple JAVA PROGRAM STRUCTURE • Let’s use example of HelloWorld Java program to understand structure and features of class. • This program is written on few lines, and its only task is to print “Hello World from Java” on the screen. Refer the following picture. 1.“PACKAGES”:
  • 15.
    2. “PUBLIC CLASSHELLOWORLD”: 3. COMMENTS SECTION: 4. “PUBLIC STATIC VOID MAIN (STRING [ ] ARGS)”: 5. SYSTEM.OUT.PRINTLN("HELLO WORLD FROM JAVA") JAVA TOKENS • A Java program is basically a collection of classes. • A class is defined by a set of declaration statements and methods containing executable statements. • Most statements contain expressions, which describe the actions carried out on data. • Smallest individual unit in a program are known as tokens. • The compiler recognizes them for building up expressions and statements. 5 Types of Tokens i. Reserved keywords ii. Identifiers iii. Literals iv. Operators v. Separators Diagram JAVA CHARACTER SET • The smallest units of Java language are the characters used to write Java tokens. • These characters are defined by the Unicode character set. • Emerging standard that tries to create characters for a large number of scripts worldwide. • The Unicode is a 16-bit character coding system and currently supports more than 34,000 defined characters. • That is derived from 24 languages
  • 16.
    KEYWORDS IN JAVA •Java Keywords also called a reserved word. Keywords are identifiers that Java reserves for its own use. • Since keywords have specific meanings • These identifiers have built-in meanings that cannot change. • There are 50 reserved keywords currently defined in the Java language and they are shown in the below table. • Eg. Boolean, interface, abstract • We cannot use them as names for variables, classes, methods etc.,. JAVA STATEMENT: • Statements are roughly equivalent to sentences in natural languages. • A statement is an executable combination of token ending with a semicolon(;) mark. • A statement forms a complete unit of execution. • The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). • Statements are usually executed in sequence in the order in which they appear. • So it control flow of execution • If necessary , using special statements. • Assignment expressions • Any use of ++ or -- • Method invocations • Object creation expressions • Such statements are called expression statements. • Here are some examples of expression statements. // assignment statement aValue = 8933.234;
  • 17.
    // increment statement aValue++; //method invocation statement System.out.println("Hello World!"); // object creation statement Bicycle myBike = new Bicycle(); Diagram Summary of Java Statements : Statement Description Remarks Empty Statement These do nothing and are used during program development as a place holder Same as C & C++ Labelled Statement Any Statement may begin with a lebel. Such label not be keywords Identical to C & C++ except jump Expression Statement Most Statements are expression Statements. 7 Types : Assignment, Pre-increment, Pre-Decrement, post-increment. Post- Decrement, Method call and Allocation Expression Same as C++ Selection Statement Select one of several control flows: if, if-else. Same as C & C++ Iteration Statement How and when looping will take place Identical to C & C++ except jump& label
  • 18.
    2 Diagrams WHAT JVMDOES? The JVM performs following operation: Loads code Verifies code Executes code Provides runtime environment JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc. VARIABLES IN JAVA 1. Introduction 2. Declaration of Variables 3. Giving Values to Variables 4. Scope of Variables Jump Statement Pass control to the beginning or end of the current block C & C++ do not use labels with jump Synchronization Statement These are used fro handling issues with multithreading Now available in C & C++ Guarding Statement For safe handling of code that may cause exceptions. Try, catch, finally… Same as in C++ except finally statement
  • 19.
    5. Getting Valuesof variables 6. Standard Default Values 7. Type casting 1. INTRODUCTION : • A variable is an identifier that denotes a storage location used to store a data value. • Constants – that remain unchanged during the execution of a program • Variable – may take different values of different times during the execution of the program • variable is chosen by the programmer in a meaningful way. • Consists of alphabets, digits, underscore and dollar characters Conditions : • They must not begin with a digit • Uppercase & Lowercase are distinct. • Not be a keyword • White space is not allowed • Any length 2. Declaration of Variables : • Variables hold one value at a time, but that value can change • After defining suitable names, declare them to the compiler. 3 things i. It tells the compiler what the variable name is ii. Specifies type of the data variable iii. Scope of the variable Syntax:
  • 20.
    dataType identifier; or dataType var1,var2, … varn; • Variables are separated by commas Ex: int x; float y; 3. Giving Values to Variables : A variable must be given a value after it has been declared but before used Achieved in 2 Ways : i) By using an Assignment statement ii) By using a read statement By using an Assignment statement - A simple method of giving value to a variable Syntax: variableName = value; Ex : x = 5; - Also possible to assign a value to a variable at the time of declaration Syntax: type variableName = value; Ex : int x = 5; By using a read statement - through the keyboard using the readLine( ) method Ex : System.out.printline(“Enter vale”); x = Integer.parseInt(in.readLine( )); readLine( ) – reads the i/p from the keyboard as a string which is then converted to the corresponding data type using the data type wrapper classes.
  • 21.
    i) By usinga read statement Reading I/p from Keyboard a) Use System.Console class – to read lines Ex : System.out.printline(“Enter value”); int x = System.Console().readLine( ); System.out.printline(“The valu is :” + x); b) Use java.util.Scanner class and System.in Ex : Scanner sc=new Scanner(System.in); String s = sc.nextLine(); -> read the line System.out.println(“ the string is” + s); By using a read statement Reading I/p from Keyboard c) Use BufferedReader class – to read lines Ex : InputStreamReader isr = new InputStreamReader(System.in) BufferedReader br = new BufferedReader(isr); 4. Scope of Variables : 3 Kinds : a) instance variables b) class variables c) local variables Instance and class variables are declared inside a class a) instance variables - created when the objects are instantiated and they are associated with the objects.
  • 22.
    - take differentvalues for each objects. b) class variables - global to a class & belong to the entire set of objects that class creats - only one memory location is created. c) local variables - variables declared and used inside methods are called local variables -not available for outside the method definition -declared inside a program blocks - defined b/w { } . 5. Getting Values of Variables : Java supports 2 o/p methods - i) print( ) method - ii) println( ) method i) print( ) method - sends information into a buffer -This buffer is not flused until a newline character in sent - prints o/p on one line until a newline is encountered Ex : System.out.print(“Hi”); ii) println( ) method - stake the information provided and displays it on a line followed by a line feed Ex : System.out.println(“Hi”); 6. Standard Default Variables : - Every variable has a default value.
  • 23.
    7. TYPE CASTING: - To store a value of one type into a variable of another type Syntax: type var1 = (type) var2; Ex : int m = 10; byte n = (byte) m; Automatic Conversion - assign a value of one type to a variable of a different type without a cast. Type of variable Default value byte Zero:0 short Zero:0 int Zero:0 long Zero:0L float 0.0f double 0.0d char null character boolean false reference null
  • 24.
    - the conversionof the assigned value automatically known as automatic-type conversion Ex : byte b =10; int a =b; From To byte Short, char, int, long, float, double short Int, long, float, double char Int, long, float, double int long, float, double long float, double float double VARIABLE ARGUMENT (VARARGS): The varrags allows the method to accept zero or muliple arguments. Before varargs either we use overloaded method or take an array as the method parameter but it was not considered good because it leads to the maintenance problem. If we don't know how many argument we will have to pass in the method, varargs is the better approach. ADVANTAGE OF VARARGS: WE DON'T HAVE TO PROVIDE OVERLOADED METHODS SO LESS CODE. SYNTAX OF VARARGS: The varargs uses ellipsis i.e. three dots after the data type. Syntax is as follows: 1. return_type method_name(data_type... variableName){} SIMPLE EXAMPLE OF VARARGS IN JAVA: 1. 2. class VarargsExample1{ 3. 4. static void display(String... values){ 5. System.out.println("display method invoked "); 6. } 7. 8. public static void main(String args[]){ 9.
  • 25.
    10. display();//zero argument 11.display("my","name","is","varargs");//four arguments 12. } 13. } 14. Test it Now Output:display method invoked display method invoked ANOTHER PROGRAM OF VARARGS IN JAVA: 1. 2. class VarargsExample2{ 3. 4. static void display(String... values){ 5. System.out.println("display method invoked "); 6. for(String s:values){ 7. System.out.println(s); 8. } 9. } 10. 11. public static void main(String args[]){ 12. 13. display();//zero argument 14. display("hello");//one argument 15. display("my","name","is","varargs");//four arguments 16. } 17. } 18. Test it Now Output:display method invoked display method invoked hello display method invoked my name is varargs download this example
  • 26.
    Rules for varargs: Whileusing the varargs, you must follow some rules otherwise program code won't compile. The rules are as follows: o There can be only one variable argument in the method. o Variable argument (varargs) must be the last argument. EXAMPLES OF VARARGS THAT FAILS TO COMPILE: 1. 2. void method(String... a, int... b){}//Compile time error 3. 4. void method(int... a, String b){}//Compile time error 5. EXAMPLE OF VARARGS THAT IS THE LAST ARGUMENT IN THE METHOD: 1. 2. class VarargsExample3{ 3. 4. static void display(int num, String... values){ 5. System.out.println("number is "+num); 6. for(String s:values){ 7. System.out.println(s); 8. } 9. } 10. 11. public static void main(String args[]){ 12. 13. display(500,"hello");//one argument 14. display(1000,"my","name","is","varargs");//four arguments 15. } 16. } 17. Test it Now Output:number is 500 hello number is 1000
  • 27.
    my name is varargs Varargs is ashort name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body } In order to define vararg, ... (three dots) is used in the formal parameter of a method. A method that takes variable number of arguments is called a variable-arity method, or simply a varargs method. First, let’s look at the example without using varargs: class NoVararg { public int sumNumber(int a, int b){ return a+b; } public int sumNumber(int a, int b, int c){ return a+b+c; } public static void main( String[] args ) { NoVararg obj = new NoVararg(); System.out.println(obj.sumNumber(1, 2)); System.out.println(obj.sumNumber(1, 2, 3)); }
  • 28.
    } When you runthis program, the output will be: 3 6 As you can clearly see, you had to overload sumNumber() method to make it work for 3 arguments. THINGS TO REMEMBER WHILE USING VARARGS Here are a couple of things you should remember while working with Java vargars: 1. While defining method signature, always keep varargs at last. The variable argument must be the last argument passed to the method. Let's consider, you invoked doSomething() method like this: doSomething(1, 2, 3, 4); And, your doSomething() method is defined as: // incorrect method declaration public void doSomething(int ... nums, int p){ // method body } In this case, compiler cannot figure out the number of arguments passed to nums. However, if you define your method as: public void doSomething(int p, int ... nums) { // method body } The Java compiler assigns the first argument to p, and the remaining int arguments are assigned to nums. 2. A method can have only one varargs parameter. For example, this method declaration is incorrect:
  • 29.
    int doSomething(int p,float ... floatNums, double ... doubleNums) { // code } AMBIGUITY IN VARARGS METHOD OVERLOADING Let’s consider you overloaded test() method like this: class Demo { static void test(int ... vargs) { // method body } static void test(int n, int ... vargs) { // method body } } In the above program, the compiler gets confused if you try to invoke the test() method even though test() methods are overloaded and accepts different number of arguments. OPERATORS IN JAVA : 2 )
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
    19 ) EXPRESSIONS INJAVA : Definition : • An expression in java is a combination of operators , variables ,constants & method invocations. • Expression is used to perform the computation indicated by the elements of the expression and return some value. Example : int a=5; // returns 5 if(a==b) // returns Boolean value c = a + b; // returns a manipulated values System.in.read(); // evaluate a single value TYPES OF EXPRESSIONS : There are three types of expressions in java. They are, 1. Expression that produce a value 2. Expression that assign a variable 3. Expressions with no result EXPRESSIONS THAT PRODUCE A VALUE :
  • 36.
    • It usesoperators to produce a value such a Arithmetic operators ,Conditional operator, Comparison operator , etc… • Example: C=3+2 A=10/5 B= 2*4/5 EXPRESSIONS THAT ASSIGN A VARIABLE : • It is a expression that assigns a value to the variable. • Example: Int A=0; // assigns integer value B= true; // assigns boolean value EXPRESSIONS WITH NO RESULT : • Some expressions does not produce result but give a side effect which occurs when an expression changes the Value of an operands. • Example: P = a*b; Here value of variable ‘p’ is changed when calculated , but value of variable ‘a’ and ‘b’ does not change. This is called side effect. • a++ • Here ,value of variable ‘a’ is changed according to the program. Unit – II Classes, Objects and Methods 1. Introduction 2. 2. Defining a Class 3. Methods Declaration
  • 37.
    4. Creating Objects 5.Accessing Class Members 6. Constructors 7. Method Overloading 8. Static Members 9. Nesting of Methods 10. Inheritance : Extending a Class 11. Overriding Methods 12. Final Variables and Methods 13. Final Classes 14. Finalizer Methods 15. Abstract Methods and Classes 16. Methods with Varargs 17. Visibility Control INTRODUCTION : • Java is a true OOPL • The underlying structure of all Java programs is classes. • Anything represented in a class • Class defines the state and behavior of the basic program components known as objects • Classes create objects and objects use methods to communicate between them • Classes provide a convenient method for packing together a group of logically related data items and functions • In Java The data items are called fields and the functions are called methods. DEFINING A CLASS : • A class is a user-defined data type with a template that serves to define its properties
  • 38.
    • These variablesare called instance variables because they are created whenever an object of the class is instantiated. Ex : class A { int length; Int width; } 3. FIELDS DECLARATION : • Data is encapsulated in a class by placing data fields inside the body of the class definition • Once the class type has been defined, we can create variables of that type using declarations that are similar to the basic-type declarations. • These termed as instances of classes, which are the actual objects. Syntax class classname [extends superclasname] { [ fields declaration; ] [methods declaration;] } Ex : class A { } 4. METHODS DECLARATION : • A class with only data fields & without methods that operate on that data has no life. • The objects created by such a class cannot respond to any messages. Syntax type methodname (parameter-list) { Method-body;
  • 39.
    } 4 basic parts: i) The name of the method – method name ii) The type of the value the method returns – type iii) A list of parameters(parameter-list) iv) The body of the method Ex : Class Rect { Int len, wid; Void getdata(int x, int y) { len=x; Wid=y; } } 5. CREATING OBJECTS : • An object in java is essentially a block of memory that contains space to store all the instance variables. • object in java are created using the new operator • The new operator creates an object of the specified class and returns a reference to that object. Ex: Rect r1; R1=new Rect( ); (or) Rect r1 = new Rect( ); Diagram Diagram 6. ACCESSING CLASS MEMBERS :
  • 40.
    • All variablesmust be assigned values before they are used. • Outside of the class cannot access the instance variables and methods directly. • so, we must use the concerned object and the dot operator Syntax : objectname.variablename = value; objectname.methodname(parameter-list); Variablename -> name of the instance variable inside the object we wish to access Methodname -> the method we wish to call Parameter list-> actual values that must match in type and number Ex: Rect r1 = new Rect( ); Rect r2=r1; r1.getdata(25, 30) r1.length = 10; r2.length = 12; Ex: void getdata(int x, int y) { length = x; width = y; } ….main( ) { Rect r1 = new Rect( ); r1.getdata(25, 30) } 7. CONSTRUCTORS : 2 approaches ( objects created) : i) Uses the dot operator to access the instance vars & assign values to them immediately. - difficult to initialize all the vars to all the objs ii) Takes the help of a method like r1.getdata(15,20); - simple one iii) But java supports special type of method called a constructor. - It enables an object to initialize itself when it is created. Constructor :
  • 41.
    • Have thesame name as the class itself • Do not specify a return type not even void • Because it return the instance of the class itself. Ex : class Rect { int length; int width; Rect(int x, int y) { length = x; width = y; } int rectArea() { return(length * width); }} 8. METHOD OVERLOADING : Definition – Method Overloading In java, possible to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading. • It is used when objects are required to perform similar task but using different input parameters • When we call a method, it follows - first matches the method name - then the number of parameters - type of parameters • This process is known as polymorphism. • Ex : – Method Overloading class Rect { int length; int width; Rect(int x, int y) // Constructor 1 { length = x; width = y }
  • 42.
    Rect(int x) //Constructor 2 { length = width=x; } int rectArea() { return(length * width); }} 9. STATIC MEMBERS : Class contains 2 sections i) declares variables ii) declares methods - these variables & methods are called instance variables & instance methods. - because every time the class is instantiated, a new copy of each of them is created. - they are accessed using the objects with dot operator. • Assume, we want to define a member that is common to all the objects and accessed without using a particular object. • ie., the member belongs to the class as whole rather than the objects created from the class. Ex: static int c; static int area(int x, int y); - the members are declared as static are called static members. - these members associated with the class itself rather than individual objects. - the static vars & methods referred to as class vars & methods. - Static vars are used when we want to have a var common to all instances of a class. Ex : class Operation { static float mul(float x, float y) { return x*y; } static float div(float x, float y) { return x/y; }} Class MathOp
  • 43.
    { public voidstatic main(String args[]) { float a = Operation.mul(5.0,2.0); float b = Operation.div(6.0,2.0); System.out.ptintln(“a=“+a); System.out.ptintln(“b=“+b) }} 10. NESTING OF METHODS : Def : A method can be called by using only its name by another method of the same class is known as nesting of methods. class Nest { int large() { …. } class display( ) { int l = large( ); } Class Ntest { public void static main(String args[]) { ….. } INHERITANCE IN JAVA : 1. Inheritance 2. Types of Inheritance 3. Why multiple inheritance is not possible in Java in case of class? Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship. Why use inheritance in java o For Method Overriding (so runtime polymorphism can be achieved).
  • 44.
    o For CodeReusability. Terms used in Inheritance o Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass. Java Inheritance Example
  • 45.
    As displayed inthe above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Test it Now Programmer salary is:40000.0 Bonus of programmer is:10000 In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability. Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
  • 46.
    Note: Multiple inheritanceis not supported in Java through class. When one class inherits multiple classes, it is known as multiple inheritance. For Example: Single Inheritance Example When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. TestInheritance.java class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat();
  • 47.
    }} Output: barking... eating... Multilevel Inheritance Example Whenthere is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }} Output: weeping... barking... eating... Hierarchical Inheritance Example When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. TestInheritance3.java
  • 48.
    class Animal{ void eat(){System.out.println("eating...");} } classDog extends Animal{ void bark(){System.out.println("barking...");} } class Cat extends Animal{ void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//C.T.Error }} Output: meowing... eating... Q) Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{//suppose if it were
  • 49.
    public static voidmain(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } } Test it Now Compile Time Error Method Overriding Method Overloading and Method Overriding are the topics that should be on your to-do list before appearing for the interview. In this post, I will share what is method overriding, the rules of method overriding, and examples. So let's dive in and understand method overriding in java. What is Method Overriding When the child class(subclass) has the method which has the same name, same parameters and same return type (or covariant return type) as a method in its parent class(or super-class), then the child method has overridden the parent class method. Runtime polymorphism can be achieved through method overriding. Remember that at runtime, Object type (not reference variable's type) determines which overridden method is used. If the parent class object is used to invoke the method, then the parent class method will be executed. Otherwise, if, a child class object is used to invoke the method, then the child class method will be executed. Example of Method Overriding
  • 50.
    // Method OverridingExample //Base class class Parent { public void display() { System.out.println("parent method is executed"); }} //Derived or Inherited class class Child extends Parent { //Below method overrides the Parent display() method @Override public void display() { System.out.println("child method is executed"); }} //Driver class public class MethodOverriding1 { public static void main(String args[]) { // If a Parent type reference refers // to a Parent object, then Parent's // display() is called Parent parentObject = new Parent(); parentObject.display(); // If a Parent type reference refers // to a Child object Child's display() // is called. This is called RUN TIME // POLYMORPHISM. Parent childObject = new Child(); childObject.display(); }} Output: parent method is executed child method is executed RULES FOR METHOD OVERRIDING IN JAVA 1. ACCESS MODIFIERS AND OVERRIDING
  • 51.
    The access levelcan't be more restrictive than the overridden method. The access level can be less restrictive than that of the overridden method. For example, a protected instance method in the parent class(superclass) can be made public but not private in the child class(subclass). If you try to make a child class private then it will give the compile- time error.
  • 52.
    // Access Modifiersand Overriding Example //Base class class Parent { //Access modifier of parent's display() method is protected protected void display() { System.out.println("parent method is executed"); } } //Derived class class Child extends Parent { //Below method overrides the Parent display() method //Access modifier public is less restrictive than protected @Override public void display() { System.out.println("child method is executed"); } } //Driver class public class MethodOverriding2 { public static void main(String args[]) { Parent parentObject = new Parent(); parentObject.display(); Parent childObject = new Child(); childObject.display(); }} Output : parent method is executed child method is executed 2. Private methods can not be overridden Another rule regarding access modifiers is you can not override private methods in the parent class. If subclass tries to override the private method of a parent class then the program will throw a compile-time error as shown below. // Access Modifiers and Overriding Example //Base class or Superclass
  • 53.
    class Parent { //Accessmodifier of parent method is private // This method can not override the child class method private void display() { System.out.println("parent method is executed"); } } //Derived class or Subclass class Child extends Parent { //Below method can not overrides the Parent display() method //This method is unique to the child class private void display() { System.out.println("child method is executed"); } } //Driver class public class MethodOverriding3 { public static void main(String args[]) { Parent parentObject = new Parent(); parentObject.display(); // this line when execute will throw compiler error Parent childObject = new Child(); childObject.display(); // this line when execute will throw compiler error } } 3. FINAL METHODS CAN NOT BE OVERRIDDEN IN JAVA You can not override a method marked final. It will throw a compile-time error if you try to do so. // Simple Java program showing // final methods cannot be overridden //Parent class or Superclass class Parent {
  • 54.
    // Can't beoverridden final void display() { } } //Child class or Subclass class Child extends Parent { // This would produce compile time error void display() { } } Output : /Main.java:13: error: display() in Child cannot override display() in Parent void display() { } ^ overridden method is final 1 error 4. STATIC METHODS CAN NOT BE OVERRIDDEN You can not override a method mark static. If you define a static method in the subclass (child class) with the same method signature as the superclass(parent class) then it is called method hiding. // Method hiding example //Base class or SuperClass class Parent { static void display() { System.out.println("parent static method is executed"); } void show() { System.out.println("parent non-static (instance) method is executed"); } }
  • 55.
    //Derived class orSubClass class Child extends Parent { //This method hides the Parent display() method static void display() { System.out.println("child static method is executed"); } // This method overrides the Parent show() method void show() { System.out.println("child non-static (instance) method is executed"); } } //Driver Class public class MethodOverriding4 { public static void main(String args[]) { Parent childObject = new Child(); // static method can not be overridden, // so below line calls parent display() method childObject.display(); // Expected child method will run childObject.show(); } } Output: parent static method is executed child non-static (instance) method is executed 5. Invoking a superclass (Parent class) version of overridden method It's easy to call the superclass(Parent class) version of overridden method by using the super keyword. // Invoking SuperClass version of Overridden Method Example //Base class or SuperClass class Parent { void display() {
  • 56.
    System.out.println("parent method isexecuted"); } } //Derived class or SubClass class Child extends Parent { //This method overrides the Parent display() method @Override void display() { super.display(); System.out.println("child method is executed"); } } public class MethodOverriding5 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(); } } Output : parent method is executed child method is executed 6. Overriding method must have the same return type (or Covariant return type) The method return type must be the same, or a subtype of, the return type declared in the original overridden method in the superclass. Since java 5.0 it is made possible to have a different return type for an overriding method in a child class. But child's return type should be a subtype of the parent's return type. This phenomenon is called covariant return type. Example of Covariant Return Type class Alpha { Alpha doStuff(char c) { return new Alpha();
  • 57.
    } } class Beta extendsAlpha { Beta doStuff(char c) { // legal override in Java 1.5 return new Beta(); } } public class MethodOverriding6 { public static void main(String args[]) { Alpha childObject = new Beta(); childObject.doStuff('a'); } } The above code will compile and run. 7. CONSTRUCTOR AND OVERRIDING You can not override the constructor as the constructor name of the base class and child class can never be the same. (Constructor name is always the same as the class name). 8. Exception Handling and Overriding Rule 1. The overriding method can throw any unchecked(runtime) exception regardless of whether the overridden method declares the exception. // Overriding when superclass does not throw an exception //Base class or SuperClass class Parent { //overridden method void display() { System.out.println("parent method is executed"); } } //Derived class or SubClass
  • 58.
    class Child extendsParent { //This method overrides the Parent display() method //It throws unchecked exception i.e Arithmetic Exception @Override void display() throws ArithmeticException{ System.out.println("child method is executed"); } } public class MethodOverriding7 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(); } } Output: child method is executed Rule 2. The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException can not be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException. Note : The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares. 9. Abstract method and Overriding Abstract methods can only be overridden by the first concrete class (classes that have no abstract methods) otherwise a compiler error will be thrown. //Abstract class abstract class Parent { public abstract void display( int x, String j);
  • 59.
    } //Subclass or DerivedClass class Child extends Parent { @Override public void display( int x, String j ) { System.out.println("child method is executed"); } } //Driver class public class MethodOverriding8 { public static void main(String args[]) { Parent childObject = new Child(); childObject.display(1, "Alive is Awesome"); } } Output : child method is executed 10. SYNCHRONIZED/STRICTFP METHOD AND OVERRIDING Synchronized or strictfp methods do not have any impact on the overriding method. It's possible that a non-synchronized or non-strictfp method can override a synchronized/strictfp method or vice versa. MultiLevel Method Overriding in Java In the multilevel method overriding we create a grandchild class and override the display() method of the parent class. Let's find out what will happen if we perform runtime polymorphism in multilevel overriding. // MultiLevel Overriding //Base class or SuperClass class Parent { //overridden method void display() {
  • 60.
    System.out.println("parent method isexecuted"); } } //Derived class or SubClass class Child extends Parent { //This method overrides the Parent display() method @Override void display() { System.out.println("child method is executed"); } } //Inherited Class class GrandChild extends Child { // This method overrides the Parent display() method @Override void display() { System.out.println("grand child method is executed"); } } //Driver Class public class MethodOverriding9 { public static void main(String args[]) { Parent grandchildObject = new GrandChild(); grandchildObject.display(); } } Output: grand child method is executed EXAMPLES OF LEGAL/ILLEGAL METHOD OVERRIDES Let's have a simple class Animal with the eat() method.
  • 61.
    public class Animal{ public void eat() { } } Below is the list of the legal/illegal overrides of the Animal eat() method 1. private void eat() {} - Illegal override code. Access modifier is more restrictive. 2. public void eat() throws IOException {} - Illegal override code. It declares a checked exception not defined by the superclass version. 3. public void eat(String food) {} - A legal overload, not an override because the argument list changed. 4. public String eat() {} - Not an override because of the return type, not an overload either because there's no change in the argument list. ADVANTAGES OF USING @OVERRIDE ANNOTATION IN THE CODE According to Oracle docs, @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. // mark method as a superclass method // that has been overridden @Override int overriddenMethod() { } While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error. Overloading vs Overriding
  • 62.
    1. Overloading isan example of compile-time polymorphism while Overriding is an example of run- time polymorphism. 2. In the method overloading parameters must be different. In overriding parameters must be the same (different if covariant return type). 3. Method overloading increases the readability of the program. Meanwhile, method overriding provides a specific implementation of the method. Difference between method overloading and method overriding in java There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below: N o . Method Overloading Method Overriding 1) Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. 2) Method overloading is Method overriding occurs in two classes
  • 63.
    performed within class.that have IS-A (inheritance) relationship. 3) In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. 4) Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. 5) In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding. Java Method Overloading example class OverloadingExample{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } Java Method Overriding example class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} }