0% found this document useful (0 votes)
13 views31 pages

Java Unit 1 Material

The document provides an overview of Object-Oriented Programming (OOP) principles, emphasizing its advantages over procedural programming, such as modularity, data encapsulation, inheritance, and polymorphism. It discusses the features of Java as a robust, object-oriented language and its historical development, highlighting its platform independence and suitability for internet applications. The document also contrasts Java with C and C++, noting significant differences in language design and functionality.

Uploaded by

devi vijay
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
13 views31 pages

Java Unit 1 Material

The document provides an overview of Object-Oriented Programming (OOP) principles, emphasizing its advantages over procedural programming, such as modularity, data encapsulation, inheritance, and polymorphism. It discusses the features of Java as a robust, object-oriented language and its historical development, highlighting its platform independence and suitability for internet applications. The document also contrasts Java with C and C++, noting significant differences in language design and functionality.

Uploaded by

devi vijay
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
FUNDAMENTALS OF OBJECT ORIENTED - PROGRAMMING INTRODUCTION: > Object-oriented programming is an approach to development and an organization that attempts to eliminate some of the flaws of conventional programming. It involves new ways of organizing and developing programs and does not a concem using a particular language. C++ isa procedural language with object oriented extension, Java, a pure object oriented language. Languages supporting OOP feature v vvY include Smalltalk, Objective C, C++, Ada, Pascal, and Java. Definition of OOPS Concepts in Ja “Object-oriented programming is an approach that modularizes programs by creating a partitioned memory arca for both functions and data that can be used as templates for creating copies of such modules on demand.” OOPS Paradigm > The primary objective of the object-oriented approach is to eliminate some of the pitfalls that exist in the procedural approach. > OOPS allows decomposing a problem into several entities called Objects and then build data and functions from these entities. The combination of the data makes up an object. Object = Method + Data > The data of an object is accessed by the methods associated with that abject. However, the methods of an object can access methods of other objects. Features of OOPS Java isa robust and scalable object-oriented programming language that is based on the concept of objects and classes, Some features of object-oriented programming in java are: Emphasis is on data than procedures Programs are divided into objects Data Structures are designed! to characterize objects. Methods operating on the data of an object are tied together in the data structure. Data is hidden, and external functions cannot access it. Objects communicate with each other through methods New methods and data can be easily added whenever nece: + Follows the bottom-up approach in program design ry General OOPS concepts in Java: Objects and Classes > vy ww ol ts are runtime entities in an object-oriented system. An object can represent a person, :t bank account, a place, a table of data, Any programming problem is analysed based on objects and how they communicate amongst themselves. ‘The objects interact with cach other by sending messages to one another when a program is executed. For Example, ‘customer’ and ‘account’ are two objects that may send a message to the account object requesting for the balance. Each object contains code and data to manipulate the data, Objects can even interact without knowing the details of each other's code or data, The entire set of code and data of an object can be made user-defined data type using the concept of the class. A class is a *data-type’ and an object as a ‘variable’ of that type. Any number of objects can be created after a class is created. The collection of objects of similar types is termed as a class. For Example, apple, orange, and mango are the objects of the class Fruit. Classes behave like built-in data types of a programming language bat are user-defined data types. Representation of an Object Data Abstraction and Encapsulation The wrapping up of the data and methods into the single unit is known as Encapsulation. The data is accessible only t0 those methods, which are wrapped in the class, and not to the outside world. ‘This insulation of data from the direct access of the program is called Data hiding. Information “out Encapsula ion- Objects as “black-boxes™ Abstraction is the act of reducing programming complexity by representing essential features without including the background explanations or details, Classes wrap or encapsulate all the essential properties of the objects that are to be created. Inheritance > Inheritance is the process by which objects of ane class uequire some properties of objects of another class, Inheritance supports the concept of hierarchical classification, In OOP, the idea of inheritance provides the concept of reusability. {1 means that we can add additional features to parent class without modification; this is possible by deriving a new class from the parent class. > The new class consists of the combined features from both the classes. In Java, the derived class is also known as the subclass, y For Example, a bird Robin is part of the class, not a mammal, which is again a part of the class Animal. ‘The principle behind this division is that each subclass shares common characteristics from the class from its parent class. Properties of Inheritance > Types of Inheritance + Single + Multiple + Multilevel + Hybrid Polymorphism > Polymorphism means the ability to take many forms. For Example, an operation exhibits different behavior in different situations. » Example: A single function name can be used to handle the different numbers and different types of arguments. Posts iene ck Doan) cr) > In polymorphism, objects having different internal structures can share the same external interface, > Inheritance extensively uses the concept of polymorphism. > Polymorphism can be achieved in two ways: * Method Overloading © Method Overriding ‘Dynamic Binding > Binding is the process of linking a procedure eall to the code to be executed in response to the call. > Tt means that the code associated with the given procedure call is not known until the time of the call at runtime. > Itis associated with inheritance and polymorphism. Message Communication > Objects communicate with each other in OOPs. The process of programming in case of OOP consists of the following: + Creating classes defining objects and their behavior. + Creating objects «Establishing communication between objects. ‘The network of Objects Communicating with Each Other > Specifying the object name, the method name, and the information to be sent is involved in message passing. > Objects can be created or [Link] they havea life cycle, It allows communication between the objects until the objects are alive. Benefits of OOPs + Inheritance eliminates redundant code and enables reusability. + As Message passing allows communication with objects, this presents writing code from scratch every time. It is thus saving development time and higher productivity. + The principle of data hiding helps the programmer to build secure programs that cannot be invaded by a code in other parts of the program. + Ibis possible to have multiple objects to coexist without any interference. + Ibis easy to Partitions work in a project based on classes and objects. + Systems up-gradation is easy from small to larger system. + Software complexity can be easily managed. Applications of OOPs + Real-time systems ‘+ Simulation and modeling * Object-oriented databases + Hypertext and Hypermedia + Aland expert systems + Neural networks and paralle! programming + Decision support and office Automation systems. * CIM/CADI/CAD System. HISTORY > v v v Java is the general purpose, true object oriented programming language and is highly suitable for modeling the real world and solving the real world problems. In the company Sun Microsystem, James Goslings(an employee there), started a project ramed ,GREEN" So James Goslings started to develop a new language known as “OAK, Inmay 1995, Sun officially announced this language at Sunworld [Link] to some reasons, the name was changed to “JAVA”, The prime motive of Java was the need for a platform independent language. The second motive was to design a language which is “Intemet Enable". To run the programs on internet, Green project team come up with the idea of developing “Web Applet”. The team developed a web browser called “Hot Java” to locate and nin applet programs on internet, The most striking feature of Java is “Platform neutralness”, Java is the first language that is not tied to any particular hardware or 0.8. JAVA MILESTONES. YEAR | DEVELOPMENT 1990 | Sun Microsystem started to develop special software for electronic devices 1991 _ | James Goslings developed a new language “OAK™. 1992 _| New language Oak was demonstrated in hand held devices. to graphical environment, Sun developed Applets. 1993 | World Wide Web(WWW)appeared on internet and transformed the text based intemet 1994 _| Green project team developed a web browser “Wot Java” fo nin applets on internet, 1995 | Ouk was renamed to JAVA. 1996 | Java established itself as the leader of internet programming. Sun released Java development kit 1.0. 1997 _| Sun released Java development kit 1.10DK 1.1). 1998 _| Sun released Java? with version 1_2(SDK 1-2). 1999 _| Sun released Java2 standard edition (J2SE) and Enterprise Edition (J2BF). 2000 | J2SE with SDK 1.3 was released. 2002 | J2SE with SDK 14 was released. 2004 | J2SE with JDK 5.0 was released. Features of Java Some following Features of Java are given below: 1, Simple and Small 2. Compiled and Interpreted 3, Platform-Independent and Portable 4, Object-Oriented 5, Distributed 6, Multithreaded 7, Dynamic and Extensible 8, High performance 9, Ease of Development 10, Scalability 11, Monitoring and Manageability 12, Desktop Client 1. Simple and Small : Java is a small and simple language, Many features of C and C++ that are either redundant or sources of unreliable code are not part of Java, Such as Java does not use pointers, preprocessor header files, goto statement and many others. It also eliminates operator overloading and multiple inheritances. 2, Compiled and Interpreted : Generally a computer language is either compiled or interpreted, Java combines both these approaches thus making java is a two-stage system. First, Java compiler translates source code into bytecode instruction, Bytecode instructions are not machine instructions. In the second stage, Java interpreter generates machine code that can be directly executed by the machine that is running the java program. So, We can say that Java is both Compiled and Interpreted Language. 3. Platform-Independent and Portable Java ensures portability in two ways, first, Java compiler generates bytecode instructions that can be implemented on any machine. Second, the size of the primitive data types is Machine-Independent. The most significant contribution of java over other languages is it portability. Java programs can be casily moved fiom one computer system to another. 4, Object-Oriented : Java is a true object-oriented 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 classes, arranged in packages. 5. Distributed : Java is designed as a distributed language for creating applications on networks. It can share both data and programs. Java applications can open and access remote objects on the Internet as e: can do in a local system. This enables multiple programs at multiple remote locations to collaborate and work together on a single project, 6. Multithreaded : Multithreaded means that handling multiple tasks simultancously. Java supports multithreaded programs. This means that we need not wait for the application to finish one task before beginning another. 7. Dynamic and Extensible : Java is a dynamic language, Java is also 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. 8. High performance : Java performance is impressive for an interpreted language, it mainly due to the use of imermediate bytecode. According to Sun, Java speed is Comparable to the native C/C++. Java architecture is also designed to reduce overheads during run-time. 9. Ease of Development : Java 2 Standard Edition (J2SE) 5.0 supports features — Generics, Enhanced for Loop, Autoboxing or Unboxing, Typesafe Enums, Static import and Annotation. These features reduce the work of a programmer by shifting the responsibility of creating 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. : J2SE 5.0 assures a significant increase in scalability by improving the startup time and reducing the amount of memory used in Java 2 runtime environment. 11, Monitoring and Manageability : Java supports several 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 manage Java applications. 12, Desktop Client desktop client users. It provides an improved Swing look and feels called Ocean. This feature is mainly used for + J2SE 5.0 provides enhanced features to meet the requirements and challenges of the Java developing graphics applications that require OpenGL hardware accelera C Programming “Tt does include the unique statement keywords sizeof, and typedef. Java Programming It does not include the C unique statement keywords sizeof, and typedef. Ticontain the data type struct and union. It does not contain the data type struct and union, It define the type modifiers keywords auto, extern, register, signed, and unsigned. It does not define the type modifiers keywords auto, exter, register, signed, and unsigned. It supports an explicit pointer type. It does not support an explicit pointer type. It has a preprocessor and therefore we can use define, # include, and # ifdef statements. It does not havea preprocessor and therefore we cannot use # define, # include, and # ifdef statements, ‘Te requires that the functions with no arguments, with the void keyword It requires that the functions with no arguments must — be declared with empty parenthesis, not with the void keyword Chas no operators such as instanceof and >>>. Java adds new operators such as instanceof and >>>. Cadds havea break and continue statements. Java adds labeled break and continue statements. Chas no object-oriented programming features. Java adds many features required for object-oriented programming. el ¢ Java does not support operator overloading. * Java does not have template classes as in C++. * Java does not support multiple inheritances of classes. This is accomplished using a new feature called “Interface”. Java does not support pike) variables. Every variable and method is declared within classes and forms part of that class. » Java does not use pointers. Java has replaced the destructor function with a finalize() function. © There are no header files in Java. (C++ Programming, ee Java Programming It support operator overloading. It does not support operator overloading. It support has template classes. It does not have template classes as in C++. It supports multiple inheritances of classes. It does not support multiple inheritances of classes. This is accomplished using a new feature called “Interface”. It supports global variables. It does not support global variables. Every variable and method is declared within classes and forms part of that class. It supports pointers. It does not support destructor function with a finalize() function. It does not use pointers. It has replaced the destructor function with a finalize() function. There are header files in Java. There are no header files in Java. Java and Internet Java is strongly associated with the internet because of the first application program is written in Java was hot Java. Web browsers to run applets on the internet. Internet users can use Java to create applet programs & run then locally using a Java-enabled browser such as hot Java. Java applets have made the internet a true extension of the storage system of the local computer. Remote computer Local computer Java and Internet \ World wide web and internet World wide web is a collection of information stored on internet computers. World wide web is an information retrieval system designed to be used in the internet's distributed environment. World wide web contains web pages that provide both information and controls. Web pages contain HTML tags that enable us to find retrieve, manipulate and display documents world wide. Before Java, the world wide web was limited to the display of still images & texts. With the help of Java WWW is capable of supporting animation graphics, games and wide rage special effects. Usert Computer Remote Computer source program Applet source code! HTML Document Applet tag web browser | —~s[web server] Java and World Wide Web (www) Java communicates with a web page through a special tag called applet . Java user sends a request for an HTML document to the remote computers net browser. The web-browser is a program that accepts a request, processes the request and sends the required documents. The HTML document is returned to that user browser. The document contains the applet tag which identifies the applet. The corresponding applet is transferred to the user computer. The Java enabled browser on the user's computer interprets the byte code and provide output. Web Browsers The internet is a vast sea of information represented in many formats and stored on many computers. a browser is a software application used to locate, retrieve and display content on the World Wide Web, including Web pages, images, video and other files. As a client/server model, the browser is the client run on a computer that contacts the Web server and requests information. The Web server sends the information back to the Web browser which displays the results. The browser application retrieves or fetches code, usually written in HTML (HyperText Markup Language) and/or another language, from a web server, interprets this code, and renders (displays) it as a Web page for you to view. on the computer or another Internet-enabled device that supports a browser. \ J An example of Web Browsers: Hot Java Netscape Navigator Internet Explorer Google Chrome JAVA ENVIRONMENT = Java environmentincludes development tools and many classes and methods. Java Environment JsL JDK (Java Standard Library) (Java Development Kit) or Application oa Interface Development Classes and tools methods ey (AVA DEVELOPMENT KIT) JDK is collection of tools used for developingand running Java programs. They include appletviewer = for viewing Java applets javac : Java compiler which translates Java source code to byte code files that the interpreter can understand iva : iva interpreter which runs applets & applications by interpreting byte codes. Javadoc - Creates HTML format documentation from java source code files javah : Produces header files for use with methods jdb . Java debugger, which helps to find errors in programs These tools are used to build and run application programs. rN APPLICATION PROGRAMMING INTERFACE ‘The API includes hundreds of classes and methods grouped into several packages. Commonly used packages are: [Link] Language Support Package + required for basic features of ava iJavacutil Ucllties Package - classes that provide functions like date and time functions javaio InpuvOurpur Package - classes required for input/output [Link] Swing Package = common GUI elements like dialog box [Link] Networking Package - classes for communicating with other computers through network javaawe AWT Package + classes that allow GUI elements and graphics [Link] Applet Package + classes that allows to create Java applets JAVA VIRTUAL MACHINE Jaa | [ise Comper > ita tachine Program Bytecove Byte code | +[ ova Inerreter ‘Machine cooe Van maetwe Byte code is generated for Java Virtual machine. JVM is not a machine but a program that resides in computer memory. The byte code is common for all machines, Java interpreter acts as a link between particular machine and byte code to make machine code (machine language). Overview of Java Language Java isa general purpose object oriented programming langage. We can develop nwo types of java programs: » Stand — alone applications > Web applets Stand alone applications:- Stand — alone application are programs written in java to carry out certain tasks on a stand — 1 invelves two steps alone local computer. Executing a stand ~alone java pro} 1. Compiling source code into byte code using javac compiler, 2. Executing the byte code program using java interpreter. class Simple { public je void main(String args{){ [Link]("Hella Java"), ) 1, class keyword is used to declare a class in java, 2. public keyword is an access modifier which represents visibility, It means itis visible to all. 3. static isa keyword. If'we declare any method as static it is known as the static method, The core advantage of the static method is that there is no need (o create an object to invoke the static method, ‘The main method is executed by the J¥M, so it doesn't require to create an object to invoke the main method. So it saves memory. void is the return type of the method. It means it doesn't return any value. main represents the starting point of the program, String{] ai [Link]() is used to print statement, Here, System isa class, out is the object of PrintStream class, printin() is the method of PrintStream class, We will learn about the internal working of [Link]. printin statement later. 9s is used for command line argument, We will learn it later, awe Java Program to illustrate the use of Rectangle class which has length and width data members class Rectangle| int lenge int width; void insert(int Lint w)| void calculateArea()([Link]. printIn(length* width);) 1 class TestRectangle2{ public static void main(String args(]){ Rectangle rl=new Rectangle(),r2=new Rectangle() /creating two objects rLinsemt(11,5 r2insert(3,15) [Link](); P2ealculateArea(); } } Ontput: 35 45 Java Program Structure A Java program may contain many classes of which only one class defines the main method. Classes contain data members and methods that operate on the data members of the class. Methods may contain data type declaration and executable statements. To write a java program, we first define class s and then put them together. A Java program may contain one or more section are shown as following in Fig: <= seezesit <— Orton Faqs kave Suture oF lava Program Documentation Section :- The documentation section comprises a set of comment lines giving the name of the program, the author and other details, which the programmer would ike to refer to at a later stage, Comments must explain why a what of chisses and how of algorithms, This would greatly help in maintaining the program. in addition to the two styles of comment like “single line comment” and “double line comment”, Java also uses a third style comment /**.....*/ known as documentation comment. This form of comment is used for generating documentation automatically. Package Statement :- ‘The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the classes defined here belong to this package. Example: package stude ‘The package statement is optional, That is, our classes do not have to be part ofa package. Import Statement :- ‘The next thing aftera package statement (but before any class definition) may be a number of import statements. This is similar to the #include statement in C. Example, import [Link]; ‘This statement instructs the interpreter to load the test class contained in the package stuclent, Using import statement, we can have access (o classes that are part of other named packages. Interface Statement :- An interfice is like a class but includes a group of method declarations. This is also an optional section and is, used only when we wish to implement the multiple inheritance feature in the program. Class Definitions :- A Java progrim may contain multiple class definitions, Classes are the primary and essential elements of a Java program. These classes are used to map the objects of real-world problems, The number of classes used depends on the complexity of the problem. Main Method Class : Since every Java stand-alone program requires a main method as its starting point, this class is the essential part of Java program, A simple Java program may contain only this part, The main method creates objects of various classes and establishes communications between them. On reaching the end of main, the program terminates and the control passes back to the operating system. Java Tokens A token is the smallest element of program that is meaningful to the compiler. Tokens can be classified as follows: 1, Keywords 2, Mentifiers 3. Constants 4, Special Symbols 5. Operators Keyword: Keywords are pre-defined or reserved words ina programming language. Each keyword is meant to perform a specific function in a program. abstract viod boolean break byte case catch char —_ class const continue default do double else enum exports extends final finally float for goto if Identifiers: Identifiers are used as the general terminology for naming of variables, functions and arrays. Examples of valid identifiers : ‘MyVariable MYVARIABLE myvariable Constants/Literals: Constants are also like normal variables. But, the only difference is, their values can not be modified by the program once they are defined. Constants refer to fixed values. They are also called as literals. Special Symbols: The following special symbols are used in Java having some special meaning and thus, cannot be used for some other purpose. The Special symbols are (10 (}.:* = Operators: Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. Some of the types are- Arithmetic Operators, Unary Operators, Assignment Operator, Relational Operators, Logical Operators Ternary Operator, Bitwise Operators, Shift Operators, instance of operator, Precedence and Associativity Period (.): It separates the packnge name form the sub-packages and class, It also separates a variable or method from a reference variable, Comments: Comments allow us to specify information about the program inside our Java code. Java compiler recognizes these comments as tokens but excludes it form further processing. The Java compiler treats comments as whitespaces, Jaya provides the following two types of comment © Line Oriented: It begins with a pair of forwarding slashes (/). © Block-Oriented: It begins with /* and continues until it founds */. JAVA STATEMENT: Implementing Java Program Implementation of a Java application program involves a series of steps. They include : + Creating the program + Compiling the program + Running the program Creating the program We can create « program using any text editor, Assume that we have entered the following program : class Javaapp { public static void main(String[] args) { [Link]("Wieome to Java"); ) ) We must save this program in a file called Javaapp,java ensuring that the file name contains the class name properly. This file is called the souree fite, Note that all Java source files will have the extension java, Compiling the program ‘To compile the program, we must run the Java Compiler javac, with the name of the source file on the ‘command line the javae compiler creates a file called [Link] containing the bytecodes of the program, Note that the compiler automatically names the bytecode file as .class, To compile the Program, Syntax : Javae filename , Running the program To run the program, we must run the Java interpreter Syntax: Java Filename ‘a, with the name of the class file on the command line Java Virtual Machine: All language compilers translate Source code into machine code for a specific computer, The Java compiler produce an intermediate code known as byte code as Byre cade fora machine that does not exist, The machine is called the Java Virtual Machine (JVM) and its only exist only inside the computer memory. ‘Java Program >[ Java Compiter Virtual Machine Source Code Bytecode Process of Compilation Bytecode _|—»[_Java Interpreter }—»[_Machine Code Virtual Machine Real Machino Process of Convarting bytecode into machine code The JVM which in tum acts as the intermediary the Operating System and Java Object Frame Work. Java Program Java Compiler PL Java API Platform Java Virtual Machine Hardware Based Platform

You might also like